index.js 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  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 _t = require("@babel/types");
  10. var t = _t;
  11. var _cache = require("../cache.js");
  12. const globalsBuiltinLower = require("@babel/helper-globals/data/builtin-lower.json"),
  13. globalsBuiltinUpper = require("@babel/helper-globals/data/builtin-upper.json");
  14. const {
  15. assignmentExpression,
  16. callExpression,
  17. cloneNode,
  18. getBindingIdentifiers,
  19. identifier,
  20. isArrayExpression,
  21. isBinary,
  22. isCallExpression,
  23. isClass,
  24. isClassBody,
  25. isClassDeclaration,
  26. isExportAllDeclaration,
  27. isExportDefaultDeclaration,
  28. isExportNamedDeclaration,
  29. isFunctionDeclaration,
  30. isIdentifier,
  31. isImportDeclaration,
  32. isLiteral,
  33. isMemberExpression,
  34. isMethod,
  35. isModuleSpecifier,
  36. isNullLiteral,
  37. isObjectExpression,
  38. isProperty,
  39. isPureish,
  40. isRegExpLiteral,
  41. isSuper,
  42. isTaggedTemplateExpression,
  43. isTemplateLiteral,
  44. isThisExpression,
  45. isUnaryExpression,
  46. isVariableDeclaration,
  47. expressionStatement,
  48. matchesPattern,
  49. memberExpression,
  50. numericLiteral,
  51. toIdentifier,
  52. variableDeclaration,
  53. variableDeclarator,
  54. isRecordExpression,
  55. isTupleExpression,
  56. isObjectProperty,
  57. isTopicReference,
  58. isMetaProperty,
  59. isPrivateName,
  60. isExportDeclaration,
  61. buildUndefinedNode,
  62. sequenceExpression
  63. } = _t;
  64. function gatherNodeParts(node, parts) {
  65. switch (node == null ? void 0 : node.type) {
  66. default:
  67. if (isImportDeclaration(node) || isExportDeclaration(node)) {
  68. var _node$specifiers;
  69. if ((isExportAllDeclaration(node) || isExportNamedDeclaration(node) || isImportDeclaration(node)) && node.source) {
  70. gatherNodeParts(node.source, parts);
  71. } else if ((isExportNamedDeclaration(node) || isImportDeclaration(node)) && (_node$specifiers = node.specifiers) != null && _node$specifiers.length) {
  72. for (const e of node.specifiers) gatherNodeParts(e, parts);
  73. } else if ((isExportDefaultDeclaration(node) || isExportNamedDeclaration(node)) && node.declaration) {
  74. gatherNodeParts(node.declaration, parts);
  75. }
  76. } else if (isModuleSpecifier(node)) {
  77. gatherNodeParts(node.local, parts);
  78. } else if (isLiteral(node) && !isNullLiteral(node) && !isRegExpLiteral(node) && !isTemplateLiteral(node)) {
  79. parts.push(node.value);
  80. }
  81. break;
  82. case "MemberExpression":
  83. case "OptionalMemberExpression":
  84. case "JSXMemberExpression":
  85. gatherNodeParts(node.object, parts);
  86. gatherNodeParts(node.property, parts);
  87. break;
  88. case "Identifier":
  89. case "JSXIdentifier":
  90. parts.push(node.name);
  91. break;
  92. case "CallExpression":
  93. case "OptionalCallExpression":
  94. case "NewExpression":
  95. gatherNodeParts(node.callee, parts);
  96. break;
  97. case "ObjectExpression":
  98. case "ObjectPattern":
  99. for (const e of node.properties) {
  100. gatherNodeParts(e, parts);
  101. }
  102. break;
  103. case "SpreadElement":
  104. case "RestElement":
  105. gatherNodeParts(node.argument, parts);
  106. break;
  107. case "ObjectProperty":
  108. case "ObjectMethod":
  109. case "ClassProperty":
  110. case "ClassMethod":
  111. case "ClassPrivateProperty":
  112. case "ClassPrivateMethod":
  113. gatherNodeParts(node.key, parts);
  114. break;
  115. case "ThisExpression":
  116. parts.push("this");
  117. break;
  118. case "Super":
  119. parts.push("super");
  120. break;
  121. case "Import":
  122. case "ImportExpression":
  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. function resetScope(scope) {
  181. {
  182. scope.references = Object.create(null);
  183. scope.uids = Object.create(null);
  184. }
  185. scope.bindings = Object.create(null);
  186. scope.globals = Object.create(null);
  187. }
  188. {
  189. var NOT_LOCAL_BINDING = Symbol.for("should not be considered a local binding");
  190. }
  191. const collectorVisitor = {
  192. ForStatement(path) {
  193. const declar = path.get("init");
  194. if (declar.isVar()) {
  195. const {
  196. scope
  197. } = path;
  198. const parentScope = scope.getFunctionParent() || scope.getProgramParent();
  199. parentScope.registerBinding("var", declar);
  200. }
  201. },
  202. Declaration(path) {
  203. if (path.isBlockScoped()) return;
  204. if (path.isImportDeclaration()) return;
  205. if (path.isExportDeclaration()) return;
  206. const parent = path.scope.getFunctionParent() || path.scope.getProgramParent();
  207. parent.registerDeclaration(path);
  208. },
  209. ImportDeclaration(path) {
  210. const parent = path.scope.getBlockParent();
  211. parent.registerDeclaration(path);
  212. },
  213. TSImportEqualsDeclaration(path) {
  214. const parent = path.scope.getBlockParent();
  215. parent.registerDeclaration(path);
  216. },
  217. ReferencedIdentifier(path, state) {
  218. if (t.isTSQualifiedName(path.parent) && path.parent.right === path.node) {
  219. return;
  220. }
  221. if (path.parentPath.isTSImportEqualsDeclaration()) return;
  222. state.references.push(path);
  223. },
  224. ForXStatement(path, state) {
  225. const left = path.get("left");
  226. if (left.isPattern() || left.isIdentifier()) {
  227. state.constantViolations.push(path);
  228. } else if (left.isVar()) {
  229. const {
  230. scope
  231. } = path;
  232. const parentScope = scope.getFunctionParent() || scope.getProgramParent();
  233. parentScope.registerBinding("var", left);
  234. }
  235. },
  236. ExportDeclaration: {
  237. exit(path) {
  238. const {
  239. node,
  240. scope
  241. } = path;
  242. if (isExportAllDeclaration(node)) return;
  243. const declar = node.declaration;
  244. if (isClassDeclaration(declar) || isFunctionDeclaration(declar)) {
  245. const id = declar.id;
  246. if (!id) return;
  247. const binding = scope.getBinding(id.name);
  248. binding == null || binding.reference(path);
  249. } else if (isVariableDeclaration(declar)) {
  250. for (const decl of declar.declarations) {
  251. for (const name of Object.keys(getBindingIdentifiers(decl))) {
  252. const binding = scope.getBinding(name);
  253. binding == null || binding.reference(path);
  254. }
  255. }
  256. }
  257. }
  258. },
  259. LabeledStatement(path) {
  260. path.scope.getBlockParent().registerDeclaration(path);
  261. },
  262. AssignmentExpression(path, state) {
  263. state.assignments.push(path);
  264. },
  265. UpdateExpression(path, state) {
  266. state.constantViolations.push(path);
  267. },
  268. UnaryExpression(path, state) {
  269. if (path.node.operator === "delete") {
  270. state.constantViolations.push(path);
  271. }
  272. },
  273. BlockScoped(path) {
  274. let scope = path.scope;
  275. if (scope.path === path) scope = scope.parent;
  276. const parent = scope.getBlockParent();
  277. parent.registerDeclaration(path);
  278. if (path.isClassDeclaration() && path.node.id) {
  279. const id = path.node.id;
  280. const name = id.name;
  281. path.scope.bindings[name] = path.scope.parent.getBinding(name);
  282. }
  283. },
  284. CatchClause(path) {
  285. path.scope.registerBinding("let", path);
  286. },
  287. Function(path) {
  288. const params = path.get("params");
  289. for (const param of params) {
  290. path.scope.registerBinding("param", param);
  291. }
  292. if (path.isFunctionExpression() && path.node.id && !path.node.id[NOT_LOCAL_BINDING]) {
  293. path.scope.registerBinding("local", path.get("id"), path);
  294. }
  295. },
  296. ClassExpression(path) {
  297. if (path.node.id && !path.node.id[NOT_LOCAL_BINDING]) {
  298. path.scope.registerBinding("local", path.get("id"), path);
  299. }
  300. },
  301. TSTypeAnnotation(path) {
  302. path.skip();
  303. }
  304. };
  305. let scopeVisitor;
  306. let uid = 0;
  307. class Scope {
  308. constructor(path) {
  309. this.uid = void 0;
  310. this.path = void 0;
  311. this.block = void 0;
  312. this.inited = void 0;
  313. this.labels = void 0;
  314. this.bindings = void 0;
  315. this.referencesSet = void 0;
  316. this.globals = void 0;
  317. this.uidsSet = void 0;
  318. this.data = void 0;
  319. this.crawling = void 0;
  320. const {
  321. node
  322. } = path;
  323. const cached = _cache.scope.get(node);
  324. if ((cached == null ? void 0 : cached.path) === path) {
  325. return cached;
  326. }
  327. _cache.scope.set(node, this);
  328. this.uid = uid++;
  329. this.block = node;
  330. this.path = path;
  331. this.labels = new Map();
  332. this.inited = false;
  333. {
  334. Object.defineProperties(this, {
  335. references: {
  336. enumerable: true,
  337. configurable: true,
  338. writable: true,
  339. value: Object.create(null)
  340. },
  341. uids: {
  342. enumerable: true,
  343. configurable: true,
  344. writable: true,
  345. value: Object.create(null)
  346. }
  347. });
  348. }
  349. }
  350. get parent() {
  351. var _parent;
  352. let parent,
  353. path = this.path;
  354. do {
  355. var _path;
  356. const shouldSkip = path.key === "key" || path.listKey === "decorators";
  357. path = path.parentPath;
  358. if (shouldSkip && path.isMethod()) path = path.parentPath;
  359. if ((_path = path) != null && _path.isScope()) parent = path;
  360. } while (path && !parent);
  361. return (_parent = parent) == null ? void 0 : _parent.scope;
  362. }
  363. get references() {
  364. throw new Error("Scope#references is not available in Babel 8. Use Scope#referencesSet instead.");
  365. }
  366. get uids() {
  367. throw new Error("Scope#uids is not available in Babel 8. Use Scope#uidsSet instead.");
  368. }
  369. generateDeclaredUidIdentifier(name) {
  370. const id = this.generateUidIdentifier(name);
  371. this.push({
  372. id
  373. });
  374. return cloneNode(id);
  375. }
  376. generateUidIdentifier(name) {
  377. return identifier(this.generateUid(name));
  378. }
  379. generateUid(name = "temp") {
  380. name = toIdentifier(name).replace(/^_+/, "").replace(/\d+$/g, "");
  381. let uid;
  382. let i = 0;
  383. do {
  384. uid = `_${name}`;
  385. if (i >= 11) uid += i - 1;else if (i >= 9) uid += i - 9;else if (i >= 1) uid += i + 1;
  386. i++;
  387. } while (this.hasLabel(uid) || this.hasBinding(uid) || this.hasGlobal(uid) || this.hasReference(uid));
  388. const program = this.getProgramParent();
  389. {
  390. program.references[uid] = true;
  391. program.uids[uid] = true;
  392. }
  393. return uid;
  394. }
  395. generateUidBasedOnNode(node, defaultName) {
  396. const parts = [];
  397. gatherNodeParts(node, parts);
  398. let id = parts.join("$");
  399. id = id.replace(/^_/, "") || defaultName || "ref";
  400. return this.generateUid(id.slice(0, 20));
  401. }
  402. generateUidIdentifierBasedOnNode(node, defaultName) {
  403. return identifier(this.generateUidBasedOnNode(node, defaultName));
  404. }
  405. isStatic(node) {
  406. if (isThisExpression(node) || isSuper(node) || isTopicReference(node)) {
  407. return true;
  408. }
  409. if (isIdentifier(node)) {
  410. const binding = this.getBinding(node.name);
  411. if (binding) {
  412. return binding.constant;
  413. } else {
  414. return this.hasBinding(node.name);
  415. }
  416. }
  417. return false;
  418. }
  419. maybeGenerateMemoised(node, dontPush) {
  420. if (this.isStatic(node)) {
  421. return null;
  422. } else {
  423. const id = this.generateUidIdentifierBasedOnNode(node);
  424. if (!dontPush) {
  425. this.push({
  426. id
  427. });
  428. return cloneNode(id);
  429. }
  430. return id;
  431. }
  432. }
  433. checkBlockScopedCollisions(local, kind, name, id) {
  434. if (kind === "param") return;
  435. if (local.kind === "local") return;
  436. const duplicate = kind === "let" || local.kind === "let" || local.kind === "const" || local.kind === "module" || local.kind === "param" && kind === "const";
  437. if (duplicate) {
  438. throw this.path.hub.buildError(id, `Duplicate declaration "${name}"`, TypeError);
  439. }
  440. }
  441. rename(oldName, newName) {
  442. const binding = this.getBinding(oldName);
  443. if (binding) {
  444. newName || (newName = this.generateUidIdentifier(oldName).name);
  445. const renamer = new _renamer.default(binding, oldName, newName);
  446. {
  447. renamer.rename(arguments[2]);
  448. }
  449. }
  450. }
  451. dump() {
  452. const sep = "-".repeat(60);
  453. console.log(sep);
  454. let scope = this;
  455. do {
  456. console.log("#", scope.block.type);
  457. for (const name of Object.keys(scope.bindings)) {
  458. const binding = scope.bindings[name];
  459. console.log(" -", name, {
  460. constant: binding.constant,
  461. references: binding.references,
  462. violations: binding.constantViolations.length,
  463. kind: binding.kind
  464. });
  465. }
  466. } while (scope = scope.parent);
  467. console.log(sep);
  468. }
  469. hasLabel(name) {
  470. return !!this.getLabel(name);
  471. }
  472. getLabel(name) {
  473. return this.labels.get(name);
  474. }
  475. registerLabel(path) {
  476. this.labels.set(path.node.label.name, path);
  477. }
  478. registerDeclaration(path) {
  479. if (path.isLabeledStatement()) {
  480. this.registerLabel(path);
  481. } else if (path.isFunctionDeclaration()) {
  482. this.registerBinding("hoisted", path.get("id"), path);
  483. } else if (path.isVariableDeclaration()) {
  484. const declarations = path.get("declarations");
  485. const {
  486. kind
  487. } = path.node;
  488. for (const declar of declarations) {
  489. this.registerBinding(kind === "using" || kind === "await using" ? "const" : kind, declar);
  490. }
  491. } else if (path.isClassDeclaration()) {
  492. if (path.node.declare) return;
  493. this.registerBinding("let", path);
  494. } else if (path.isImportDeclaration()) {
  495. const isTypeDeclaration = path.node.importKind === "type" || path.node.importKind === "typeof";
  496. const specifiers = path.get("specifiers");
  497. for (const specifier of specifiers) {
  498. const isTypeSpecifier = isTypeDeclaration || specifier.isImportSpecifier() && (specifier.node.importKind === "type" || specifier.node.importKind === "typeof");
  499. this.registerBinding(isTypeSpecifier ? "unknown" : "module", specifier);
  500. }
  501. } else if (path.isExportDeclaration()) {
  502. const declar = path.get("declaration");
  503. if (declar.isClassDeclaration() || declar.isFunctionDeclaration() || declar.isVariableDeclaration()) {
  504. this.registerDeclaration(declar);
  505. }
  506. } else {
  507. this.registerBinding("unknown", path);
  508. }
  509. }
  510. buildUndefinedNode() {
  511. return buildUndefinedNode();
  512. }
  513. registerConstantViolation(path) {
  514. const ids = path.getAssignmentIdentifiers();
  515. for (const name of Object.keys(ids)) {
  516. var _this$getBinding;
  517. (_this$getBinding = this.getBinding(name)) == null || _this$getBinding.reassign(path);
  518. }
  519. }
  520. registerBinding(kind, path, bindingPath = path) {
  521. if (!kind) throw new ReferenceError("no `kind`");
  522. if (path.isVariableDeclaration()) {
  523. const declarators = path.get("declarations");
  524. for (const declar of declarators) {
  525. this.registerBinding(kind, declar);
  526. }
  527. return;
  528. }
  529. const parent = this.getProgramParent();
  530. const ids = path.getOuterBindingIdentifiers(true);
  531. for (const name of Object.keys(ids)) {
  532. {
  533. parent.references[name] = true;
  534. }
  535. for (const id of ids[name]) {
  536. const local = this.getOwnBinding(name);
  537. if (local) {
  538. if (local.identifier === id) continue;
  539. this.checkBlockScopedCollisions(local, kind, name, id);
  540. }
  541. if (local) {
  542. local.reassign(bindingPath);
  543. } else {
  544. this.bindings[name] = new _binding.default({
  545. identifier: id,
  546. scope: this,
  547. path: bindingPath,
  548. kind: kind
  549. });
  550. }
  551. }
  552. }
  553. }
  554. addGlobal(node) {
  555. this.globals[node.name] = node;
  556. }
  557. hasUid(name) {
  558. {
  559. let scope = this;
  560. do {
  561. if (scope.uids[name]) return true;
  562. } while (scope = scope.parent);
  563. return false;
  564. }
  565. }
  566. hasGlobal(name) {
  567. let scope = this;
  568. do {
  569. if (scope.globals[name]) return true;
  570. } while (scope = scope.parent);
  571. return false;
  572. }
  573. hasReference(name) {
  574. {
  575. return !!this.getProgramParent().references[name];
  576. }
  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. resetScope(this);
  680. this.data = Object.create(null);
  681. let scope = this;
  682. do {
  683. if (scope.crawling) return;
  684. if (scope.path.isProgram()) {
  685. break;
  686. }
  687. } while (scope = scope.parent);
  688. const programParent = scope;
  689. const state = {
  690. references: [],
  691. constantViolations: [],
  692. assignments: []
  693. };
  694. this.crawling = true;
  695. scopeVisitor || (scopeVisitor = _index.default.visitors.merge([{
  696. Scope(path) {
  697. resetScope(path.scope);
  698. }
  699. }, collectorVisitor]));
  700. if (path.type !== "Program") {
  701. for (const visit of scopeVisitor.enter) {
  702. visit.call(state, path, state);
  703. }
  704. const typeVisitors = scopeVisitor[path.type];
  705. if (typeVisitors) {
  706. for (const visit of typeVisitors.enter) {
  707. visit.call(state, path, state);
  708. }
  709. }
  710. }
  711. path.traverse(scopeVisitor, state);
  712. this.crawling = false;
  713. for (const path of state.assignments) {
  714. const ids = path.getAssignmentIdentifiers();
  715. for (const name of Object.keys(ids)) {
  716. if (path.scope.getBinding(name)) continue;
  717. programParent.addGlobal(ids[name]);
  718. }
  719. path.scope.registerConstantViolation(path);
  720. }
  721. for (const ref of state.references) {
  722. const binding = ref.scope.getBinding(ref.node.name);
  723. if (binding) {
  724. binding.reference(ref);
  725. } else {
  726. programParent.addGlobal(ref.node);
  727. }
  728. }
  729. for (const path of state.constantViolations) {
  730. path.scope.registerConstantViolation(path);
  731. }
  732. }
  733. push(opts) {
  734. let path = this.path;
  735. if (path.isPattern()) {
  736. path = this.getPatternParent().path;
  737. } else if (!path.isBlockStatement() && !path.isProgram()) {
  738. path = this.getBlockParent().path;
  739. }
  740. if (path.isSwitchStatement()) {
  741. path = (this.getFunctionParent() || this.getProgramParent()).path;
  742. }
  743. const {
  744. init,
  745. unique,
  746. kind = "var",
  747. id
  748. } = opts;
  749. if (!init && !unique && (kind === "var" || kind === "let") && path.isFunction() && !path.node.name && isCallExpression(path.parent, {
  750. callee: path.node
  751. }) && path.parent.arguments.length <= path.node.params.length && isIdentifier(id)) {
  752. path.pushContainer("params", id);
  753. path.scope.registerBinding("param", path.get("params")[path.node.params.length - 1]);
  754. return;
  755. }
  756. if (path.isLoop() || path.isCatchClause() || path.isFunction()) {
  757. path.ensureBlock();
  758. path = path.get("body");
  759. }
  760. const blockHoist = opts._blockHoist == null ? 2 : opts._blockHoist;
  761. const dataKey = `declaration:${kind}:${blockHoist}`;
  762. let declarPath = !unique && path.getData(dataKey);
  763. if (!declarPath) {
  764. const declar = variableDeclaration(kind, []);
  765. declar._blockHoist = blockHoist;
  766. [declarPath] = path.unshiftContainer("body", [declar]);
  767. if (!unique) path.setData(dataKey, declarPath);
  768. }
  769. const declarator = variableDeclarator(id, init);
  770. const len = declarPath.node.declarations.push(declarator);
  771. path.scope.registerBinding(kind, declarPath.get("declarations")[len - 1]);
  772. }
  773. getProgramParent() {
  774. let scope = this;
  775. do {
  776. if (scope.path.isProgram()) {
  777. return scope;
  778. }
  779. } while (scope = scope.parent);
  780. throw new Error("Couldn't find a Program");
  781. }
  782. getFunctionParent() {
  783. let scope = this;
  784. do {
  785. if (scope.path.isFunctionParent()) {
  786. return scope;
  787. }
  788. } while (scope = scope.parent);
  789. return null;
  790. }
  791. getBlockParent() {
  792. let scope = this;
  793. do {
  794. if (scope.path.isBlockParent()) {
  795. return scope;
  796. }
  797. } while (scope = scope.parent);
  798. throw new Error("We couldn't find a BlockStatement, For, Switch, Function, Loop or Program...");
  799. }
  800. getPatternParent() {
  801. let scope = this;
  802. do {
  803. if (!scope.path.isPattern()) {
  804. return scope.getBlockParent();
  805. }
  806. } while (scope = scope.parent.parent);
  807. throw new Error("We couldn't find a BlockStatement, For, Switch, Function, Loop or Program...");
  808. }
  809. getAllBindings() {
  810. const ids = Object.create(null);
  811. let scope = this;
  812. do {
  813. for (const key of Object.keys(scope.bindings)) {
  814. if (key in ids === false) {
  815. ids[key] = scope.bindings[key];
  816. }
  817. }
  818. scope = scope.parent;
  819. } while (scope);
  820. return ids;
  821. }
  822. bindingIdentifierEquals(name, node) {
  823. return this.getBindingIdentifier(name) === node;
  824. }
  825. getBinding(name) {
  826. let scope = this;
  827. let previousPath;
  828. do {
  829. const binding = scope.getOwnBinding(name);
  830. if (binding) {
  831. var _previousPath;
  832. if ((_previousPath = previousPath) != null && _previousPath.isPattern() && binding.kind !== "param" && binding.kind !== "local") {} else {
  833. return binding;
  834. }
  835. } else if (!binding && name === "arguments" && scope.path.isFunction() && !scope.path.isArrowFunctionExpression()) {
  836. break;
  837. }
  838. previousPath = scope.path;
  839. } while (scope = scope.parent);
  840. }
  841. getOwnBinding(name) {
  842. return this.bindings[name];
  843. }
  844. getBindingIdentifier(name) {
  845. var _this$getBinding2;
  846. return (_this$getBinding2 = this.getBinding(name)) == null ? void 0 : _this$getBinding2.identifier;
  847. }
  848. getOwnBindingIdentifier(name) {
  849. const binding = this.bindings[name];
  850. return binding == null ? void 0 : binding.identifier;
  851. }
  852. hasOwnBinding(name) {
  853. return !!this.getOwnBinding(name);
  854. }
  855. hasBinding(name, opts) {
  856. if (!name) return false;
  857. let noGlobals;
  858. let noUids;
  859. let upToScope;
  860. if (typeof opts === "object") {
  861. noGlobals = opts.noGlobals;
  862. noUids = opts.noUids;
  863. upToScope = opts.upToScope;
  864. } else if (typeof opts === "boolean") {
  865. noGlobals = opts;
  866. }
  867. let scope = this;
  868. do {
  869. if (upToScope === scope) {
  870. break;
  871. }
  872. if (scope.hasOwnBinding(name)) {
  873. return true;
  874. }
  875. } while (scope = scope.parent);
  876. if (!noUids && this.hasUid(name)) return true;
  877. if (!noGlobals && Scope.globals.includes(name)) return true;
  878. if (!noGlobals && Scope.contextVariables.includes(name)) return true;
  879. return false;
  880. }
  881. parentHasBinding(name, opts) {
  882. var _this$parent;
  883. return (_this$parent = this.parent) == null ? void 0 : _this$parent.hasBinding(name, opts);
  884. }
  885. moveBindingTo(name, scope) {
  886. const info = this.getBinding(name);
  887. if (info) {
  888. info.scope.removeOwnBinding(name);
  889. info.scope = scope;
  890. scope.bindings[name] = info;
  891. }
  892. }
  893. removeOwnBinding(name) {
  894. delete this.bindings[name];
  895. }
  896. removeBinding(name) {
  897. var _this$getBinding3;
  898. (_this$getBinding3 = this.getBinding(name)) == null || _this$getBinding3.scope.removeOwnBinding(name);
  899. {
  900. let scope = this;
  901. do {
  902. if (scope.uids[name]) {
  903. scope.uids[name] = false;
  904. }
  905. } while (scope = scope.parent);
  906. }
  907. }
  908. hoistVariables(emit = id => this.push({
  909. id
  910. })) {
  911. this.crawl();
  912. const seen = new Set();
  913. for (const name of Object.keys(this.bindings)) {
  914. const binding = this.bindings[name];
  915. if (!binding) continue;
  916. const {
  917. path
  918. } = binding;
  919. if (!path.isVariableDeclarator()) continue;
  920. const {
  921. parent,
  922. parentPath
  923. } = path;
  924. if (parent.kind !== "var" || seen.has(parent)) continue;
  925. seen.add(path.parent);
  926. let firstId;
  927. const init = [];
  928. for (const decl of parent.declarations) {
  929. 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 = [...globalsBuiltinLower, ...globalsBuiltinUpper];
  959. Scope.contextVariables = ["arguments", "undefined", "Infinity", "NaN"];
  960. {
  961. Scope.prototype._renameFromMap = function _renameFromMap(map, oldName, newName, value) {
  962. if (map[oldName]) {
  963. map[newName] = value;
  964. map[oldName] = null;
  965. }
  966. };
  967. Scope.prototype.traverse = function (node, opts, state) {
  968. (0, _index.default)(node, opts, this, state, this.path);
  969. };
  970. Scope.prototype._generateUid = function _generateUid(name, i) {
  971. let id = name;
  972. if (i > 1) id += i;
  973. return `_${id}`;
  974. };
  975. Scope.prototype.toArray = function toArray(node, i, arrayLikeIsIterable) {
  976. if (isIdentifier(node)) {
  977. const binding = this.getBinding(node.name);
  978. if (binding != null && binding.constant && binding.path.isGenericType("Array")) {
  979. return node;
  980. }
  981. }
  982. if (isArrayExpression(node)) {
  983. return node;
  984. }
  985. if (isIdentifier(node, {
  986. name: "arguments"
  987. })) {
  988. return callExpression(memberExpression(memberExpression(memberExpression(identifier("Array"), identifier("prototype")), identifier("slice")), identifier("call")), [node]);
  989. }
  990. let helperName;
  991. const args = [node];
  992. if (i === true) {
  993. helperName = "toConsumableArray";
  994. } else if (typeof i === "number") {
  995. args.push(numericLiteral(i));
  996. helperName = "slicedToArray";
  997. } else {
  998. helperName = "toArray";
  999. }
  1000. if (arrayLikeIsIterable) {
  1001. args.unshift(this.path.hub.addHelper(helperName));
  1002. helperName = "maybeArrayLike";
  1003. }
  1004. return callExpression(this.path.hub.addHelper(helperName), args);
  1005. };
  1006. Scope.prototype.getAllBindingsOfKind = function getAllBindingsOfKind(...kinds) {
  1007. const ids = Object.create(null);
  1008. for (const kind of kinds) {
  1009. let scope = this;
  1010. do {
  1011. for (const name of Object.keys(scope.bindings)) {
  1012. const binding = scope.bindings[name];
  1013. if (binding.kind === kind) ids[name] = binding;
  1014. }
  1015. scope = scope.parent;
  1016. } while (scope);
  1017. }
  1018. return ids;
  1019. };
  1020. Object.defineProperties(Scope.prototype, {
  1021. parentBlock: {
  1022. configurable: true,
  1023. enumerable: true,
  1024. get() {
  1025. return this.path.parent;
  1026. }
  1027. },
  1028. hub: {
  1029. configurable: true,
  1030. enumerable: true,
  1031. get() {
  1032. return this.path.hub;
  1033. }
  1034. }
  1035. });
  1036. }
  1037. //# sourceMappingURL=index.js.map