index.js 29 KB

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