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. 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. exports.arrowFunctionToShadowed = function () {
  103. if (!this.isArrowFunctionExpression()) return;
  104. this.arrowFunctionToExpression();
  105. };
  106. function unwrapFunctionEnvironment() {
  107. if (!this.isArrowFunctionExpression() && !this.isFunctionExpression() && !this.isFunctionDeclaration()) {
  108. throw this.buildCodeFrameError("Can only unwrap the environment of a function.");
  109. }
  110. hoistFunctionEnvironment(this);
  111. }
  112. function setType(path, type) {
  113. path.node.type = type;
  114. }
  115. function arrowFunctionToExpression({
  116. allowInsertArrow = true,
  117. allowInsertArrowWithRest = allowInsertArrow,
  118. noNewArrows = !(_arguments$ => (_arguments$ = arguments[0]) == null ? void 0 : _arguments$.specCompliant)()
  119. } = {}) {
  120. if (!this.isArrowFunctionExpression()) {
  121. throw this.buildCodeFrameError("Cannot convert non-arrow function to a function expression.");
  122. }
  123. let self = this;
  124. if (!noNewArrows) {
  125. var _self$ensureFunctionN;
  126. self = (_self$ensureFunctionN = self.ensureFunctionName(false)) != null ? _self$ensureFunctionN : self;
  127. }
  128. const {
  129. thisBinding,
  130. fnPath: fn
  131. } = hoistFunctionEnvironment(self, noNewArrows, allowInsertArrow, allowInsertArrowWithRest);
  132. fn.ensureBlock();
  133. setType(fn, "FunctionExpression");
  134. if (!noNewArrows) {
  135. const checkBinding = thisBinding ? null : fn.scope.generateUidIdentifier("arrowCheckId");
  136. if (checkBinding) {
  137. fn.parentPath.scope.push({
  138. id: checkBinding,
  139. init: objectExpression([])
  140. });
  141. }
  142. fn.get("body").unshiftContainer("body", expressionStatement(callExpression(this.hub.addHelper("newArrowCheck"), [thisExpression(), checkBinding ? identifier(checkBinding.name) : identifier(thisBinding)])));
  143. fn.replaceWith(callExpression(memberExpression(fn.node, identifier("bind")), [checkBinding ? identifier(checkBinding.name) : thisExpression()]));
  144. return fn.get("callee.object");
  145. }
  146. return fn;
  147. }
  148. const getSuperCallsVisitor = (0, _visitors.environmentVisitor)({
  149. CallExpression(child, {
  150. allSuperCalls
  151. }) {
  152. if (!child.get("callee").isSuper()) return;
  153. allSuperCalls.push(child);
  154. }
  155. });
  156. function hoistFunctionEnvironment(fnPath, noNewArrows = true, allowInsertArrow = true, allowInsertArrowWithRest = true) {
  157. let arrowParent;
  158. let thisEnvFn = fnPath.findParent(p => {
  159. if (p.isArrowFunctionExpression()) {
  160. arrowParent != null ? arrowParent : arrowParent = p;
  161. return false;
  162. }
  163. return p.isFunction() || p.isProgram() || p.isClassProperty({
  164. static: false
  165. }) || p.isClassPrivateProperty({
  166. static: false
  167. });
  168. });
  169. const inConstructor = thisEnvFn.isClassMethod({
  170. kind: "constructor"
  171. });
  172. if (thisEnvFn.isClassProperty() || thisEnvFn.isClassPrivateProperty()) {
  173. if (arrowParent) {
  174. thisEnvFn = arrowParent;
  175. } else if (allowInsertArrow) {
  176. fnPath.replaceWith(callExpression(arrowFunctionExpression([], toExpression(fnPath.node)), []));
  177. thisEnvFn = fnPath.get("callee");
  178. fnPath = thisEnvFn.get("body");
  179. } else {
  180. throw fnPath.buildCodeFrameError("Unable to transform arrow inside class property");
  181. }
  182. }
  183. const {
  184. thisPaths,
  185. argumentsPaths,
  186. newTargetPaths,
  187. superProps,
  188. superCalls
  189. } = getScopeInformation(fnPath);
  190. if (inConstructor && superCalls.length > 0) {
  191. if (!allowInsertArrow) {
  192. 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.");
  193. }
  194. if (!allowInsertArrowWithRest) {
  195. 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.");
  196. }
  197. const allSuperCalls = [];
  198. thisEnvFn.traverse(getSuperCallsVisitor, {
  199. allSuperCalls
  200. });
  201. const superBinding = getSuperBinding(thisEnvFn);
  202. allSuperCalls.forEach(superCall => {
  203. const callee = identifier(superBinding);
  204. callee.loc = superCall.node.callee.loc;
  205. superCall.get("callee").replaceWith(callee);
  206. });
  207. }
  208. if (argumentsPaths.length > 0) {
  209. const argumentsBinding = getBinding(thisEnvFn, "arguments", () => {
  210. const args = () => identifier("arguments");
  211. if (thisEnvFn.scope.path.isProgram()) {
  212. return conditionalExpression(binaryExpression("===", unaryExpression("typeof", args()), stringLiteral("undefined")), thisEnvFn.scope.buildUndefinedNode(), args());
  213. } else {
  214. return args();
  215. }
  216. });
  217. argumentsPaths.forEach(argumentsChild => {
  218. const argsRef = identifier(argumentsBinding);
  219. argsRef.loc = argumentsChild.node.loc;
  220. argumentsChild.replaceWith(argsRef);
  221. });
  222. }
  223. if (newTargetPaths.length > 0) {
  224. const newTargetBinding = getBinding(thisEnvFn, "newtarget", () => metaProperty(identifier("new"), identifier("target")));
  225. newTargetPaths.forEach(targetChild => {
  226. const targetRef = identifier(newTargetBinding);
  227. targetRef.loc = targetChild.node.loc;
  228. targetChild.replaceWith(targetRef);
  229. });
  230. }
  231. if (superProps.length > 0) {
  232. if (!allowInsertArrow) {
  233. 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.");
  234. }
  235. const flatSuperProps = superProps.reduce((acc, superProp) => acc.concat(standardizeSuperProperty(superProp)), []);
  236. flatSuperProps.forEach(superProp => {
  237. const key = superProp.node.computed ? "" : superProp.get("property").node.name;
  238. const superParentPath = superProp.parentPath;
  239. const isAssignment = superParentPath.isAssignmentExpression({
  240. left: superProp.node
  241. });
  242. const isCall = superParentPath.isCallExpression({
  243. callee: superProp.node
  244. });
  245. const isTaggedTemplate = superParentPath.isTaggedTemplateExpression({
  246. tag: superProp.node
  247. });
  248. const superBinding = getSuperPropBinding(thisEnvFn, isAssignment, key);
  249. const args = [];
  250. if (superProp.node.computed) {
  251. args.push(superProp.get("property").node);
  252. }
  253. if (isAssignment) {
  254. const value = superParentPath.node.right;
  255. args.push(value);
  256. }
  257. const call = callExpression(identifier(superBinding), args);
  258. if (isCall) {
  259. superParentPath.unshiftContainer("arguments", thisExpression());
  260. superProp.replaceWith(memberExpression(call, identifier("call")));
  261. thisPaths.push(superParentPath.get("arguments.0"));
  262. } else if (isAssignment) {
  263. superParentPath.replaceWith(call);
  264. } else if (isTaggedTemplate) {
  265. superProp.replaceWith(callExpression(memberExpression(call, identifier("bind"), false), [thisExpression()]));
  266. thisPaths.push(superProp.get("arguments.0"));
  267. } else {
  268. superProp.replaceWith(call);
  269. }
  270. });
  271. }
  272. let thisBinding;
  273. if (thisPaths.length > 0 || !noNewArrows) {
  274. thisBinding = getThisBinding(thisEnvFn, inConstructor);
  275. if (noNewArrows || inConstructor && hasSuperClass(thisEnvFn)) {
  276. thisPaths.forEach(thisChild => {
  277. const thisRef = thisChild.isJSX() ? jsxIdentifier(thisBinding) : identifier(thisBinding);
  278. thisRef.loc = thisChild.node.loc;
  279. thisChild.replaceWith(thisRef);
  280. });
  281. if (!noNewArrows) thisBinding = null;
  282. }
  283. }
  284. return {
  285. thisBinding: thisBinding,
  286. fnPath
  287. };
  288. }
  289. function isLogicalOp(op) {
  290. return LOGICAL_OPERATORS.includes(op);
  291. }
  292. function standardizeSuperProperty(superProp) {
  293. if (superProp.parentPath.isAssignmentExpression() && superProp.parentPath.node.operator !== "=") {
  294. const assignmentPath = superProp.parentPath;
  295. const op = assignmentPath.node.operator.slice(0, -1);
  296. const value = assignmentPath.node.right;
  297. const isLogicalAssignment = isLogicalOp(op);
  298. if (superProp.node.computed) {
  299. const tmp = superProp.scope.generateDeclaredUidIdentifier("tmp");
  300. const {
  301. object,
  302. property
  303. } = superProp.node;
  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