index.js 27 KB

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