You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

989 lines
30 KiB

3 months ago
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _renamer = require("./lib/renamer.js");
  7. var _index = require("../index.js");
  8. var _binding = require("./binding.js");
  9. var _globals = require("globals");
  10. var _t = require("@babel/types");
  11. var t = _t;
  12. var _cache = require("../cache.js");
  13. var _visitors = require("../visitors.js");
  14. const {
  15. NOT_LOCAL_BINDING,
  16. assignmentExpression,
  17. callExpression,
  18. cloneNode,
  19. getBindingIdentifiers,
  20. identifier,
  21. isArrayExpression,
  22. isBinary,
  23. isCallExpression,
  24. isClass,
  25. isClassBody,
  26. isClassDeclaration,
  27. isExportAllDeclaration,
  28. isExportDefaultDeclaration,
  29. isExportNamedDeclaration,
  30. isFunctionDeclaration,
  31. isIdentifier,
  32. isImportDeclaration,
  33. isLiteral,
  34. isMemberExpression,
  35. isMethod,
  36. isModuleSpecifier,
  37. isNullLiteral,
  38. isObjectExpression,
  39. isProperty,
  40. isPureish,
  41. isRegExpLiteral,
  42. isSuper,
  43. isTaggedTemplateExpression,
  44. isTemplateLiteral,
  45. isThisExpression,
  46. isUnaryExpression,
  47. isVariableDeclaration,
  48. expressionStatement,
  49. matchesPattern,
  50. memberExpression,
  51. numericLiteral,
  52. toIdentifier,
  53. variableDeclaration,
  54. variableDeclarator,
  55. isRecordExpression,
  56. isTupleExpression,
  57. isObjectProperty,
  58. isTopicReference,
  59. isMetaProperty,
  60. isPrivateName,
  61. isExportDeclaration,
  62. buildUndefinedNode,
  63. sequenceExpression
  64. } = _t;
  65. function gatherNodeParts(node, parts) {
  66. switch (node == null ? void 0 : node.type) {
  67. default:
  68. if (isImportDeclaration(node) || isExportDeclaration(node)) {
  69. var _node$specifiers;
  70. if ((isExportAllDeclaration(node) || isExportNamedDeclaration(node) || isImportDeclaration(node)) && node.source) {
  71. gatherNodeParts(node.source, parts);
  72. } else if ((isExportNamedDeclaration(node) || isImportDeclaration(node)) && (_node$specifiers = node.specifiers) != null && _node$specifiers.length) {
  73. for (const e of node.specifiers) gatherNodeParts(e, parts);
  74. } else if ((isExportDefaultDeclaration(node) || isExportNamedDeclaration(node)) && node.declaration) {
  75. gatherNodeParts(node.declaration, parts);
  76. }
  77. } else if (isModuleSpecifier(node)) {
  78. gatherNodeParts(node.local, parts);
  79. } else if (isLiteral(node) && !isNullLiteral(node) && !isRegExpLiteral(node) && !isTemplateLiteral(node)) {
  80. parts.push(node.value);
  81. }
  82. break;
  83. case "MemberExpression":
  84. case "OptionalMemberExpression":
  85. case "JSXMemberExpression":
  86. gatherNodeParts(node.object, parts);
  87. gatherNodeParts(node.property, parts);
  88. break;
  89. case "Identifier":
  90. case "JSXIdentifier":
  91. parts.push(node.name);
  92. break;
  93. case "CallExpression":
  94. case "OptionalCallExpression":
  95. case "NewExpression":
  96. gatherNodeParts(node.callee, parts);
  97. break;
  98. case "ObjectExpression":
  99. case "ObjectPattern":
  100. for (const e of node.properties) {
  101. gatherNodeParts(e, parts);
  102. }
  103. break;
  104. case "SpreadElement":
  105. case "RestElement":
  106. gatherNodeParts(node.argument, parts);
  107. break;
  108. case "ObjectProperty":
  109. case "ObjectMethod":
  110. case "ClassProperty":
  111. case "ClassMethod":
  112. case "ClassPrivateProperty":
  113. case "ClassPrivateMethod":
  114. gatherNodeParts(node.key, parts);
  115. break;
  116. case "ThisExpression":
  117. parts.push("this");
  118. break;
  119. case "Super":
  120. parts.push("super");
  121. break;
  122. case "Import":
  123. parts.push("import");
  124. break;
  125. case "DoExpression":
  126. parts.push("do");
  127. break;
  128. case "YieldExpression":
  129. parts.push("yield");
  130. gatherNodeParts(node.argument, parts);
  131. break;
  132. case "AwaitExpression":
  133. parts.push("await");
  134. gatherNodeParts(node.argument, parts);
  135. break;
  136. case "AssignmentExpression":
  137. gatherNodeParts(node.left, parts);
  138. break;
  139. case "VariableDeclarator":
  140. gatherNodeParts(node.id, parts);
  141. break;
  142. case "FunctionExpression":
  143. case "FunctionDeclaration":
  144. case "ClassExpression":
  145. case "ClassDeclaration":
  146. gatherNodeParts(node.id, parts);
  147. break;
  148. case "PrivateName":
  149. gatherNodeParts(node.id, parts);
  150. break;
  151. case "ParenthesizedExpression":
  152. gatherNodeParts(node.expression, parts);
  153. break;
  154. case "UnaryExpression":
  155. case "UpdateExpression":
  156. gatherNodeParts(node.argument, parts);
  157. break;
  158. case "MetaProperty":
  159. gatherNodeParts(node.meta, parts);
  160. gatherNodeParts(node.property, parts);
  161. break;
  162. case "JSXElement":
  163. gatherNodeParts(node.openingElement, parts);
  164. break;
  165. case "JSXOpeningElement":
  166. gatherNodeParts(node.name, parts);
  167. break;
  168. case "JSXFragment":
  169. gatherNodeParts(node.openingFragment, parts);
  170. break;
  171. case "JSXOpeningFragment":
  172. parts.push("Fragment");
  173. break;
  174. case "JSXNamespacedName":
  175. gatherNodeParts(node.namespace, parts);
  176. gatherNodeParts(node.name, parts);
  177. break;
  178. }
  179. }
  180. const collectorVisitor = {
  181. ForStatement(path) {
  182. const declar = path.get("init");
  183. if (declar.isVar()) {
  184. const {
  185. scope
  186. } = path;
  187. const parentScope = scope.getFunctionParent() || scope.getProgramParent();
  188. parentScope.registerBinding("var", declar);
  189. }
  190. },
  191. Declaration(path) {
  192. if (path.isBlockScoped()) return;
  193. if (path.isImportDeclaration()) return;
  194. if (path.isExportDeclaration()) return;
  195. const parent = path.scope.getFunctionParent() || path.scope.getProgramParent();
  196. parent.registerDeclaration(path);
  197. },
  198. ImportDeclaration(path) {
  199. const parent = path.scope.getBlockParent();
  200. parent.registerDeclaration(path);
  201. },
  202. TSImportEqualsDeclaration(path) {
  203. const parent = path.scope.getBlockParent();
  204. parent.registerDeclaration(path);
  205. },
  206. ReferencedIdentifier(path, state) {
  207. if (t.isTSQualifiedName(path.parent) && path.parent.right === path.node) {
  208. return;
  209. }
  210. if (path.parentPath.isTSImportEqualsDeclaration()) return;
  211. state.references.push(path);
  212. },
  213. ForXStatement(path, state) {
  214. const left = path.get("left");
  215. if (left.isPattern() || left.isIdentifier()) {
  216. state.constantViolations.push(path);
  217. } else if (left.isVar()) {
  218. const {
  219. scope
  220. } = path;
  221. const parentScope = scope.getFunctionParent() || scope.getProgramParent();
  222. parentScope.registerBinding("var", left);
  223. }
  224. },
  225. ExportDeclaration: {
  226. exit(path) {
  227. const {
  228. node,
  229. scope
  230. } = path;
  231. if (isExportAllDeclaration(node)) return;
  232. const declar = node.declaration;
  233. if (isClassDeclaration(declar) || isFunctionDeclaration(declar)) {
  234. const id = declar.id;
  235. if (!id) return;
  236. const binding = scope.getBinding(id.name);
  237. binding == null || binding.reference(path);
  238. } else if (isVariableDeclaration(declar)) {
  239. for (const decl of declar.declarations) {
  240. for (const name of Object.keys(getBindingIdentifiers(decl))) {
  241. const binding = scope.getBinding(name);
  242. binding == null || binding.reference(path);
  243. }
  244. }
  245. }
  246. }
  247. },
  248. LabeledStatement(path) {
  249. path.scope.getBlockParent().registerDeclaration(path);
  250. },
  251. AssignmentExpression(path, state) {
  252. state.assignments.push(path);
  253. },
  254. UpdateExpression(path, state) {
  255. state.constantViolations.push(path);
  256. },
  257. UnaryExpression(path, state) {
  258. if (path.node.operator === "delete") {
  259. state.constantViolations.push(path);
  260. }
  261. },
  262. BlockScoped(path) {
  263. let scope = path.scope;
  264. if (scope.path === path) scope = scope.parent;
  265. const parent = scope.getBlockParent();
  266. parent.registerDeclaration(path);
  267. if (path.isClassDeclaration() && path.node.id) {
  268. const id = path.node.id;
  269. const name = id.name;
  270. path.scope.bindings[name] = path.scope.parent.getBinding(name);
  271. }
  272. },
  273. CatchClause(path) {
  274. path.scope.registerBinding("let", path);
  275. },
  276. Function(path) {
  277. const params = path.get("params");
  278. for (const param of params) {
  279. path.scope.registerBinding("param", param);
  280. }
  281. if (path.isFunctionExpression() && path.node.id && !path.node.id[NOT_LOCAL_BINDING]) {
  282. path.scope.registerBinding("local", path.get("id"), path);
  283. }
  284. },
  285. ClassExpression(path) {
  286. if (path.node.id && !path.node.id[NOT_LOCAL_BINDING]) {
  287. path.scope.registerBinding("local", path.get("id"), path);
  288. }
  289. },
  290. TSTypeAnnotation(path) {
  291. path.skip();
  292. }
  293. };
  294. let uid = 0;
  295. class Scope {
  296. constructor(path) {
  297. this.uid = void 0;
  298. this.path = void 0;
  299. this.block = void 0;
  300. this.inited = void 0;
  301. this.labels = void 0;
  302. this.bindings = void 0;
  303. this.references = void 0;
  304. this.globals = void 0;
  305. this.uids = void 0;
  306. this.data = void 0;
  307. this.crawling = void 0;
  308. const {
  309. node
  310. } = path;
  311. const cached = _cache.scope.get(node);
  312. if ((cached == null ? void 0 : cached.path) === path) {
  313. return cached;
  314. }
  315. _cache.scope.set(node, this);
  316. this.uid = uid++;
  317. this.block = node;
  318. this.path = path;
  319. this.labels = new Map();
  320. this.inited = false;
  321. }
  322. get parent() {
  323. var _parent;
  324. let parent,
  325. path = this.path;
  326. do {
  327. var _path;
  328. const shouldSkip = path.key === "key" || path.listKey === "decorators";
  329. path = path.parentPath;
  330. if (shouldSkip && path.isMethod()) path = path.parentPath;
  331. if ((_path = path) != null && _path.isScope()) parent = path;
  332. } while (path && !parent);
  333. return (_parent = parent) == null ? void 0 : _parent.scope;
  334. }
  335. generateDeclaredUidIdentifier(name) {
  336. const id = this.generateUidIdentifier(name);
  337. this.push({
  338. id
  339. });
  340. return cloneNode(id);
  341. }
  342. generateUidIdentifier(name) {
  343. return identifier(this.generateUid(name));
  344. }
  345. generateUid(name = "temp") {
  346. name = toIdentifier(name).replace(/^_+/, "").replace(/\d+$/g, "");
  347. let uid;
  348. let i = 1;
  349. do {
  350. uid = `_${name}`;
  351. if (i > 1) uid += i;
  352. i++;
  353. } while (this.hasLabel(uid) || this.hasBinding(uid) || this.hasGlobal(uid) || this.hasReference(uid));
  354. const program = this.getProgramParent();
  355. program.references[uid] = true;
  356. program.uids[uid] = true;
  357. return uid;
  358. }
  359. generateUidBasedOnNode(node, defaultName) {
  360. const parts = [];
  361. gatherNodeParts(node, parts);
  362. let id = parts.join("$");
  363. id = id.replace(/^_/, "") || defaultName || "ref";
  364. return this.generateUid(id.slice(0, 20));
  365. }
  366. generateUidIdentifierBasedOnNode(node, defaultName) {
  367. return identifier(this.generateUidBasedOnNode(node, defaultName));
  368. }
  369. isStatic(node) {
  370. if (isThisExpression(node) || isSuper(node) || isTopicReference(node)) {
  371. return true;
  372. }
  373. if (isIdentifier(node)) {
  374. const binding = this.getBinding(node.name);
  375. if (binding) {
  376. return binding.constant;
  377. } else {
  378. return this.hasBinding(node.name);
  379. }
  380. }
  381. return false;
  382. }
  383. maybeGenerateMemoised(node, dontPush) {
  384. if (this.isStatic(node)) {
  385. return null;
  386. } else {
  387. const id = this.generateUidIdentifierBasedOnNode(node);
  388. if (!dontPush) {
  389. this.push({
  390. id
  391. });
  392. return cloneNode(id);
  393. }
  394. return id;
  395. }
  396. }
  397. checkBlockScopedCollisions(local, kind, name, id) {
  398. if (kind === "param") return;
  399. if (local.kind === "local") return;
  400. const duplicate = kind === "let" || local.kind === "let" || local.kind === "const" || local.kind === "module" || local.kind === "param" && kind === "const";
  401. if (duplicate) {
  402. throw this.path.hub.buildError(id, `Duplicate declaration "${name}"`, TypeError);
  403. }
  404. }
  405. rename(oldName, newName) {
  406. const binding = this.getBinding(oldName);
  407. if (binding) {
  408. newName || (newName = this.generateUidIdentifier(oldName).name);
  409. const renamer = new _renamer.default(binding, oldName, newName);
  410. {
  411. renamer.rename(arguments[2]);
  412. }
  413. }
  414. }
  415. dump() {
  416. const sep = "-".repeat(60);
  417. console.log(sep);
  418. let scope = this;
  419. do {
  420. console.log("#", scope.block.type);
  421. for (const name of Object.keys(scope.bindings)) {
  422. const binding = scope.bindings[name];
  423. console.log(" -", name, {
  424. constant: binding.constant,
  425. references: binding.references,
  426. violations: binding.constantViolations.length,
  427. kind: binding.kind
  428. });
  429. }
  430. } while (scope = scope.parent);
  431. console.log(sep);
  432. }
  433. hasLabel(name) {
  434. return !!this.getLabel(name);
  435. }
  436. getLabel(name) {
  437. return this.labels.get(name);
  438. }
  439. registerLabel(path) {
  440. this.labels.set(path.node.label.name, path);
  441. }
  442. registerDeclaration(path) {
  443. if (path.isLabeledStatement()) {
  444. this.registerLabel(path);
  445. } else if (path.isFunctionDeclaration()) {
  446. this.registerBinding("hoisted", path.get("id"), path);
  447. } else if (path.isVariableDeclaration()) {
  448. const declarations = path.get("declarations");
  449. const {
  450. kind
  451. } = path.node;
  452. for (const declar of declarations) {
  453. this.registerBinding(kind === "using" || kind === "await using" ? "const" : kind, declar);
  454. }
  455. } else if (path.isClassDeclaration()) {
  456. if (path.node.declare) return;
  457. this.registerBinding("let", path);
  458. } else if (path.isImportDeclaration()) {
  459. const isTypeDeclaration = path.node.importKind === "type" || path.node.importKind === "typeof";
  460. const specifiers = path.get("specifiers");
  461. for (const specifier of specifiers) {
  462. const isTypeSpecifier = isTypeDeclaration || specifier.isImportSpecifier() && (specifier.node.importKind === "type" || specifier.node.importKind === "typeof");
  463. this.registerBinding(isTypeSpecifier ? "unknown" : "module", specifier);
  464. }
  465. } else if (path.isExportDeclaration()) {
  466. const declar = path.get("declaration");
  467. if (declar.isClassDeclaration() || declar.isFunctionDeclaration() || declar.isVariableDeclaration()) {
  468. this.registerDeclaration(declar);
  469. }
  470. } else {
  471. this.registerBinding("unknown", path);
  472. }
  473. }
  474. buildUndefinedNode() {
  475. return buildUndefinedNode();
  476. }
  477. registerConstantViolation(path) {
  478. const ids = path.getAssignmentIdentifiers();
  479. for (const name of Object.keys(ids)) {
  480. var _this$getBinding;
  481. (_this$getBinding = this.getBinding(name)) == null || _this$getBinding.reassign(path);
  482. }
  483. }
  484. registerBinding(kind, path, bindingPath = path) {
  485. if (!kind) throw new ReferenceError("no `kind`");
  486. if (path.isVariableDeclaration()) {
  487. const declarators = path.get("declarations");
  488. for (const declar of declarators) {
  489. this.registerBinding(kind, declar);
  490. }
  491. return;
  492. }
  493. const parent = this.getProgramParent();
  494. const ids = path.getOuterBindingIdentifiers(true);
  495. for (const name of Object.keys(ids)) {
  496. parent.references[name] = true;
  497. for (const id of ids[name]) {
  498. const local = this.getOwnBinding(name);
  499. if (local) {
  500. if (local.identifier === id) continue;
  501. this.checkBlockScopedCollisions(local, kind, name, id);
  502. }
  503. if (local) {
  504. local.reassign(bindingPath);
  505. } else {
  506. this.bindings[name] = new _binding.default({
  507. identifier: id,
  508. scope: this,
  509. path: bindingPath,
  510. kind: kind
  511. });
  512. }
  513. }
  514. }
  515. }
  516. addGlobal(node) {
  517. this.globals[node.name] = node;
  518. }
  519. hasUid(name) {
  520. let scope = this;
  521. do {
  522. if (scope.uids[name]) return true;
  523. } while (scope = scope.parent);
  524. return false;
  525. }
  526. hasGlobal(name) {
  527. let scope = this;
  528. do {
  529. if (scope.globals[name]) return true;
  530. } while (scope = scope.parent);
  531. return false;
  532. }
  533. hasReference(name) {
  534. return !!this.getProgramParent().references[name];
  535. }
  536. isPure(node, constantsOnly) {
  537. if (isIdentifier(node)) {
  538. const binding = this.getBinding(node.name);
  539. if (!binding) return false;
  540. if (constantsOnly) return binding.constant;
  541. return true;
  542. } else if (isThisExpression(node) || isMetaProperty(node) || isTopicReference(node) || isPrivateName(node)) {
  543. return true;
  544. } else if (isClass(node)) {
  545. var _node$decorators;
  546. if (node.superClass && !this.isPure(node.superClass, constantsOnly)) {
  547. return false;
  548. }
  549. if (((_node$decorators = node.decorators) == null ? void 0 : _node$decorators.length) > 0) {
  550. return false;
  551. }
  552. return this.isPure(node.body, constantsOnly);
  553. } else if (isClassBody(node)) {
  554. for (const method of node.body) {
  555. if (!this.isPure(method, constantsOnly)) return false;
  556. }
  557. return true;
  558. } else if (isBinary(node)) {
  559. return this.isPure(node.left, constantsOnly) && this.isPure(node.right, constantsOnly);
  560. } else if (isArrayExpression(node) || isTupleExpression(node)) {
  561. for (const elem of node.elements) {
  562. if (elem !== null && !this.isPure(elem, constantsOnly)) return false;
  563. }
  564. return true;
  565. } else if (isObjectExpression(node) || isRecordExpression(node)) {
  566. for (const prop of node.properties) {
  567. if (!this.isPure(prop, constantsOnly)) return false;
  568. }
  569. return true;
  570. } else if (isMethod(node)) {
  571. var _node$decorators2;
  572. if (node.computed && !this.isPure(node.key, constantsOnly)) return false;
  573. if (((_node$decorators2 = node.decorators) == null ? void 0 : _node$decorators2.length) > 0) {
  574. return false;
  575. }
  576. return true;
  577. } else if (isProperty(node)) {
  578. var _node$decorators3;
  579. if (node.computed && !this.isPure(node.key, constantsOnly)) return false;
  580. if (((_node$decorators3 = node.decorators) == null ? void 0 : _node$decorators3.length) > 0) {
  581. return false;
  582. }
  583. if (isObjectProperty(node) || node.static) {
  584. if (node.value !== null && !this.isPure(node.value, constantsOnly)) {
  585. return false;
  586. }
  587. }
  588. return true;
  589. } else if (isUnaryExpression(node)) {
  590. return this.isPure(node.argument, constantsOnly);
  591. } else if (isTemplateLiteral(node)) {
  592. for (const expression of node.expressions) {
  593. if (!this.isPure(expression, constantsOnly)) return false;
  594. }
  595. return true;
  596. } else if (isTaggedTemplateExpression(node)) {
  597. return matchesPattern(node.tag, "String.raw") && !this.hasBinding("String", {
  598. noGlobals: true
  599. }) && this.isPure(node.quasi, constantsOnly);
  600. } else if (isMemberExpression(node)) {
  601. return !node.computed && isIdentifier(node.object) && node.object.name === "Symbol" && isIdentifier(node.property) && node.property.name !== "for" && !this.hasBinding("Symbol", {
  602. noGlobals: true
  603. });
  604. } else if (isCallExpression(node)) {
  605. return matchesPattern(node.callee, "Symbol.for") && !this.hasBinding("Symbol", {
  606. noGlobals: true
  607. }) && node.arguments.length === 1 && t.isStringLiteral(node.arguments[0]);
  608. } else {
  609. return isPureish(node);
  610. }
  611. }
  612. setData(key, val) {
  613. return this.data[key] = val;
  614. }
  615. getData(key) {
  616. let scope = this;
  617. do {
  618. const data = scope.data[key];
  619. if (data != null) return data;
  620. } while (scope = scope.parent);
  621. }
  622. removeData(key) {
  623. let scope = this;
  624. do {
  625. const data = scope.data[key];
  626. if (data != null) scope.data[key] = null;
  627. } while (scope = scope.parent);
  628. }
  629. init() {
  630. if (!this.inited) {
  631. this.inited = true;
  632. this.crawl();
  633. }
  634. }
  635. crawl() {
  636. const path = this.path;
  637. this.references = Object.create(null);
  638. this.bindings = Object.create(null);
  639. this.globals = Object.create(null);
  640. this.uids = Object.create(null);
  641. this.data = Object.create(null);
  642. let scope = this;
  643. do {
  644. if (scope.crawling) return;
  645. if (scope.path.isProgram()) {
  646. break;
  647. }
  648. } while (scope = scope.parent);
  649. const programParent = scope;
  650. const state = {
  651. references: [],
  652. constantViolations: [],
  653. assignments: []
  654. };
  655. this.crawling = true;
  656. if (path.type !== "Program" && (0, _visitors.isExplodedVisitor)(collectorVisitor)) {
  657. for (const visit of collectorVisitor.enter) {
  658. visit.call(state, path, state);
  659. }
  660. const typeVisitors = collectorVisitor[path.type];
  661. if (typeVisitors) {
  662. for (const visit of typeVisitors.enter) {
  663. visit.call(state, path, state);
  664. }
  665. }
  666. }
  667. path.traverse(collectorVisitor, state);
  668. this.crawling = false;
  669. for (const path of state.assignments) {
  670. const ids = path.getAssignmentIdentifiers();
  671. for (const name of Object.keys(ids)) {
  672. if (path.scope.getBinding(name)) continue;
  673. programParent.addGlobal(ids[name]);
  674. }
  675. path.scope.registerConstantViolation(path);
  676. }
  677. for (const ref of state.references) {
  678. const binding = ref.scope.getBinding(ref.node.name);
  679. if (binding) {
  680. binding.reference(ref);
  681. } else {
  682. programParent.addGlobal(ref.node);
  683. }
  684. }
  685. for (const path of state.constantViolations) {
  686. path.scope.registerConstantViolation(path);
  687. }
  688. }
  689. push(opts) {
  690. let path = this.path;
  691. if (path.isPattern()) {
  692. path = this.getPatternParent().path;
  693. } else if (!path.isBlockStatement() && !path.isProgram()) {
  694. path = this.getBlockParent().path;
  695. }
  696. if (path.isSwitchStatement()) {
  697. path = (this.getFunctionParent() || this.getProgramParent()).path;
  698. }
  699. const {
  700. init,
  701. unique,
  702. kind = "var",
  703. id
  704. } = opts;
  705. if (!init && !unique && (kind === "var" || kind === "let") && path.isFunction() && !path.node.name && isCallExpression(path.parent, {
  706. callee: path.node
  707. }) && path.parent.arguments.length <= path.node.params.length && isIdentifier(id)) {
  708. path.pushContainer("params", id);
  709. path.scope.registerBinding("param", path.get("params")[path.node.params.length - 1]);
  710. return;
  711. }
  712. if (path.isLoop() || path.isCatchClause() || path.isFunction()) {
  713. path.ensureBlock();
  714. path = path.get("body");
  715. }
  716. const blockHoist = opts._blockHoist == null ? 2 : opts._blockHoist;
  717. const dataKey = `declaration:${kind}:${blockHoist}`;
  718. let declarPath = !unique && path.getData(dataKey);
  719. if (!declarPath) {
  720. const declar = variableDeclaration(kind, []);
  721. declar._blockHoist = blockHoist;
  722. [declarPath] = path.unshiftContainer("body", [declar]);
  723. if (!unique) path.setData(dataKey, declarPath);
  724. }
  725. const declarator = variableDeclarator(id, init);
  726. const len = declarPath.node.declarations.push(declarator);
  727. path.scope.registerBinding(kind, declarPath.get("declarations")[len - 1]);
  728. }
  729. getProgramParent() {
  730. let scope = this;
  731. do {
  732. if (scope.path.isProgram()) {
  733. return scope;
  734. }
  735. } while (scope = scope.parent);
  736. throw new Error("Couldn't find a Program");
  737. }
  738. getFunctionParent() {
  739. let scope = this;
  740. do {
  741. if (scope.path.isFunctionParent()) {
  742. return scope;
  743. }
  744. } while (scope = scope.parent);
  745. return null;
  746. }
  747. getBlockParent() {
  748. let scope = this;
  749. do {
  750. if (scope.path.isBlockParent()) {
  751. return scope;
  752. }
  753. } while (scope = scope.parent);
  754. throw new Error("We couldn't find a BlockStatement, For, Switch, Function, Loop or Program...");
  755. }
  756. getPatternParent() {
  757. let scope = this;
  758. do {
  759. if (!scope.path.isPattern()) {
  760. return scope.getBlockParent();
  761. }
  762. } while (scope = scope.parent.parent);
  763. throw new Error("We couldn't find a BlockStatement, For, Switch, Function, Loop or Program...");
  764. }
  765. getAllBindings() {
  766. const ids = Object.create(null);
  767. let scope = this;
  768. do {
  769. for (const key of Object.keys(scope.bindings)) {
  770. if (key in ids === false) {
  771. ids[key] = scope.bindings[key];
  772. }
  773. }
  774. scope = scope.parent;
  775. } while (scope);
  776. return ids;
  777. }
  778. bindingIdentifierEquals(name, node) {
  779. return this.getBindingIdentifier(name) === node;
  780. }
  781. getBinding(name) {
  782. let scope = this;
  783. let previousPath;
  784. do {
  785. const binding = scope.getOwnBinding(name);
  786. if (binding) {
  787. var _previousPath;
  788. if ((_previousPath = previousPath) != null && _previousPath.isPattern() && binding.kind !== "param" && binding.kind !== "local") {} else {
  789. return binding;
  790. }
  791. } else if (!binding && name === "arguments" && scope.path.isFunction() && !scope.path.isArrowFunctionExpression()) {
  792. break;
  793. }
  794. previousPath = scope.path;
  795. } while (scope = scope.parent);
  796. }
  797. getOwnBinding(name) {
  798. return this.bindings[name];
  799. }
  800. getBindingIdentifier(name) {
  801. var _this$getBinding2;
  802. return (_this$getBinding2 = this.getBinding(name)) == null ? void 0 : _this$getBinding2.identifier;
  803. }
  804. getOwnBindingIdentifier(name) {
  805. const binding = this.bindings[name];
  806. return binding == null ? void 0 : binding.identifier;
  807. }
  808. hasOwnBinding(name) {
  809. return !!this.getOwnBinding(name);
  810. }
  811. hasBinding(name, opts) {
  812. if (!name) return false;
  813. let scope = this;
  814. do {
  815. if (scope.hasOwnBinding(name)) {
  816. return true;
  817. }
  818. } while (scope = scope.parent);
  819. let noGlobals;
  820. let noUids;
  821. if (typeof opts === "object") {
  822. noGlobals = opts.noGlobals;
  823. noUids = opts.noUids;
  824. } else if (typeof opts === "boolean") {
  825. noGlobals = opts;
  826. }
  827. if (!noUids && this.hasUid(name)) return true;
  828. if (!noGlobals && Scope.globals.includes(name)) return true;
  829. if (!noGlobals && Scope.contextVariables.includes(name)) return true;
  830. return false;
  831. }
  832. parentHasBinding(name, opts) {
  833. var _this$parent;
  834. return (_this$parent = this.parent) == null ? void 0 : _this$parent.hasBinding(name, opts);
  835. }
  836. moveBindingTo(name, scope) {
  837. const info = this.getBinding(name);
  838. if (info) {
  839. info.scope.removeOwnBinding(name);
  840. info.scope = scope;
  841. scope.bindings[name] = info;
  842. }
  843. }
  844. removeOwnBinding(name) {
  845. delete this.bindings[name];
  846. }
  847. removeBinding(name) {
  848. var _this$getBinding3;
  849. (_this$getBinding3 = this.getBinding(name)) == null || _this$getBinding3.scope.removeOwnBinding(name);
  850. let scope = this;
  851. do {
  852. if (scope.uids[name]) {
  853. scope.uids[name] = false;
  854. }
  855. } while (scope = scope.parent);
  856. }
  857. hoistVariables(emit = id => this.push({
  858. id
  859. })) {
  860. this.crawl();
  861. const seen = new Set();
  862. for (const name of Object.keys(this.bindings)) {
  863. const binding = this.bindings[name];
  864. if (!binding) continue;
  865. const {
  866. path
  867. } = binding;
  868. if (!path.isVariableDeclarator()) continue;
  869. const {
  870. parent,
  871. parentPath
  872. } = path;
  873. if (parent.kind !== "var" || seen.has(parent)) continue;
  874. seen.add(path.parent);
  875. let firstId;
  876. const init = [];
  877. for (const decl of parent.declarations) {
  878. var _firstId;
  879. (_firstId = firstId) != null ? _firstId : firstId = decl.id;
  880. if (decl.init) {
  881. init.push(assignmentExpression("=", decl.id, decl.init));
  882. }
  883. const ids = Object.keys(getBindingIdentifiers(decl, false, true, true));
  884. for (const name of ids) {
  885. emit(identifier(name), decl.init != null);
  886. }
  887. }
  888. if (parentPath.parentPath.isFor({
  889. left: parent
  890. })) {
  891. parentPath.replaceWith(firstId);
  892. } else if (init.length === 0) {
  893. parentPath.remove();
  894. } else {
  895. const expr = init.length === 1 ? init[0] : sequenceExpression(init);
  896. if (parentPath.parentPath.isForStatement({
  897. init: parent
  898. })) {
  899. parentPath.replaceWith(expr);
  900. } else {
  901. parentPath.replaceWith(expressionStatement(expr));
  902. }
  903. }
  904. }
  905. }
  906. }
  907. exports.default = Scope;
  908. Scope.globals = Object.keys(_globals.builtin);
  909. Scope.contextVariables = ["arguments", "undefined", "Infinity", "NaN"];
  910. {
  911. Scope.prototype._renameFromMap = function _renameFromMap(map, oldName, newName, value) {
  912. if (map[oldName]) {
  913. map[newName] = value;
  914. map[oldName] = null;
  915. }
  916. };
  917. Scope.prototype.traverse = function (node, opts, state) {
  918. (0, _index.default)(node, opts, this, state, this.path);
  919. };
  920. Scope.prototype._generateUid = function _generateUid(name, i) {
  921. let id = name;
  922. if (i > 1) id += i;
  923. return `_${id}`;
  924. };
  925. Scope.prototype.toArray = function toArray(node, i, arrayLikeIsIterable) {
  926. if (isIdentifier(node)) {
  927. const binding = this.getBinding(node.name);
  928. if (binding != null && binding.constant && binding.path.isGenericType("Array")) {
  929. return node;
  930. }
  931. }
  932. if (isArrayExpression(node)) {
  933. return node;
  934. }
  935. if (isIdentifier(node, {
  936. name: "arguments"
  937. })) {
  938. return callExpression(memberExpression(memberExpression(memberExpression(identifier("Array"), identifier("prototype")), identifier("slice")), identifier("call")), [node]);
  939. }
  940. let helperName;
  941. const args = [node];
  942. if (i === true) {
  943. helperName = "toConsumableArray";
  944. } else if (typeof i === "number") {
  945. args.push(numericLiteral(i));
  946. helperName = "slicedToArray";
  947. } else {
  948. helperName = "toArray";
  949. }
  950. if (arrayLikeIsIterable) {
  951. args.unshift(this.path.hub.addHelper(helperName));
  952. helperName = "maybeArrayLike";
  953. }
  954. return callExpression(this.path.hub.addHelper(helperName), args);
  955. };
  956. Scope.prototype.getAllBindingsOfKind = function getAllBindingsOfKind(...kinds) {
  957. const ids = Object.create(null);
  958. for (const kind of kinds) {
  959. let scope = this;
  960. do {
  961. for (const name of Object.keys(scope.bindings)) {
  962. const binding = scope.bindings[name];
  963. if (binding.kind === kind) ids[name] = binding;
  964. }
  965. scope = scope.parent;
  966. } while (scope);
  967. }
  968. return ids;
  969. };
  970. Object.defineProperties(Scope.prototype, {
  971. parentBlock: {
  972. configurable: true,
  973. enumerable: true,
  974. get() {
  975. return this.path.parent;
  976. }
  977. },
  978. hub: {
  979. configurable: true,
  980. enumerable: true,
  981. get() {
  982. return this.path.hub;
  983. }
  984. }
  985. });
  986. }
  987. //# sourceMappingURL=index.js.map