index.js 24 KB

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