conversion.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  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. const {
  15. arrowFunctionExpression,
  16. assignmentExpression,
  17. binaryExpression,
  18. blockStatement,
  19. callExpression,
  20. conditionalExpression,
  21. expressionStatement,
  22. identifier,
  23. isIdentifier,
  24. jsxIdentifier,
  25. logicalExpression,
  26. LOGICAL_OPERATORS,
  27. memberExpression,
  28. metaProperty,
  29. numericLiteral,
  30. objectExpression,
  31. restElement,
  32. returnStatement,
  33. sequenceExpression,
  34. spreadElement,
  35. stringLiteral,
  36. super: _super,
  37. thisExpression,
  38. toExpression,
  39. unaryExpression,
  40. toBindingIdentifierName,
  41. isFunction,
  42. isAssignmentPattern,
  43. isRestElement,
  44. getFunctionName,
  45. cloneNode,
  46. variableDeclaration,
  47. variableDeclarator,
  48. exportNamedDeclaration,
  49. exportSpecifier,
  50. inherits
  51. } = _t;
  52. function toComputedKey() {
  53. let key;
  54. if (this.isMemberExpression()) {
  55. key = this.node.property;
  56. } else if (this.isProperty() || this.isMethod()) {
  57. key = this.node.key;
  58. } else {
  59. throw new ReferenceError("todo");
  60. }
  61. if (!this.node.computed) {
  62. if (isIdentifier(key)) key = stringLiteral(key.name);
  63. }
  64. return key;
  65. }
  66. function ensureBlock() {
  67. const body = this.get("body");
  68. const bodyNode = body.node;
  69. if (Array.isArray(body)) {
  70. throw new Error("Can't convert array path to a block statement");
  71. }
  72. if (!bodyNode) {
  73. throw new Error("Can't convert node without a body");
  74. }
  75. if (body.isBlockStatement()) {
  76. return bodyNode;
  77. }
  78. const statements = [];
  79. let stringPath = "body";
  80. let key;
  81. let listKey;
  82. if (body.isStatement()) {
  83. listKey = "body";
  84. key = 0;
  85. statements.push(body.node);
  86. } else {
  87. stringPath += ".body.0";
  88. if (this.isFunction()) {
  89. key = "argument";
  90. statements.push(returnStatement(body.node));
  91. } else {
  92. key = "expression";
  93. statements.push(expressionStatement(body.node));
  94. }
  95. }
  96. this.node.body = blockStatement(statements);
  97. const parentPath = this.get(stringPath);
  98. body.setup(parentPath, listKey ? parentPath.node[listKey] : parentPath.node, listKey, key);
  99. return this.node;
  100. }
  101. {
  102. exports.arrowFunctionToShadowed = function () {
  103. if (!this.isArrowFunctionExpression()) return;
  104. this.arrowFunctionToExpression();
  105. };
  106. }
  107. function unwrapFunctionEnvironment() {
  108. if (!this.isArrowFunctionExpression() && !this.isFunctionExpression() && !this.isFunctionDeclaration()) {
  109. throw this.buildCodeFrameError("Can only unwrap the environment of a function.");
  110. }
  111. hoistFunctionEnvironment(this);
  112. }
  113. function setType(path, type) {
  114. path.node.type = type;
  115. }
  116. function arrowFunctionToExpression({
  117. allowInsertArrow = true,
  118. allowInsertArrowWithRest = allowInsertArrow,
  119. noNewArrows = !(_arguments$ => (_arguments$ = arguments[0]) == null ? void 0 : _arguments$.specCompliant)()
  120. } = {}) {
  121. if (!this.isArrowFunctionExpression()) {
  122. throw this.buildCodeFrameError("Cannot convert non-arrow function to a function expression.");
  123. }
  124. let self = this;
  125. if (!noNewArrows) {
  126. var _self$ensureFunctionN;
  127. self = (_self$ensureFunctionN = self.ensureFunctionName(false)) != null ? _self$ensureFunctionN : self;
  128. }
  129. const {
  130. thisBinding,
  131. fnPath: fn
  132. } = hoistFunctionEnvironment(self, noNewArrows, allowInsertArrow, allowInsertArrowWithRest);
  133. fn.ensureBlock();
  134. setType(fn, "FunctionExpression");
  135. if (!noNewArrows) {
  136. const checkBinding = thisBinding ? null : fn.scope.generateUidIdentifier("arrowCheckId");
  137. if (checkBinding) {
  138. fn.parentPath.scope.push({
  139. id: checkBinding,
  140. init: objectExpression([])
  141. });
  142. }
  143. fn.get("body").unshiftContainer("body", expressionStatement(callExpression(this.hub.addHelper("newArrowCheck"), [thisExpression(), checkBinding ? identifier(checkBinding.name) : identifier(thisBinding)])));
  144. fn.replaceWith(callExpression(memberExpression(fn.node, identifier("bind")), [checkBinding ? identifier(checkBinding.name) : thisExpression()]));
  145. return fn.get("callee.object");
  146. }
  147. return fn;
  148. }
  149. const getSuperCallsVisitor = (0, _visitors.environmentVisitor)({
  150. CallExpression(child, {
  151. allSuperCalls
  152. }) {
  153. if (!child.get("callee").isSuper()) return;
  154. allSuperCalls.push(child);
  155. }
  156. });
  157. function hoistFunctionEnvironment(fnPath, noNewArrows = true, allowInsertArrow = true, allowInsertArrowWithRest = true) {
  158. let arrowParent;
  159. let thisEnvFn = fnPath.findParent(p => {
  160. if (p.isArrowFunctionExpression()) {
  161. var _arrowParent;
  162. (_arrowParent = 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,
  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 object = superProp.node.object;
  303. const property = superProp.node.property;
  304. assignmentPath.get("left").replaceWith(memberExpression(object, assignmentExpression("=", tmp, property), true));
  305. assignmentPath.get("right").replaceWith(rightExpression(isLogicalAssignment ? "=" : op, memberExpression(object, identifier(tmp.name), true), value));
  306. } else {
  307. const object = superProp.node.object;
  308. const property = superProp.node.property;
  309. assignmentPath.get("left").replaceWith(memberExpression(object, property));
  310. assignmentPath.get("right").replaceWith(rightExpression(isLogicalAssignment ? "=" : op, memberExpression(object, identifier(property.name)), value));
  311. }
  312. if (isLogicalAssignment) {
  313. assignmentPath.replaceWith(logicalExpression(op, assignmentPath.node.left, assignmentPath.node.right));
  314. } else {
  315. assignmentPath.node.operator = "=";
  316. }
  317. return [assignmentPath.get("left"), assignmentPath.get("right").get("left")];
  318. } else if (superProp.parentPath.isUpdateExpression()) {
  319. const updateExpr = superProp.parentPath;
  320. const tmp = superProp.scope.generateDeclaredUidIdentifier("tmp");
  321. const computedKey = superProp.node.computed ? superProp.scope.generateDeclaredUidIdentifier("prop") : null;
  322. 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)))];
  323. if (!superProp.parentPath.node.prefix) {
  324. parts.push(identifier(tmp.name));
  325. }
  326. updateExpr.replaceWith(sequenceExpression(parts));
  327. const left = updateExpr.get("expressions.0.right");
  328. const right = updateExpr.get("expressions.1.left");
  329. return [left, right];
  330. }
  331. return [superProp];
  332. function rightExpression(op, left, right) {
  333. if (op === "=") {
  334. return assignmentExpression("=", left, right);
  335. } else {
  336. return binaryExpression(op, left, right);
  337. }
  338. }
  339. }
  340. function hasSuperClass(thisEnvFn) {
  341. return thisEnvFn.isClassMethod() && !!thisEnvFn.parentPath.parentPath.node.superClass;
  342. }
  343. const assignSuperThisVisitor = (0, _visitors.environmentVisitor)({
  344. CallExpression(child, {
  345. supers,
  346. thisBinding
  347. }) {
  348. if (!child.get("callee").isSuper()) return;
  349. if (supers.has(child.node)) return;
  350. supers.add(child.node);
  351. child.replaceWithMultiple([child.node, assignmentExpression("=", identifier(thisBinding), identifier("this"))]);
  352. }
  353. });
  354. function getThisBinding(thisEnvFn, inConstructor) {
  355. return getBinding(thisEnvFn, "this", thisBinding => {
  356. if (!inConstructor || !hasSuperClass(thisEnvFn)) return thisExpression();
  357. thisEnvFn.traverse(assignSuperThisVisitor, {
  358. supers: new WeakSet(),
  359. thisBinding
  360. });
  361. });
  362. }
  363. function getSuperBinding(thisEnvFn) {
  364. return getBinding(thisEnvFn, "supercall", () => {
  365. const argsBinding = thisEnvFn.scope.generateUidIdentifier("args");
  366. return arrowFunctionExpression([restElement(argsBinding)], callExpression(_super(), [spreadElement(identifier(argsBinding.name))]));
  367. });
  368. }
  369. function getSuperPropBinding(thisEnvFn, isAssignment, propName) {
  370. const op = isAssignment ? "set" : "get";
  371. return getBinding(thisEnvFn, `superprop_${op}:${propName || ""}`, () => {
  372. const argsList = [];
  373. let fnBody;
  374. if (propName) {
  375. fnBody = memberExpression(_super(), identifier(propName));
  376. } else {
  377. const method = thisEnvFn.scope.generateUidIdentifier("prop");
  378. argsList.unshift(method);
  379. fnBody = memberExpression(_super(), identifier(method.name), true);
  380. }
  381. if (isAssignment) {
  382. const valueIdent = thisEnvFn.scope.generateUidIdentifier("value");
  383. argsList.push(valueIdent);
  384. fnBody = assignmentExpression("=", fnBody, identifier(valueIdent.name));
  385. }
  386. return arrowFunctionExpression(argsList, fnBody);
  387. });
  388. }
  389. function getBinding(thisEnvFn, key, init) {
  390. const cacheKey = "binding:" + key;
  391. let data = thisEnvFn.getData(cacheKey);
  392. if (!data) {
  393. const id = thisEnvFn.scope.generateUidIdentifier(key);
  394. data = id.name;
  395. thisEnvFn.setData(cacheKey, data);
  396. thisEnvFn.scope.push({
  397. id: id,
  398. init: init(data)
  399. });
  400. }
  401. return data;
  402. }
  403. const getScopeInformationVisitor = (0, _visitors.environmentVisitor)({
  404. ThisExpression(child, {
  405. thisPaths
  406. }) {
  407. thisPaths.push(child);
  408. },
  409. JSXIdentifier(child, {
  410. thisPaths
  411. }) {
  412. if (child.node.name !== "this") return;
  413. if (!child.parentPath.isJSXMemberExpression({
  414. object: child.node
  415. }) && !child.parentPath.isJSXOpeningElement({
  416. name: child.node
  417. })) {
  418. return;
  419. }
  420. thisPaths.push(child);
  421. },
  422. CallExpression(child, {
  423. superCalls
  424. }) {
  425. if (child.get("callee").isSuper()) superCalls.push(child);
  426. },
  427. MemberExpression(child, {
  428. superProps
  429. }) {
  430. if (child.get("object").isSuper()) superProps.push(child);
  431. },
  432. Identifier(child, {
  433. argumentsPaths
  434. }) {
  435. if (!child.isReferencedIdentifier({
  436. name: "arguments"
  437. })) return;
  438. let curr = child.scope;
  439. do {
  440. if (curr.hasOwnBinding("arguments")) {
  441. curr.rename("arguments");
  442. return;
  443. }
  444. if (curr.path.isFunction() && !curr.path.isArrowFunctionExpression()) {
  445. break;
  446. }
  447. } while (curr = curr.parent);
  448. argumentsPaths.push(child);
  449. },
  450. MetaProperty(child, {
  451. newTargetPaths
  452. }) {
  453. if (!child.get("meta").isIdentifier({
  454. name: "new"
  455. })) return;
  456. if (!child.get("property").isIdentifier({
  457. name: "target"
  458. })) return;
  459. newTargetPaths.push(child);
  460. }
  461. });
  462. function getScopeInformation(fnPath) {
  463. const thisPaths = [];
  464. const argumentsPaths = [];
  465. const newTargetPaths = [];
  466. const superProps = [];
  467. const superCalls = [];
  468. fnPath.traverse(getScopeInformationVisitor, {
  469. thisPaths,
  470. argumentsPaths,
  471. newTargetPaths,
  472. superProps,
  473. superCalls
  474. });
  475. return {
  476. thisPaths,
  477. argumentsPaths,
  478. newTargetPaths,
  479. superProps,
  480. superCalls
  481. };
  482. }
  483. function splitExportDeclaration() {
  484. if (!this.isExportDeclaration() || this.isExportAllDeclaration()) {
  485. throw new Error("Only default and named export declarations can be split.");
  486. }
  487. if (this.isExportNamedDeclaration() && this.get("specifiers").length > 0) {
  488. throw new Error("It doesn't make sense to split exported specifiers.");
  489. }
  490. const declaration = this.get("declaration");
  491. if (this.isExportDefaultDeclaration()) {
  492. const standaloneDeclaration = declaration.isFunctionDeclaration() || declaration.isClassDeclaration();
  493. const exportExpr = declaration.isFunctionExpression() || declaration.isClassExpression();
  494. const scope = declaration.isScope() ? declaration.scope.parent : declaration.scope;
  495. let id = declaration.node.id;
  496. let needBindingRegistration = false;
  497. if (!id) {
  498. needBindingRegistration = true;
  499. id = scope.generateUidIdentifier("default");
  500. if (standaloneDeclaration || exportExpr) {
  501. declaration.node.id = cloneNode(id);
  502. }
  503. } else if (exportExpr && scope.hasBinding(id.name)) {
  504. needBindingRegistration = true;
  505. id = scope.generateUidIdentifier(id.name);
  506. }
  507. const updatedDeclaration = standaloneDeclaration ? declaration.node : variableDeclaration("var", [variableDeclarator(cloneNode(id), declaration.node)]);
  508. const updatedExportDeclaration = exportNamedDeclaration(null, [exportSpecifier(cloneNode(id), identifier("default"))]);
  509. this.insertAfter(updatedExportDeclaration);
  510. this.replaceWith(updatedDeclaration);
  511. if (needBindingRegistration) {
  512. scope.registerDeclaration(this);
  513. }
  514. return this;
  515. } else if (this.get("specifiers").length > 0) {
  516. throw new Error("It doesn't make sense to split exported specifiers.");
  517. }
  518. const bindingIdentifiers = declaration.getOuterBindingIdentifiers();
  519. const specifiers = Object.keys(bindingIdentifiers).map(name => {
  520. return exportSpecifier(identifier(name), identifier(name));
  521. });
  522. const aliasDeclar = exportNamedDeclaration(null, specifiers);
  523. this.insertAfter(aliasDeclar);
  524. this.replaceWith(declaration.node);
  525. return this;
  526. }
  527. const refersOuterBindingVisitor = {
  528. "ReferencedIdentifier|BindingIdentifier"(path, state) {
  529. if (path.node.name !== state.name) return;
  530. state.needsRename = true;
  531. path.stop();
  532. },
  533. Scope(path, state) {
  534. if (path.scope.hasOwnBinding(state.name)) {
  535. path.skip();
  536. }
  537. }
  538. };
  539. function ensureFunctionName(supportUnicodeId) {
  540. if (this.node.id) return this;
  541. const res = getFunctionName(this.node, this.parent);
  542. if (res == null) return this;
  543. let {
  544. name
  545. } = res;
  546. if (!supportUnicodeId && /[\uD800-\uDFFF]/.test(name)) {
  547. return null;
  548. }
  549. if (name.startsWith("get ") || name.startsWith("set ")) {
  550. return null;
  551. }
  552. name = toBindingIdentifierName(name.replace(/[/ ]/g, "_"));
  553. const id = identifier(name);
  554. inherits(id, res.originalNode);
  555. const state = {
  556. needsRename: false,
  557. name
  558. };
  559. const {
  560. scope
  561. } = this;
  562. const binding = scope.getOwnBinding(name);
  563. if (binding) {
  564. if (binding.kind === "param") {
  565. state.needsRename = true;
  566. } else {}
  567. } else if (scope.parent.hasBinding(name) || scope.hasGlobal(name)) {
  568. this.traverse(refersOuterBindingVisitor, state);
  569. }
  570. if (!state.needsRename) {
  571. this.node.id = id;
  572. scope.getProgramParent().references[id.name] = true;
  573. return this;
  574. }
  575. if (scope.hasBinding(id.name) && !scope.hasGlobal(id.name)) {
  576. scope.rename(id.name);
  577. this.node.id = id;
  578. scope.getProgramParent().references[id.name] = true;
  579. return this;
  580. }
  581. if (!isFunction(this.node)) return null;
  582. const key = scope.generateUidIdentifier(id.name);
  583. const params = [];
  584. for (let i = 0, len = getFunctionArity(this.node); i < len; i++) {
  585. params.push(scope.generateUidIdentifier("x"));
  586. }
  587. const call = _template.default.expression.ast`
  588. (function (${key}) {
  589. function ${id}(${params}) {
  590. return ${cloneNode(key)}.apply(this, arguments);
  591. }
  592. ${cloneNode(id)}.toString = function () {
  593. return ${cloneNode(key)}.toString();
  594. }
  595. return ${cloneNode(id)};
  596. })(${toExpression(this.node)})
  597. `;
  598. return this.replaceWith(call)[0].get("arguments.0");
  599. }
  600. function getFunctionArity(node) {
  601. const count = node.params.findIndex(param => isAssignmentPattern(param) || isRestElement(param));
  602. return count === -1 ? node.params.length : count;
  603. }
  604. //# sourceMappingURL=conversion.js.map