index.js 31 KB

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