index.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  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. ReferencedIdentifier(path, state) {
  203. state.references.push(path);
  204. },
  205. ForXStatement(path, state) {
  206. const left = path.get("left");
  207. if (left.isPattern() || left.isIdentifier()) {
  208. state.constantViolations.push(path);
  209. } else if (left.isVar()) {
  210. const {
  211. scope
  212. } = path;
  213. const parentScope = scope.getFunctionParent() || scope.getProgramParent();
  214. parentScope.registerBinding("var", left);
  215. }
  216. },
  217. ExportDeclaration: {
  218. exit(path) {
  219. const {
  220. node,
  221. scope
  222. } = path;
  223. if (isExportAllDeclaration(node)) return;
  224. const declar = node.declaration;
  225. if (isClassDeclaration(declar) || isFunctionDeclaration(declar)) {
  226. const id = declar.id;
  227. if (!id) return;
  228. const binding = scope.getBinding(id.name);
  229. binding == null || binding.reference(path);
  230. } else if (isVariableDeclaration(declar)) {
  231. for (const decl of declar.declarations) {
  232. for (const name of Object.keys(getBindingIdentifiers(decl))) {
  233. const binding = scope.getBinding(name);
  234. binding == null || binding.reference(path);
  235. }
  236. }
  237. }
  238. }
  239. },
  240. LabeledStatement(path) {
  241. path.scope.getBlockParent().registerDeclaration(path);
  242. },
  243. AssignmentExpression(path, state) {
  244. state.assignments.push(path);
  245. },
  246. UpdateExpression(path, state) {
  247. state.constantViolations.push(path);
  248. },
  249. UnaryExpression(path, state) {
  250. if (path.node.operator === "delete") {
  251. state.constantViolations.push(path);
  252. }
  253. },
  254. BlockScoped(path) {
  255. let scope = path.scope;
  256. if (scope.path === path) scope = scope.parent;
  257. const parent = scope.getBlockParent();
  258. parent.registerDeclaration(path);
  259. if (path.isClassDeclaration() && path.node.id) {
  260. const id = path.node.id;
  261. const name = id.name;
  262. path.scope.bindings[name] = path.scope.parent.getBinding(name);
  263. }
  264. },
  265. CatchClause(path) {
  266. path.scope.registerBinding("let", path);
  267. },
  268. Function(path) {
  269. const params = path.get("params");
  270. for (const param of params) {
  271. path.scope.registerBinding("param", param);
  272. }
  273. if (path.isFunctionExpression() && path.node.id && !path.node.id[NOT_LOCAL_BINDING]) {
  274. path.scope.registerBinding("local", path.get("id"), path);
  275. }
  276. },
  277. ClassExpression(path) {
  278. if (path.node.id && !path.node.id[NOT_LOCAL_BINDING]) {
  279. path.scope.registerBinding("local", path.get("id"), path);
  280. }
  281. },
  282. TSTypeAnnotation(path) {
  283. path.skip();
  284. }
  285. };
  286. let uid = 0;
  287. class Scope {
  288. constructor(path) {
  289. this.uid = void 0;
  290. this.path = void 0;
  291. this.block = void 0;
  292. this.inited = void 0;
  293. this.labels = void 0;
  294. this.bindings = void 0;
  295. this.references = void 0;
  296. this.globals = void 0;
  297. this.uids = void 0;
  298. this.data = void 0;
  299. this.crawling = void 0;
  300. const {
  301. node
  302. } = path;
  303. const cached = _cache.scope.get(node);
  304. if ((cached == null ? void 0 : cached.path) === path) {
  305. return cached;
  306. }
  307. _cache.scope.set(node, this);
  308. this.uid = uid++;
  309. this.block = node;
  310. this.path = path;
  311. this.labels = new Map();
  312. this.inited = false;
  313. }
  314. get parent() {
  315. var _parent;
  316. let parent,
  317. path = this.path;
  318. do {
  319. var _path;
  320. const shouldSkip = path.key === "key" || path.listKey === "decorators";
  321. path = path.parentPath;
  322. if (shouldSkip && path.isMethod()) path = path.parentPath;
  323. if ((_path = path) != null && _path.isScope()) parent = path;
  324. } while (path && !parent);
  325. return (_parent = parent) == null ? void 0 : _parent.scope;
  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(/\d+$/g, "");
  339. let uid;
  340. let i = 1;
  341. do {
  342. uid = `_${name}`;
  343. if (i > 1) uid += i;
  344. i++;
  345. } while (this.hasLabel(uid) || this.hasBinding(uid) || this.hasGlobal(uid) || this.hasReference(uid));
  346. const program = this.getProgramParent();
  347. program.references[uid] = true;
  348. program.uids[uid] = true;
  349. return uid;
  350. }
  351. generateUidBasedOnNode(node, defaultName) {
  352. const parts = [];
  353. gatherNodeParts(node, parts);
  354. let id = parts.join("$");
  355. id = id.replace(/^_/, "") || defaultName || "ref";
  356. return this.generateUid(id.slice(0, 20));
  357. }
  358. generateUidIdentifierBasedOnNode(node, defaultName) {
  359. return identifier(this.generateUidBasedOnNode(node, defaultName));
  360. }
  361. isStatic(node) {
  362. if (isThisExpression(node) || isSuper(node) || isTopicReference(node)) {
  363. return true;
  364. }
  365. if (isIdentifier(node)) {
  366. const binding = this.getBinding(node.name);
  367. if (binding) {
  368. return binding.constant;
  369. } else {
  370. return this.hasBinding(node.name);
  371. }
  372. }
  373. return false;
  374. }
  375. maybeGenerateMemoised(node, dontPush) {
  376. if (this.isStatic(node)) {
  377. return null;
  378. } else {
  379. const id = this.generateUidIdentifierBasedOnNode(node);
  380. if (!dontPush) {
  381. this.push({
  382. id
  383. });
  384. return cloneNode(id);
  385. }
  386. return id;
  387. }
  388. }
  389. checkBlockScopedCollisions(local, kind, name, id) {
  390. if (kind === "param") return;
  391. if (local.kind === "local") return;
  392. const duplicate = kind === "let" || local.kind === "let" || local.kind === "const" || local.kind === "module" || local.kind === "param" && kind === "const";
  393. if (duplicate) {
  394. throw this.path.hub.buildError(id, `Duplicate declaration "${name}"`, TypeError);
  395. }
  396. }
  397. rename(oldName, newName) {
  398. const binding = this.getBinding(oldName);
  399. if (binding) {
  400. newName || (newName = this.generateUidIdentifier(oldName).name);
  401. const renamer = new _renamer.default(binding, oldName, newName);
  402. {
  403. renamer.rename(arguments[2]);
  404. }
  405. }
  406. }
  407. dump() {
  408. const sep = "-".repeat(60);
  409. console.log(sep);
  410. let scope = this;
  411. do {
  412. console.log("#", scope.block.type);
  413. for (const name of Object.keys(scope.bindings)) {
  414. const binding = scope.bindings[name];
  415. console.log(" -", name, {
  416. constant: binding.constant,
  417. references: binding.references,
  418. violations: binding.constantViolations.length,
  419. kind: binding.kind
  420. });
  421. }
  422. } while (scope = scope.parent);
  423. console.log(sep);
  424. }
  425. hasLabel(name) {
  426. return !!this.getLabel(name);
  427. }
  428. getLabel(name) {
  429. return this.labels.get(name);
  430. }
  431. registerLabel(path) {
  432. this.labels.set(path.node.label.name, path);
  433. }
  434. registerDeclaration(path) {
  435. if (path.isLabeledStatement()) {
  436. this.registerLabel(path);
  437. } else if (path.isFunctionDeclaration()) {
  438. this.registerBinding("hoisted", path.get("id"), path);
  439. } else if (path.isVariableDeclaration()) {
  440. const declarations = path.get("declarations");
  441. const {
  442. kind
  443. } = path.node;
  444. for (const declar of declarations) {
  445. this.registerBinding(kind === "using" || kind === "await using" ? "const" : kind, declar);
  446. }
  447. } else if (path.isClassDeclaration()) {
  448. if (path.node.declare) return;
  449. this.registerBinding("let", path);
  450. } else if (path.isImportDeclaration()) {
  451. const isTypeDeclaration = path.node.importKind === "type" || path.node.importKind === "typeof";
  452. const specifiers = path.get("specifiers");
  453. for (const specifier of specifiers) {
  454. const isTypeSpecifier = isTypeDeclaration || specifier.isImportSpecifier() && (specifier.node.importKind === "type" || specifier.node.importKind === "typeof");
  455. this.registerBinding(isTypeSpecifier ? "unknown" : "module", specifier);
  456. }
  457. } else if (path.isExportDeclaration()) {
  458. const declar = path.get("declaration");
  459. if (declar.isClassDeclaration() || declar.isFunctionDeclaration() || declar.isVariableDeclaration()) {
  460. this.registerDeclaration(declar);
  461. }
  462. } else {
  463. this.registerBinding("unknown", path);
  464. }
  465. }
  466. buildUndefinedNode() {
  467. return buildUndefinedNode();
  468. }
  469. registerConstantViolation(path) {
  470. const ids = path.getAssignmentIdentifiers();
  471. for (const name of Object.keys(ids)) {
  472. var _this$getBinding;
  473. (_this$getBinding = this.getBinding(name)) == null || _this$getBinding.reassign(path);
  474. }
  475. }
  476. registerBinding(kind, path, bindingPath = path) {
  477. if (!kind) throw new ReferenceError("no `kind`");
  478. if (path.isVariableDeclaration()) {
  479. const declarators = path.get("declarations");
  480. for (const declar of declarators) {
  481. this.registerBinding(kind, declar);
  482. }
  483. return;
  484. }
  485. const parent = this.getProgramParent();
  486. const ids = path.getOuterBindingIdentifiers(true);
  487. for (const name of Object.keys(ids)) {
  488. parent.references[name] = true;
  489. for (const id of ids[name]) {
  490. const local = this.getOwnBinding(name);
  491. if (local) {
  492. if (local.identifier === id) continue;
  493. this.checkBlockScopedCollisions(local, kind, name, id);
  494. }
  495. if (local) {
  496. local.reassign(bindingPath);
  497. } else {
  498. this.bindings[name] = new _binding.default({
  499. identifier: id,
  500. scope: this,
  501. path: bindingPath,
  502. kind: kind
  503. });
  504. }
  505. }
  506. }
  507. }
  508. addGlobal(node) {
  509. this.globals[node.name] = node;
  510. }
  511. hasUid(name) {
  512. let scope = this;
  513. do {
  514. if (scope.uids[name]) return true;
  515. } while (scope = scope.parent);
  516. return false;
  517. }
  518. hasGlobal(name) {
  519. let scope = this;
  520. do {
  521. if (scope.globals[name]) return true;
  522. } while (scope = scope.parent);
  523. return false;
  524. }
  525. hasReference(name) {
  526. return !!this.getProgramParent().references[name];
  527. }
  528. isPure(node, constantsOnly) {
  529. if (isIdentifier(node)) {
  530. const binding = this.getBinding(node.name);
  531. if (!binding) return false;
  532. if (constantsOnly) return binding.constant;
  533. return true;
  534. } else if (isThisExpression(node) || isMetaProperty(node) || isTopicReference(node) || isPrivateName(node)) {
  535. return true;
  536. } else if (isClass(node)) {
  537. var _node$decorators;
  538. if (node.superClass && !this.isPure(node.superClass, constantsOnly)) {
  539. return false;
  540. }
  541. if (((_node$decorators = node.decorators) == null ? void 0 : _node$decorators.length) > 0) {
  542. return false;
  543. }
  544. return this.isPure(node.body, constantsOnly);
  545. } else if (isClassBody(node)) {
  546. for (const method of node.body) {
  547. if (!this.isPure(method, constantsOnly)) return false;
  548. }
  549. return true;
  550. } else if (isBinary(node)) {
  551. return this.isPure(node.left, constantsOnly) && this.isPure(node.right, constantsOnly);
  552. } else if (isArrayExpression(node) || isTupleExpression(node)) {
  553. for (const elem of node.elements) {
  554. if (elem !== null && !this.isPure(elem, constantsOnly)) return false;
  555. }
  556. return true;
  557. } else if (isObjectExpression(node) || isRecordExpression(node)) {
  558. for (const prop of node.properties) {
  559. if (!this.isPure(prop, constantsOnly)) return false;
  560. }
  561. return true;
  562. } else if (isMethod(node)) {
  563. var _node$decorators2;
  564. if (node.computed && !this.isPure(node.key, constantsOnly)) return false;
  565. if (((_node$decorators2 = node.decorators) == null ? void 0 : _node$decorators2.length) > 0) {
  566. return false;
  567. }
  568. return true;
  569. } else if (isProperty(node)) {
  570. var _node$decorators3;
  571. if (node.computed && !this.isPure(node.key, constantsOnly)) return false;
  572. if (((_node$decorators3 = node.decorators) == null ? void 0 : _node$decorators3.length) > 0) {
  573. return false;
  574. }
  575. if (isObjectProperty(node) || node.static) {
  576. if (node.value !== null && !this.isPure(node.value, constantsOnly)) {
  577. return false;
  578. }
  579. }
  580. return true;
  581. } else if (isUnaryExpression(node)) {
  582. return this.isPure(node.argument, constantsOnly);
  583. } else if (isTemplateLiteral(node)) {
  584. for (const expression of node.expressions) {
  585. if (!this.isPure(expression, constantsOnly)) return false;
  586. }
  587. return true;
  588. } else if (isTaggedTemplateExpression(node)) {
  589. return matchesPattern(node.tag, "String.raw") && !this.hasBinding("String", {
  590. noGlobals: true
  591. }) && this.isPure(node.quasi, constantsOnly);
  592. } else if (isMemberExpression(node)) {
  593. return !node.computed && isIdentifier(node.object) && node.object.name === "Symbol" && isIdentifier(node.property) && node.property.name !== "for" && !this.hasBinding("Symbol", {
  594. noGlobals: true
  595. });
  596. } else if (isCallExpression(node)) {
  597. return matchesPattern(node.callee, "Symbol.for") && !this.hasBinding("Symbol", {
  598. noGlobals: true
  599. }) && node.arguments.length === 1 && t.isStringLiteral(node.arguments[0]);
  600. } else {
  601. return isPureish(node);
  602. }
  603. }
  604. setData(key, val) {
  605. return this.data[key] = val;
  606. }
  607. getData(key) {
  608. let scope = this;
  609. do {
  610. const data = scope.data[key];
  611. if (data != null) return data;
  612. } while (scope = scope.parent);
  613. }
  614. removeData(key) {
  615. let scope = this;
  616. do {
  617. const data = scope.data[key];
  618. if (data != null) scope.data[key] = null;
  619. } while (scope = scope.parent);
  620. }
  621. init() {
  622. if (!this.inited) {
  623. this.inited = true;
  624. this.crawl();
  625. }
  626. }
  627. crawl() {
  628. const path = this.path;
  629. this.references = Object.create(null);
  630. this.bindings = Object.create(null);
  631. this.globals = Object.create(null);
  632. this.uids = Object.create(null);
  633. this.data = Object.create(null);
  634. const programParent = this.getProgramParent();
  635. if (programParent.crawling) return;
  636. const state = {
  637. references: [],
  638. constantViolations: [],
  639. assignments: []
  640. };
  641. this.crawling = true;
  642. if (path.type !== "Program" && (0, _visitors.isExplodedVisitor)(collectorVisitor)) {
  643. for (const visit of collectorVisitor.enter) {
  644. visit.call(state, path, state);
  645. }
  646. const typeVisitors = collectorVisitor[path.type];
  647. if (typeVisitors) {
  648. for (const visit of typeVisitors.enter) {
  649. visit.call(state, path, state);
  650. }
  651. }
  652. }
  653. path.traverse(collectorVisitor, state);
  654. this.crawling = false;
  655. for (const path of state.assignments) {
  656. const ids = path.getAssignmentIdentifiers();
  657. for (const name of Object.keys(ids)) {
  658. if (path.scope.getBinding(name)) continue;
  659. programParent.addGlobal(ids[name]);
  660. }
  661. path.scope.registerConstantViolation(path);
  662. }
  663. for (const ref of state.references) {
  664. const binding = ref.scope.getBinding(ref.node.name);
  665. if (binding) {
  666. binding.reference(ref);
  667. } else {
  668. programParent.addGlobal(ref.node);
  669. }
  670. }
  671. for (const path of state.constantViolations) {
  672. path.scope.registerConstantViolation(path);
  673. }
  674. }
  675. push(opts) {
  676. let path = this.path;
  677. if (path.isPattern()) {
  678. path = this.getPatternParent().path;
  679. } else if (!path.isBlockStatement() && !path.isProgram()) {
  680. path = this.getBlockParent().path;
  681. }
  682. if (path.isSwitchStatement()) {
  683. path = (this.getFunctionParent() || this.getProgramParent()).path;
  684. }
  685. const {
  686. init,
  687. unique,
  688. kind = "var",
  689. id
  690. } = opts;
  691. if (!init && !unique && (kind === "var" || kind === "let") && path.isFunction() && !path.node.name && isCallExpression(path.parent, {
  692. callee: path.node
  693. }) && path.parent.arguments.length <= path.node.params.length && isIdentifier(id)) {
  694. path.pushContainer("params", id);
  695. path.scope.registerBinding("param", path.get("params")[path.node.params.length - 1]);
  696. return;
  697. }
  698. if (path.isLoop() || path.isCatchClause() || path.isFunction()) {
  699. path.ensureBlock();
  700. path = path.get("body");
  701. }
  702. const blockHoist = opts._blockHoist == null ? 2 : opts._blockHoist;
  703. const dataKey = `declaration:${kind}:${blockHoist}`;
  704. let declarPath = !unique && path.getData(dataKey);
  705. if (!declarPath) {
  706. const declar = variableDeclaration(kind, []);
  707. declar._blockHoist = blockHoist;
  708. [declarPath] = path.unshiftContainer("body", [declar]);
  709. if (!unique) path.setData(dataKey, declarPath);
  710. }
  711. const declarator = variableDeclarator(id, init);
  712. const len = declarPath.node.declarations.push(declarator);
  713. path.scope.registerBinding(kind, declarPath.get("declarations")[len - 1]);
  714. }
  715. getProgramParent() {
  716. let scope = this;
  717. do {
  718. if (scope.path.isProgram()) {
  719. return scope;
  720. }
  721. } while (scope = scope.parent);
  722. throw new Error("Couldn't find a Program");
  723. }
  724. getFunctionParent() {
  725. let scope = this;
  726. do {
  727. if (scope.path.isFunctionParent()) {
  728. return scope;
  729. }
  730. } while (scope = scope.parent);
  731. return null;
  732. }
  733. getBlockParent() {
  734. let scope = this;
  735. do {
  736. if (scope.path.isBlockParent()) {
  737. return scope;
  738. }
  739. } while (scope = scope.parent);
  740. throw new Error("We couldn't find a BlockStatement, For, Switch, Function, Loop or Program...");
  741. }
  742. getPatternParent() {
  743. let scope = this;
  744. do {
  745. if (!scope.path.isPattern()) {
  746. return scope.getBlockParent();
  747. }
  748. } while (scope = scope.parent.parent);
  749. throw new Error("We couldn't find a BlockStatement, For, Switch, Function, Loop or Program...");
  750. }
  751. getAllBindings() {
  752. const ids = Object.create(null);
  753. let scope = this;
  754. do {
  755. for (const key of Object.keys(scope.bindings)) {
  756. if (key in ids === false) {
  757. ids[key] = scope.bindings[key];
  758. }
  759. }
  760. scope = scope.parent;
  761. } while (scope);
  762. return ids;
  763. }
  764. bindingIdentifierEquals(name, node) {
  765. return this.getBindingIdentifier(name) === node;
  766. }
  767. getBinding(name) {
  768. let scope = this;
  769. let previousPath;
  770. do {
  771. const binding = scope.getOwnBinding(name);
  772. if (binding) {
  773. var _previousPath;
  774. if ((_previousPath = previousPath) != null && _previousPath.isPattern() && binding.kind !== "param" && binding.kind !== "local") {} else {
  775. return binding;
  776. }
  777. } else if (!binding && name === "arguments" && scope.path.isFunction() && !scope.path.isArrowFunctionExpression()) {
  778. break;
  779. }
  780. previousPath = scope.path;
  781. } while (scope = scope.parent);
  782. }
  783. getOwnBinding(name) {
  784. return this.bindings[name];
  785. }
  786. getBindingIdentifier(name) {
  787. var _this$getBinding2;
  788. return (_this$getBinding2 = this.getBinding(name)) == null ? void 0 : _this$getBinding2.identifier;
  789. }
  790. getOwnBindingIdentifier(name) {
  791. const binding = this.bindings[name];
  792. return binding == null ? void 0 : binding.identifier;
  793. }
  794. hasOwnBinding(name) {
  795. return !!this.getOwnBinding(name);
  796. }
  797. hasBinding(name, opts) {
  798. if (!name) return false;
  799. let scope = this;
  800. do {
  801. if (scope.hasOwnBinding(name)) {
  802. return true;
  803. }
  804. } while (scope = scope.parent);
  805. let noGlobals;
  806. let noUids;
  807. if (typeof opts === "object") {
  808. noGlobals = opts.noGlobals;
  809. noUids = opts.noUids;
  810. } else if (typeof opts === "boolean") {
  811. noGlobals = opts;
  812. }
  813. if (!noUids && this.hasUid(name)) return true;
  814. if (!noGlobals && Scope.globals.includes(name)) return true;
  815. if (!noGlobals && Scope.contextVariables.includes(name)) return true;
  816. return false;
  817. }
  818. parentHasBinding(name, opts) {
  819. var _this$parent;
  820. return (_this$parent = this.parent) == null ? void 0 : _this$parent.hasBinding(name, opts);
  821. }
  822. moveBindingTo(name, scope) {
  823. const info = this.getBinding(name);
  824. if (info) {
  825. info.scope.removeOwnBinding(name);
  826. info.scope = scope;
  827. scope.bindings[name] = info;
  828. }
  829. }
  830. removeOwnBinding(name) {
  831. delete this.bindings[name];
  832. }
  833. removeBinding(name) {
  834. var _this$getBinding3;
  835. (_this$getBinding3 = this.getBinding(name)) == null || _this$getBinding3.scope.removeOwnBinding(name);
  836. let scope = this;
  837. do {
  838. if (scope.uids[name]) {
  839. scope.uids[name] = false;
  840. }
  841. } while (scope = scope.parent);
  842. }
  843. hoistVariables(emit = id => this.push({
  844. id
  845. })) {
  846. this.crawl();
  847. const seen = new Set();
  848. for (const name of Object.keys(this.bindings)) {
  849. const binding = this.bindings[name];
  850. if (!binding) continue;
  851. const {
  852. path
  853. } = binding;
  854. if (!path.isVariableDeclarator()) continue;
  855. const {
  856. parent,
  857. parentPath
  858. } = path;
  859. if (parent.kind !== "var" || seen.has(parent)) continue;
  860. seen.add(path.parent);
  861. let firstId;
  862. const init = [];
  863. for (const decl of parent.declarations) {
  864. var _firstId;
  865. (_firstId = firstId) != null ? _firstId : firstId = decl.id;
  866. if (decl.init) {
  867. init.push(assignmentExpression("=", decl.id, decl.init));
  868. }
  869. const ids = Object.keys(getBindingIdentifiers(decl, false, true, true));
  870. for (const name of ids) {
  871. emit(identifier(name), decl.init != null);
  872. }
  873. }
  874. if (parentPath.parentPath.isFor({
  875. left: parent
  876. })) {
  877. parentPath.replaceWith(firstId);
  878. } else if (init.length === 0) {
  879. parentPath.remove();
  880. } else {
  881. const expr = init.length === 1 ? init[0] : sequenceExpression(init);
  882. if (parentPath.parentPath.isForStatement({
  883. init: parent
  884. })) {
  885. parentPath.replaceWith(expr);
  886. } else {
  887. parentPath.replaceWith(expressionStatement(expr));
  888. }
  889. }
  890. }
  891. }
  892. }
  893. exports.default = Scope;
  894. Scope.globals = Object.keys(_globals.builtin);
  895. Scope.contextVariables = ["arguments", "undefined", "Infinity", "NaN"];
  896. {
  897. Scope.prototype._renameFromMap = function _renameFromMap(map, oldName, newName, value) {
  898. if (map[oldName]) {
  899. map[newName] = value;
  900. map[oldName] = null;
  901. }
  902. };
  903. Scope.prototype.traverse = function (node, opts, state) {
  904. (0, _index.default)(node, opts, this, state, this.path);
  905. };
  906. Scope.prototype._generateUid = function _generateUid(name, i) {
  907. let id = name;
  908. if (i > 1) id += i;
  909. return `_${id}`;
  910. };
  911. Scope.prototype.toArray = function toArray(node, i, arrayLikeIsIterable) {
  912. if (isIdentifier(node)) {
  913. const binding = this.getBinding(node.name);
  914. if (binding != null && binding.constant && binding.path.isGenericType("Array")) {
  915. return node;
  916. }
  917. }
  918. if (isArrayExpression(node)) {
  919. return node;
  920. }
  921. if (isIdentifier(node, {
  922. name: "arguments"
  923. })) {
  924. return callExpression(memberExpression(memberExpression(memberExpression(identifier("Array"), identifier("prototype")), identifier("slice")), identifier("call")), [node]);
  925. }
  926. let helperName;
  927. const args = [node];
  928. if (i === true) {
  929. helperName = "toConsumableArray";
  930. } else if (typeof i === "number") {
  931. args.push(numericLiteral(i));
  932. helperName = "slicedToArray";
  933. } else {
  934. helperName = "toArray";
  935. }
  936. if (arrayLikeIsIterable) {
  937. args.unshift(this.path.hub.addHelper(helperName));
  938. helperName = "maybeArrayLike";
  939. }
  940. return callExpression(this.path.hub.addHelper(helperName), args);
  941. };
  942. Scope.prototype.getAllBindingsOfKind = function getAllBindingsOfKind(...kinds) {
  943. const ids = Object.create(null);
  944. for (const kind of kinds) {
  945. let scope = this;
  946. do {
  947. for (const name of Object.keys(scope.bindings)) {
  948. const binding = scope.bindings[name];
  949. if (binding.kind === kind) ids[name] = binding;
  950. }
  951. scope = scope.parent;
  952. } while (scope);
  953. }
  954. return ids;
  955. };
  956. Object.defineProperties(Scope.prototype, {
  957. parentBlock: {
  958. configurable: true,
  959. enumerable: true,
  960. get() {
  961. return this.path.parent;
  962. }
  963. },
  964. hub: {
  965. configurable: true,
  966. enumerable: true,
  967. get() {
  968. return this.path.hub;
  969. }
  970. }
  971. });
  972. }
  973. //# sourceMappingURL=index.js.map