conversion.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.arrowFunctionToExpression = arrowFunctionToExpression;
  6. exports.ensureBlock = ensureBlock;
  7. exports.ensureFunctionName = ensureFunctionName;
  8. exports.splitExportDeclaration = splitExportDeclaration;
  9. exports.toComputedKey = toComputedKey;
  10. exports.unwrapFunctionEnvironment = unwrapFunctionEnvironment;
  11. var _t = require("@babel/types");
  12. var _template = require("@babel/template");
  13. var _visitors = require("../visitors.js");
  14. var _context = require("./context.js");
  15. const {
  16. arrowFunctionExpression,
  17. assignmentExpression,
  18. binaryExpression,
  19. blockStatement,
  20. callExpression,
  21. conditionalExpression,
  22. expressionStatement,
  23. identifier,
  24. isIdentifier,
  25. jsxIdentifier,
  26. logicalExpression,
  27. LOGICAL_OPERATORS,
  28. memberExpression,
  29. metaProperty,
  30. numericLiteral,
  31. objectExpression,
  32. restElement,
  33. returnStatement,
  34. sequenceExpression,
  35. spreadElement,
  36. stringLiteral,
  37. super: _super,
  38. thisExpression,
  39. toExpression,
  40. unaryExpression,
  41. toBindingIdentifierName,
  42. isFunction,
  43. isAssignmentPattern,
  44. isRestElement,
  45. getFunctionName,
  46. cloneNode,
  47. variableDeclaration,
  48. variableDeclarator,
  49. exportNamedDeclaration,
  50. exportSpecifier,
  51. inherits
  52. } = _t;
  53. function toComputedKey() {
  54. let key;
  55. if (this.isMemberExpression()) {
  56. key = this.node.property;
  57. } else if (this.isProperty() || this.isMethod()) {
  58. key = this.node.key;
  59. } else {
  60. throw new ReferenceError("todo");
  61. }
  62. if (!this.node.computed) {
  63. if (isIdentifier(key)) key = stringLiteral(key.name);
  64. }
  65. return key;
  66. }
  67. function ensureBlock() {
  68. const body = this.get("body");
  69. const bodyNode = body.node;
  70. if (Array.isArray(body)) {
  71. throw new Error("Can't convert array path to a block statement");
  72. }
  73. if (!bodyNode) {
  74. throw new Error("Can't convert node without a body");
  75. }
  76. if (body.isBlockStatement()) {
  77. return bodyNode;
  78. }
  79. const statements = [];
  80. let stringPath = "body";
  81. let key;
  82. let listKey;
  83. if (body.isStatement()) {
  84. listKey = "body";
  85. key = 0;
  86. statements.push(body.node);
  87. } else {
  88. stringPath += ".body.0";
  89. if (this.isFunction()) {
  90. key = "argument";
  91. statements.push(returnStatement(body.node));
  92. } else {
  93. key = "expression";
  94. statements.push(expressionStatement(body.node));
  95. }
  96. }
  97. this.node.body = blockStatement(statements);
  98. const parentPath = this.get(stringPath);
  99. _context.setup.call(body, parentPath, listKey ? parentPath.node[listKey] : parentPath.node, listKey, key);
  100. return this.node;
  101. }
  102. {
  103. exports.arrowFunctionToShadowed = function () {
  104. if (!this.isArrowFunctionExpression()) return;
  105. this.arrowFunctionToExpression();
  106. };
  107. }
  108. function unwrapFunctionEnvironment() {
  109. if (!this.isArrowFunctionExpression() && !this.isFunctionExpression() && !this.isFunctionDeclaration()) {
  110. throw this.buildCodeFrameError("Can only unwrap the environment of a function.");
  111. }
  112. hoistFunctionEnvironment(this);
  113. }
  114. function setType(path, type) {
  115. path.node.type = type;
  116. }
  117. function arrowFunctionToExpression({
  118. allowInsertArrow = true,
  119. allowInsertArrowWithRest = allowInsertArrow,
  120. noNewArrows = !(_arguments$ => (_arguments$ = arguments[0]) == null ? void 0 : _arguments$.specCompliant)()
  121. } = {}) {
  122. if (!this.isArrowFunctionExpression()) {
  123. throw this.buildCodeFrameError("Cannot convert non-arrow function to a function expression.");
  124. }
  125. let self = this;
  126. if (!noNewArrows) {
  127. var _self$ensureFunctionN;
  128. self = (_self$ensureFunctionN = self.ensureFunctionName(false)) != null ? _self$ensureFunctionN : self;
  129. }
  130. const {
  131. thisBinding,
  132. fnPath: fn
  133. } = hoistFunctionEnvironment(self, noNewArrows, allowInsertArrow, allowInsertArrowWithRest);
  134. fn.ensureBlock();
  135. setType(fn, "FunctionExpression");
  136. if (!noNewArrows) {
  137. const checkBinding = thisBinding ? null : fn.scope.generateUidIdentifier("arrowCheckId");
  138. if (checkBinding) {
  139. fn.parentPath.scope.push({
  140. id: checkBinding,
  141. init: objectExpression([])
  142. });
  143. }
  144. fn.get("body").unshiftContainer("body", expressionStatement(callExpression(this.hub.addHelper("newArrowCheck"), [thisExpression(), checkBinding ? identifier(checkBinding.name) : identifier(thisBinding)])));
  145. fn.replaceWith(callExpression(memberExpression(fn.node, identifier("bind")), [checkBinding ? identifier(checkBinding.name) : thisExpression()]));
  146. return fn.get("callee.object");
  147. }
  148. return fn;
  149. }
  150. const getSuperCallsVisitor = (0, _visitors.environmentVisitor)({
  151. CallExpression(child, {
  152. allSuperCalls
  153. }) {
  154. if (!child.get("callee").isSuper()) return;
  155. allSuperCalls.push(child);
  156. }
  157. });
  158. function hoistFunctionEnvironment(fnPath, noNewArrows = true, allowInsertArrow = true, allowInsertArrowWithRest = true) {
  159. let arrowParent;
  160. let thisEnvFn = fnPath.findParent(p => {
  161. if (p.isArrowFunctionExpression()) {
  162. arrowParent != null ? arrowParent : arrowParent = p;
  163. return false;
  164. }
  165. return p.isFunction() || p.isProgram() || p.isClassProperty({
  166. static: false
  167. }) || p.isClassPrivateProperty({
  168. static: false
  169. });
  170. });
  171. const inConstructor = thisEnvFn.isClassMethod({
  172. kind: "constructor"
  173. });
  174. if (thisEnvFn.isClassProperty() || thisEnvFn.isClassPrivateProperty()) {
  175. if (arrowParent) {
  176. thisEnvFn = arrowParent;
  177. } else if (allowInsertArrow) {
  178. fnPath.replaceWith(callExpression(arrowFunctionExpression([], toExpression(fnPath.node)), []));
  179. thisEnvFn = fnPath.get("callee");
  180. fnPath = thisEnvFn.get("body");
  181. } else {
  182. throw fnPath.buildCodeFrameError("Unable to transform arrow inside class property");
  183. }
  184. }
  185. const {
  186. thisPaths,
  187. argumentsPaths,
  188. newTargetPaths,
  189. superProps,
  190. superCalls
  191. } = getScopeInformation(fnPath);
  192. if (inConstructor && superCalls.length > 0) {
  193. if (!allowInsertArrow) {
  194. throw superCalls[0].buildCodeFrameError("When using '@babel/plugin-transform-arrow-functions', " + "it's not possible to compile `super()` in an arrow function without compiling classes.\n" + "Please add '@babel/plugin-transform-classes' to your Babel configuration.");
  195. }
  196. if (!allowInsertArrowWithRest) {
  197. throw superCalls[0].buildCodeFrameError("When using '@babel/plugin-transform-parameters', " + "it's not possible to compile `super()` in an arrow function with default or rest parameters without compiling classes.\n" + "Please add '@babel/plugin-transform-classes' to your Babel configuration.");
  198. }
  199. const allSuperCalls = [];
  200. thisEnvFn.traverse(getSuperCallsVisitor, {
  201. allSuperCalls
  202. });
  203. const superBinding = getSuperBinding(thisEnvFn);
  204. allSuperCalls.forEach(superCall => {
  205. const callee = identifier(superBinding);
  206. callee.loc = superCall.node.callee.loc;
  207. superCall.get("callee").replaceWith(callee);
  208. });
  209. }
  210. if (argumentsPaths.length > 0) {
  211. const argumentsBinding = getBinding(thisEnvFn, "arguments", () => {
  212. const args = () => identifier("arguments");
  213. if (thisEnvFn.scope.path.isProgram()) {
  214. return conditionalExpression(binaryExpression("===", unaryExpression("typeof", args()), stringLiteral("undefined")), thisEnvFn.scope.buildUndefinedNode(), args());
  215. } else {
  216. return args();
  217. }
  218. });
  219. argumentsPaths.forEach(argumentsChild => {
  220. const argsRef = identifier(argumentsBinding);
  221. argsRef.loc = argumentsChild.node.loc;
  222. argumentsChild.replaceWith(argsRef);
  223. });
  224. }
  225. if (newTargetPaths.length > 0) {
  226. const newTargetBinding = getBinding(thisEnvFn, "newtarget", () => metaProperty(identifier("new"), identifier("target")));
  227. newTargetPaths.forEach(targetChild => {
  228. const targetRef = identifier(newTargetBinding);
  229. targetRef.loc = targetChild.node.loc;
  230. targetChild.replaceWith(targetRef);
  231. });
  232. }
  233. if (superProps.length > 0) {
  234. if (!allowInsertArrow) {
  235. throw superProps[0].buildCodeFrameError("When using '@babel/plugin-transform-arrow-functions', " + "it's not possible to compile `super.prop` in an arrow function without compiling classes.\n" + "Please add '@babel/plugin-transform-classes' to your Babel configuration.");
  236. }
  237. const flatSuperProps = superProps.reduce((acc, superProp) => acc.concat(standardizeSuperProperty(superProp)), []);
  238. flatSuperProps.forEach(superProp => {
  239. const key = superProp.node.computed ? "" : superProp.get("property").node.name;
  240. const superParentPath = superProp.parentPath;
  241. const isAssignment = superParentPath.isAssignmentExpression({
  242. left: superProp.node
  243. });
  244. const isCall = superParentPath.isCallExpression({
  245. callee: superProp.node
  246. });
  247. const isTaggedTemplate = superParentPath.isTaggedTemplateExpression({
  248. tag: superProp.node
  249. });
  250. const superBinding = getSuperPropBinding(thisEnvFn, isAssignment, key);
  251. const args = [];
  252. if (superProp.node.computed) {
  253. args.push(superProp.get("property").node);
  254. }
  255. if (isAssignment) {
  256. const value = superParentPath.node.right;
  257. args.push(value);
  258. }
  259. const call = callExpression(identifier(superBinding), args);
  260. if (isCall) {
  261. superParentPath.unshiftContainer("arguments", thisExpression());
  262. superProp.replaceWith(memberExpression(call, identifier("call")));
  263. thisPaths.push(superParentPath.get("arguments.0"));
  264. } else if (isAssignment) {
  265. superParentPath.replaceWith(call);
  266. } else if (isTaggedTemplate) {
  267. superProp.replaceWith(callExpression(memberExpression(call, identifier("bind"), false), [thisExpression()]));
  268. thisPaths.push(superProp.get("arguments.0"));
  269. } else {
  270. superProp.replaceWith(call);
  271. }
  272. });
  273. }
  274. let thisBinding;
  275. if (thisPaths.length > 0 || !noNewArrows) {
  276. thisBinding = getThisBinding(thisEnvFn, inConstructor);
  277. if (noNewArrows || inConstructor && hasSuperClass(thisEnvFn)) {
  278. thisPaths.forEach(thisChild => {
  279. const thisRef = thisChild.isJSX() ? jsxIdentifier(thisBinding) : identifier(thisBinding);
  280. thisRef.loc = thisChild.node.loc;
  281. thisChild.replaceWith(thisRef);
  282. });
  283. if (!noNewArrows) thisBinding = null;
  284. }
  285. }
  286. return {
  287. thisBinding: thisBinding,
  288. fnPath
  289. };
  290. }
  291. function isLogicalOp(op) {
  292. return LOGICAL_OPERATORS.includes(op);
  293. }
  294. function standardizeSuperProperty(superProp) {
  295. if (superProp.parentPath.isAssignmentExpression() && superProp.parentPath.node.operator !== "=") {
  296. const assignmentPath = superProp.parentPath;
  297. const op = assignmentPath.node.operator.slice(0, -1);
  298. const value = assignmentPath.node.right;
  299. const isLogicalAssignment = isLogicalOp(op);
  300. if (superProp.node.computed) {
  301. const tmp = superProp.scope.generateDeclaredUidIdentifier("tmp");
  302. const {
  303. object,
  304. property
  305. } = superProp.node;
  306. assignmentPath.get("left").replaceWith(memberExpression(object, assignmentExpression("=", tmp, property), true));
  307. assignmentPath.get("right").replaceWith(rightExpression(isLogicalAssignment ? "=" : op, memberExpression(object, identifier(tmp.name), true), value));
  308. } else {
  309. const object = superProp.node.object;
  310. const property = superProp.node.property;
  311. assignmentPath.get("left").replaceWith(memberExpression(object, property));
  312. assignmentPath.get("right").replaceWith(rightExpression(isLogicalAssignment ? "=" : op, memberExpression(object, identifier(property.name)), value));
  313. }
  314. if (isLogicalAssignment) {
  315. assignmentPath.replaceWith(logicalExpression(op, assignmentPath.node.left, assignmentPath.node.right));
  316. } else {
  317. assignmentPath.node.operator = "=";
  318. }
  319. return [assignmentPath.get("left"), assignmentPath.get("right").get("left")];
  320. } else if (superProp.parentPath.isUpdateExpression()) {
  321. const updateExpr = superProp.parentPath;
  322. const tmp = superProp.scope.generateDeclaredUidIdentifier("tmp");
  323. const computedKey = superProp.node.computed ? superProp.scope.generateDeclaredUidIdentifier("prop") : null;
  324. const parts = [assignmentExpression("=", tmp, memberExpression(superProp.node.object, computedKey ? assignmentExpression("=", computedKey, superProp.node.property) : superProp.node.property, superProp.node.computed)), assignmentExpression("=", memberExpression(superProp.node.object, computedKey ? identifier(computedKey.name) : superProp.node.property, superProp.node.computed), binaryExpression(superProp.parentPath.node.operator[0], identifier(tmp.name), numericLiteral(1)))];
  325. if (!superProp.parentPath.node.prefix) {
  326. parts.push(identifier(tmp.name));
  327. }
  328. updateExpr.replaceWith(sequenceExpression(parts));
  329. const left = updateExpr.get("expressions.0.right");
  330. const right = updateExpr.get("expressions.1.left");
  331. return [left, right];
  332. }
  333. return [superProp];
  334. function rightExpression(op, left, right) {
  335. if (op === "=") {
  336. return assignmentExpression("=", left, right);
  337. } else {
  338. return binaryExpression(op, left, right);
  339. }
  340. }
  341. }
  342. function hasSuperClass(thisEnvFn) {
  343. return thisEnvFn.isClassMethod() && !!thisEnvFn.parentPath.parentPath.node.superClass;
  344. }
  345. const assignSuperThisVisitor = (0, _visitors.environmentVisitor)({
  346. CallExpression(child, {
  347. supers,
  348. thisBinding
  349. }) {
  350. if (!child.get("callee").isSuper()) return;
  351. if (supers.has(child.node)) return;
  352. supers.add(child.node);
  353. child.replaceWithMultiple([child.node, assignmentExpression("=", identifier(thisBinding), identifier("this"))]);
  354. }
  355. });
  356. function getThisBinding(thisEnvFn, inConstructor) {
  357. return getBinding(thisEnvFn, "this", thisBinding => {
  358. if (!inConstructor || !hasSuperClass(thisEnvFn)) return thisExpression();
  359. thisEnvFn.traverse(assignSuperThisVisitor, {
  360. supers: new WeakSet(),
  361. thisBinding
  362. });
  363. });
  364. }
  365. function getSuperBinding(thisEnvFn) {
  366. return getBinding(thisEnvFn, "supercall", () => {
  367. const argsBinding = thisEnvFn.scope.generateUidIdentifier("args");
  368. return arrowFunctionExpression([restElement(argsBinding)], callExpression(_super(), [spreadElement(identifier(argsBinding.name))]));
  369. });
  370. }
  371. function getSuperPropBinding(thisEnvFn, isAssignment, propName) {
  372. const op = isAssignment ? "set" : "get";
  373. return getBinding(thisEnvFn, `superprop_${op}:${propName || ""}`, () => {
  374. const argsList = [];
  375. let fnBody;
  376. if (propName) {
  377. fnBody = memberExpression(_super(), identifier(propName));
  378. } else {
  379. const method = thisEnvFn.scope.generateUidIdentifier("prop");
  380. argsList.unshift(method);
  381. fnBody = memberExpression(_super(), identifier(method.name), true);
  382. }
  383. if (isAssignment) {
  384. const valueIdent = thisEnvFn.scope.generateUidIdentifier("value");
  385. argsList.push(valueIdent);
  386. fnBody = assignmentExpression("=", fnBody, identifier(valueIdent.name));
  387. }
  388. return arrowFunctionExpression(argsList, fnBody);
  389. });
  390. }
  391. function getBinding(thisEnvFn, key, init) {
  392. const cacheKey = "binding:" + key;
  393. let data = thisEnvFn.getData(cacheKey);
  394. if (!data) {
  395. const id = thisEnvFn.scope.generateUidIdentifier(key);
  396. data = id.name;
  397. thisEnvFn.setData(cacheKey, data);
  398. thisEnvFn.scope.push({
  399. id: id,
  400. init: init(data)
  401. });
  402. }
  403. return data;
  404. }
  405. const getScopeInformationVisitor = (0, _visitors.environmentVisitor)({
  406. ThisExpression(child, {
  407. thisPaths
  408. }) {
  409. thisPaths.push(child);
  410. },
  411. JSXIdentifier(child, {
  412. thisPaths
  413. }) {
  414. if (child.node.name !== "this") return;
  415. if (!child.parentPath.isJSXMemberExpression({
  416. object: child.node
  417. }) && !child.parentPath.isJSXOpeningElement({
  418. name: child.node
  419. })) {
  420. return;
  421. }
  422. thisPaths.push(child);
  423. },
  424. CallExpression(child, {
  425. superCalls
  426. }) {
  427. if (child.get("callee").isSuper()) superCalls.push(child);
  428. },
  429. MemberExpression(child, {
  430. superProps
  431. }) {
  432. if (child.get("object").isSuper()) superProps.push(child);
  433. },
  434. Identifier(child, {
  435. argumentsPaths
  436. }) {
  437. if (!child.isReferencedIdentifier({
  438. name: "arguments"
  439. })) return;
  440. let curr = child.scope;
  441. do {
  442. if (curr.hasOwnBinding("arguments")) {
  443. curr.rename("arguments");
  444. return;
  445. }
  446. if (curr.path.isFunction() && !curr.path.isArrowFunctionExpression()) {
  447. break;
  448. }
  449. } while (curr = curr.parent);
  450. argumentsPaths.push(child);
  451. },
  452. MetaProperty(child, {
  453. newTargetPaths
  454. }) {
  455. if (!child.get("meta").isIdentifier({
  456. name: "new"
  457. })) return;
  458. if (!child.get("property").isIdentifier({
  459. name: "target"
  460. })) return;
  461. newTargetPaths.push(child);
  462. }
  463. });
  464. function getScopeInformation(fnPath) {
  465. const thisPaths = [];
  466. const argumentsPaths = [];
  467. const newTargetPaths = [];
  468. const superProps = [];
  469. const superCalls = [];
  470. fnPath.traverse(getScopeInformationVisitor, {
  471. thisPaths,
  472. argumentsPaths,
  473. newTargetPaths,
  474. superProps,
  475. superCalls
  476. });
  477. return {
  478. thisPaths,
  479. argumentsPaths,
  480. newTargetPaths,
  481. superProps,
  482. superCalls
  483. };
  484. }
  485. function splitExportDeclaration() {
  486. if (!this.isExportDeclaration() || this.isExportAllDeclaration()) {
  487. throw new Error("Only default and named export declarations can be split.");
  488. }
  489. if (this.isExportNamedDeclaration() && this.get("specifiers").length > 0) {
  490. throw new Error("It doesn't make sense to split exported specifiers.");
  491. }
  492. const declaration = this.get("declaration");
  493. if (this.isExportDefaultDeclaration()) {
  494. const standaloneDeclaration = declaration.isFunctionDeclaration() || declaration.isClassDeclaration();
  495. const exportExpr = declaration.isFunctionExpression() || declaration.isClassExpression();
  496. const scope = declaration.isScope() ? declaration.scope.parent : declaration.scope;
  497. let id = declaration.node.id;
  498. let needBindingRegistration = false;
  499. if (!id) {
  500. needBindingRegistration = true;
  501. id = scope.generateUidIdentifier("default");
  502. if (standaloneDeclaration || exportExpr) {
  503. declaration.node.id = cloneNode(id);
  504. }
  505. } else if (exportExpr && scope.hasBinding(id.name)) {
  506. needBindingRegistration = true;
  507. id = scope.generateUidIdentifier(id.name);
  508. }
  509. const updatedDeclaration = standaloneDeclaration ? declaration.node : variableDeclaration("var", [variableDeclarator(cloneNode(id), declaration.node)]);
  510. const updatedExportDeclaration = exportNamedDeclaration(null, [exportSpecifier(cloneNode(id), identifier("default"))]);
  511. this.insertAfter(updatedExportDeclaration);
  512. this.replaceWith(updatedDeclaration);
  513. if (needBindingRegistration) {
  514. scope.registerDeclaration(this);
  515. }
  516. return this;
  517. } else if (this.get("specifiers").length > 0) {
  518. throw new Error("It doesn't make sense to split exported specifiers.");
  519. }
  520. const bindingIdentifiers = declaration.getOuterBindingIdentifiers();
  521. const specifiers = Object.keys(bindingIdentifiers).map(name => {
  522. return exportSpecifier(identifier(name), identifier(name));
  523. });
  524. const aliasDeclar = exportNamedDeclaration(null, specifiers);
  525. this.insertAfter(aliasDeclar);
  526. this.replaceWith(declaration.node);
  527. return this;
  528. }
  529. const refersOuterBindingVisitor = {
  530. "ReferencedIdentifier|BindingIdentifier"(path, state) {
  531. if (path.node.name !== state.name) return;
  532. state.needsRename = true;
  533. path.stop();
  534. },
  535. Scope(path, state) {
  536. if (path.scope.hasOwnBinding(state.name)) {
  537. path.skip();
  538. }
  539. }
  540. };
  541. function ensureFunctionName(supportUnicodeId) {
  542. if (this.node.id) return this;
  543. const res = getFunctionName(this.node, this.parent);
  544. if (res == null) return this;
  545. let {
  546. name
  547. } = res;
  548. if (!supportUnicodeId && /[\uD800-\uDFFF]/.test(name)) {
  549. return null;
  550. }
  551. if (name.startsWith("get ") || name.startsWith("set ")) {
  552. return null;
  553. }
  554. name = toBindingIdentifierName(name.replace(/[/ ]/g, "_"));
  555. const id = identifier(name);
  556. inherits(id, res.originalNode);
  557. const state = {
  558. needsRename: false,
  559. name
  560. };
  561. const {
  562. scope
  563. } = this;
  564. const binding = scope.getOwnBinding(name);
  565. if (binding) {
  566. if (binding.kind === "param") {
  567. state.needsRename = true;
  568. } else {}
  569. } else if (scope.parent.hasBinding(name) || scope.hasGlobal(name)) {
  570. this.traverse(refersOuterBindingVisitor, state);
  571. }
  572. if (!state.needsRename) {
  573. this.node.id = id;
  574. {
  575. scope.getProgramParent().references[id.name] = true;
  576. }
  577. return this;
  578. }
  579. if (scope.hasBinding(id.name) && !scope.hasGlobal(id.name)) {
  580. scope.rename(id.name);
  581. this.node.id = id;
  582. {
  583. scope.getProgramParent().references[id.name] = true;
  584. }
  585. return this;
  586. }
  587. if (!isFunction(this.node)) return null;
  588. const key = scope.generateUidIdentifier(id.name);
  589. const params = [];
  590. for (let i = 0, len = getFunctionArity(this.node); i < len; i++) {
  591. params.push(scope.generateUidIdentifier("x"));
  592. }
  593. const call = _template.default.expression.ast`
  594. (function (${key}) {
  595. function ${id}(${params}) {
  596. return ${cloneNode(key)}.apply(this, arguments);
  597. }
  598. ${cloneNode(id)}.toString = function () {
  599. return ${cloneNode(key)}.toString();
  600. }
  601. return ${cloneNode(id)};
  602. })(${toExpression(this.node)})
  603. `;
  604. return this.replaceWith(call)[0].get("arguments.0");
  605. }
  606. function getFunctionArity(node) {
  607. const count = node.params.findIndex(param => isAssignmentPattern(param) || isRestElement(param));
  608. return count === -1 ? node.params.length : count;
  609. }
  610. //# sourceMappingURL=conversion.js.map