Debian Codegraph @

packages/babel-traverse/src/scope/index.ts

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 import Renamer from "./lib/renamer";
2 import type NodePath from "../path";
3 import traverse from "../index";
4 import type { TraverseOptions } from "../index";
5 import Binding from "./binding";
6 import type { BindingKind } from "./binding";
7 import globals from "globals";
8 import {
9 NOT_LOCAL_BINDING,
10 callExpression,
11 cloneNode,
12 getBindingIdentifiers,
13 identifier,
14 isArrayExpression,
15 isBinary,
16 isClass,
17 isClassBody,
18 isClassDeclaration,
19 isExportAllDeclaration,
20 isExportDefaultDeclaration,
21 isExportNamedDeclaration,
22 isFunctionDeclaration,
23 isIdentifier,
24 isImportDeclaration,
25 isLiteral,
26 isMethod,
27 isModuleSpecifier,
28 isNullLiteral,
29 isObjectExpression,
30 isProperty,
31 isPureish,
32 isRegExpLiteral,
33 isSuper,
34 isTaggedTemplateExpression,
35 isTemplateLiteral,
36 isThisExpression,
37 isUnaryExpression,
38 isVariableDeclaration,
39 matchesPattern,
40 memberExpression,
41 numericLiteral,
42 toIdentifier,
43 unaryExpression,
44 variableDeclaration,
45 variableDeclarator,
46 isRecordExpression,
47 isTupleExpression,
48 isObjectProperty,
49 isTopicReference,
50 isMetaProperty,
51 isPrivateName,
52 isExportDeclaration,
53 } from "@babel/types";
54 import type * as t from "@babel/types";
55 import { scope as scopeCache } from "../cache";
56 import type { Visitor } from "../types";
57
58 type NodePart = string | number | boolean;
59 // Recursively gathers the identifying names of a node.
60 function gatherNodeParts(node: t.Node, parts: NodePart[]) {
61 switch (node?.type) {
62 default:
63 if (isImportDeclaration(node) || isExportDeclaration(node)) {
64 if (
65 (isExportAllDeclaration(node) ||
66 isExportNamedDeclaration(node) ||
67 isImportDeclaration(node)) &&
68 node.source
69 ) {
70 gatherNodeParts(node.source, parts);
71 } else if (
72 (isExportNamedDeclaration(node) || isImportDeclaration(node)) &&
73 node.specifiers &&
74 node.specifiers.length
75 ) {
76 for (const e of node.specifiers) gatherNodeParts(e, parts);
77 } else if (
78 (isExportDefaultDeclaration(node) ||
79 isExportNamedDeclaration(node)) &&
80 node.declaration
81 ) {
82 gatherNodeParts(node.declaration, parts);
83 }
84 } else if (isModuleSpecifier(node)) {
85 // todo(flow->ts): should condition instead be:
86 // ```
87 // t.isExportSpecifier(node) ||
88 // t.isImportDefaultSpecifier(node) ||
89 // t.isImportNamespaceSpecifier(node) ||
90 // t.isImportSpecifier(node)
91 // ```
92 // allowing only nodes with `.local`?
93 // @ts-expect-error todo(flow->ts)
94 gatherNodeParts(node.local, parts);
95 } else if (
96 isLiteral(node) &&
97 !isNullLiteral(node) &&
98 !isRegExpLiteral(node) &&
99 !isTemplateLiteral(node)
100 ) {
101 parts.push(node.value);
102 }
103 break;
104
105 case "MemberExpression":
106 case "OptionalMemberExpression":
107 case "JSXMemberExpression":
108 gatherNodeParts(node.object, parts);
109 gatherNodeParts(node.property, parts);
110 break;
111
112 case "Identifier":
113 case "JSXIdentifier":
114 parts.push(node.name);
115 break;
116
117 case "CallExpression":
118 case "OptionalCallExpression":
119 case "NewExpression":
120 gatherNodeParts(node.callee, parts);
121 break;
122
123 case "ObjectExpression":
124 case "ObjectPattern":
125 for (const e of node.properties) {
126 gatherNodeParts(e, parts);
127 }
128 break;
129
130 case "SpreadElement":
131 case "RestElement":
132 gatherNodeParts(node.argument, parts);
133 break;
134
135 case "ObjectProperty":
136 case "ObjectMethod":
137 case "ClassProperty":
138 case "ClassMethod":
139 case "ClassPrivateProperty":
140 case "ClassPrivateMethod":
141 gatherNodeParts(node.key, parts);
142 break;
143
144 case "ThisExpression":
145 parts.push("this");
146 break;
147
148 case "Super":
149 parts.push("super");
150 break;
151
152 case "Import":
153 parts.push("import");
154 break;
155
156 case "DoExpression":
157 parts.push("do");
158 break;
159
160 case "YieldExpression":
161 parts.push("yield");
162 gatherNodeParts(node.argument, parts);
163 break;
164
165 case "AwaitExpression":
166 parts.push("await");
167 gatherNodeParts(node.argument, parts);
168 break;
169
170 case "AssignmentExpression":
171 gatherNodeParts(node.left, parts);
172 break;
173
174 case "VariableDeclarator":
175 gatherNodeParts(node.id, parts);
176 break;
177
178 case "FunctionExpression":
179 case "FunctionDeclaration":
180 case "ClassExpression":
181 case "ClassDeclaration":
182 gatherNodeParts(node.id, parts);
183 break;
184
185 case "PrivateName":
186 gatherNodeParts(node.id, parts);
187 break;
188
189 case "ParenthesizedExpression":
190 gatherNodeParts(node.expression, parts);
191 break;
192
193 case "UnaryExpression":
194 case "UpdateExpression":
195 gatherNodeParts(node.argument, parts);
196 break;
197
198 case "MetaProperty":
199 gatherNodeParts(node.meta, parts);
200 gatherNodeParts(node.property, parts);
201 break;
202
203 case "JSXElement":
204 gatherNodeParts(node.openingElement, parts);
205 break;
206
207 case "JSXOpeningElement":
208 gatherNodeParts(node.name, parts);
209 break;
210
211 case "JSXFragment":
212 gatherNodeParts(node.openingFragment, parts);
213 break;
214
215 case "JSXOpeningFragment":
216 parts.push("Fragment");
217 break;
218
219 case "JSXNamespacedName":
220 gatherNodeParts(node.namespace, parts);
221 gatherNodeParts(node.name, parts);
222 break;
223 }
224 }
225
226 //
227 interface CollectVisitorState {
228 assignments: NodePath<t.AssignmentExpression>[];
229 references: NodePath<t.Identifier | t.JSXIdentifier>[];
230 constantViolations: NodePath[];
231 }
232
233 const collectorVisitor: Visitor<CollectVisitorState> = {
234 ForStatement(path) {
235 const declar = path.get("init");
236 // delegate block scope handling to the `BlockScoped` method
237 if (declar.isVar()) {
238 const { scope } = path;
239 const parentScope = scope.getFunctionParent() || scope.getProgramParent();
240 parentScope.registerBinding("var", declar);
241 }
242 },
243
244 Declaration(path) {
245 // delegate block scope handling to the `BlockScoped` method
246 if (path.isBlockScoped()) return;
247
248 // delegate import handing to the `ImportDeclaration` method
249 if (path.isImportDeclaration()) return;
250
251 // this will be hit again once we traverse into it after this iteration
252 if (path.isExportDeclaration()) return;
253
254 // we've ran into a declaration!
255 const parent =
256 path.scope.getFunctionParent() || path.scope.getProgramParent();
257 parent.registerDeclaration(path);
258 },
259
260 ImportDeclaration(path) {
261 // import may only appear in the top level or inside a module/namespace (for TS/flow)
262 const parent = path.scope.getBlockParent();
263
264 parent.registerDeclaration(path);
265 },
266
267 ReferencedIdentifier(path, state) {
268 state.references.push(path);
269 },
270
271 ForXStatement(path, state) {
272 const left = path.get("left");
273 if (left.isPattern() || left.isIdentifier()) {
274 state.constantViolations.push(path);
275 }
276 // delegate block scope handling to the `BlockScoped` method
277 else if (left.isVar()) {
278 const { scope } = path;
279 const parentScope = scope.getFunctionParent() || scope.getProgramParent();
280 parentScope.registerBinding("var", left);
281 }
282 },
283
284 ExportDeclaration: {
285 exit(path) {
286 const { node, scope } = path;
287 // ExportAllDeclaration does not have `declaration`
288 if (isExportAllDeclaration(node)) return;
289 const declar = node.declaration;
290 if (isClassDeclaration(declar) || isFunctionDeclaration(declar)) {
291 const id = declar.id;
292 if (!id) return;
293
294 const binding = scope.getBinding(id.name);
295 binding?.reference(path);
296 } else if (isVariableDeclaration(declar)) {
297 for (const decl of declar.declarations) {
298 for (const name of Object.keys(getBindingIdentifiers(decl))) {
299 const binding = scope.getBinding(name);
300 binding?.reference(path);
301 }
302 }
303 }
304 },
305 },
306
307 LabeledStatement(path) {
308 path.scope.getBlockParent().registerDeclaration(path);
309 },
310
311 AssignmentExpression(path, state) {
312 state.assignments.push(path);
313 },
314
315 UpdateExpression(path, state) {
316 state.constantViolations.push(path);
317 },
318
319 UnaryExpression(path, state) {
320 if (path.node.operator === "delete") {
321 state.constantViolations.push(path);
322 }
323 },
324
325 BlockScoped(path) {
326 let scope = path.scope;
327 if (scope.path === path) scope = scope.parent;
328
329 const parent = scope.getBlockParent();
330 parent.registerDeclaration(path);
331
332 // Register class identifier in class' scope if this is a class declaration.
333 if (path.isClassDeclaration() && path.node.id) {
334 const id = path.node.id;
335 const name = id.name;
336
337 path.scope.bindings[name] = path.scope.parent.getBinding(name);
338 }
339 },
340
341 CatchClause(path) {
342 path.scope.registerBinding("let", path);
343 },
344
345 Function(path) {
346 const params: Array<NodePath> = path.get("params");
347 for (const param of params) {
348 path.scope.registerBinding("param", param);
349 }
350
351 // Register function expression id after params. When the id
352 // collides with a function param, the id effectively can't be
353 // referenced: here we registered it as a constantViolation
354 if (
355 path.isFunctionExpression() &&
356 path.has("id") &&
357 // @ts-expect-error Fixme: document symbol ast properties
358 !path.get("id").node[NOT_LOCAL_BINDING]
359 ) {
360 path.scope.registerBinding("local", path.get("id"), path);
361 }
362 },
363
364 ClassExpression(path) {
365 if (
366 path.has("id") &&
367 // @ts-expect-error Fixme: document symbol ast properties
368 !path.get("id").node[NOT_LOCAL_BINDING]
369 ) {
370 path.scope.registerBinding("local", path);
371 }
372 },
373 };
374
375 let uid = 0;
376
377 export type { Binding };
378
379 export default class Scope {
380 uid;
381
382 path: NodePath;
383 block: t.Pattern | t.Scopable;
384
385 labels;
386 inited;
387
388 bindings: { [name: string]: Binding };
389 references: { [name: string]: true };
390 globals: { [name: string]: t.Identifier | t.JSXIdentifier };
391 uids: { [name: string]: boolean };
392 data: { [key: string | symbol]: unknown };
393 crawling: boolean;
394
395 /**
396 * This searches the current "scope" and collects all references/bindings
397 * within.
398 */
399 constructor(path: NodePath<t.Pattern | t.Scopable>) {
400 const { node } = path;
401 const cached = scopeCache.get(node);
402 // Sometimes, a scopable path is placed higher in the AST tree.
403 // In these cases, have to create a new Scope.
404 if (cached?.path === path) {
405 return cached;
406 }
407 scopeCache.set(node, this);
408
409 this.uid = uid++;
410
411 this.block = node;
412 this.path = path;
413
414 this.labels = new Map();
415 this.inited = false;
416 }
417
418 /**
419 * Globals.
420 */
421
422 static globals = Object.keys(globals.builtin);
423
424 /**
425 * Variables available in current context.
426 */
427
428 static contextVariables = ["arguments", "undefined", "Infinity", "NaN"];
429
430 get parent() {
431 let parent,
432 path = this.path;
433 do {
434 // Skip method scope if coming from inside computed key or decorator expression
435 const shouldSkip = path.key === "key" || path.listKey === "decorators";
436 path = path.parentPath;
437 if (shouldSkip && path.isMethod()) path = path.parentPath;
438 if (path && path.isScope()) parent = path;
439 } while (path && !parent);
440
441 return parent?.scope;
442 }
443
444 get parentBlock() {
445 return this.path.parent;
446 }
447
448 get hub() {
449 return this.path.hub;
450 }
451
452 traverse<S>(
453 node: t.Node | t.Node[],
454 opts: TraverseOptions<S>,
455 state: S,
456 ): void;
457 traverse(node: t.Node | t.Node[], opts?: TraverseOptions, state?: any): void;
458 /**
459 * Traverse node with current scope and path.
460 *
461 * !!! WARNING !!!
462 * This method assumes that `this.path` is the NodePath representing `node`.
463 * After running the traversal, the `.parentPath` of the NodePaths
464 * corresponding to `node`'s children will be set to `this.path`.
465 *
466 * There is no good reason to use this method, since the only safe way to use
467 * it is equivalent to `scope.path.traverse(opts, state)`.
468 */
469 traverse<S>(node: any, opts: any, state?: S) {
470 traverse(node, opts, this, state, this.path);
471 }
472
473 /**
474 * Generate a unique identifier and add it to the current scope.
475 */
476
477 generateDeclaredUidIdentifier(name?: string) {
478 const id = this.generateUidIdentifier(name);
479 this.push({ id });
480 return cloneNode(id);
481 }
482
483 /**
484 * Generate a unique identifier.
485 */
486
487 generateUidIdentifier(name?: string) {
488 return identifier(this.generateUid(name));
489 }
490
491 /**
492 * Generate a unique `_id1` binding.
493 */
494
495 generateUid(name: string = "temp"): string {
496 name = toIdentifier(name)
497 .replace(/^_+/, "")
498 .replace(/[0-9]+$/g, "");
499
500 let uid;
501 let i = 1;
502 do {
503 uid = this._generateUid(name, i);
504 i++;
505 } while (
506 this.hasLabel(uid) ||
507 this.hasBinding(uid) ||
508 this.hasGlobal(uid) ||
509 this.hasReference(uid)
510 );
511
512 const program = this.getProgramParent();
513 program.references[uid] = true;
514 program.uids[uid] = true;
515
516 return uid;
517 }
518
519 /**
520 * Generate an `_id1`.
521 */
522
523 _generateUid(name: string, i: number) {
524 let id = name;
525 if (i > 1) id += i;
526 return `_${id}`;
527 }
528
529 generateUidBasedOnNode(node: t.Node, defaultName?: string) {
530 const parts: NodePart[] = [];
531 gatherNodeParts(node, parts);
532
533 let id = parts.join("$");
534 id = id.replace(/^_/, "") || defaultName || "ref";
535
536 return this.generateUid(id.slice(0, 20));
537 }
538
539 /**
540 * Generate a unique identifier based on a node.
541 */
542
543 generateUidIdentifierBasedOnNode(node: t.Node, defaultName?: string) {
544 return identifier(this.generateUidBasedOnNode(node, defaultName));
545 }
546
547 /**
548 * Determine whether evaluating the specific input `node` is a consequenceless reference. ie.
549 * evaluating it wont result in potentially arbitrary code from being ran. The following are
550 * allowed and determined not to cause side effects:
551 *
552 * - `this` expressions
553 * - `super` expressions
554 * - Bound identifiers
555 */
556
557 isStatic(node: t.Node): boolean {
558 if (isThisExpression(node) || isSuper(node) || isTopicReference(node)) {
559 return true;
560 }
561
562 if (isIdentifier(node)) {
563 const binding = this.getBinding(node.name);
564 if (binding) {
565 return binding.constant;
566 } else {
567 return this.hasBinding(node.name);
568 }
569 }
570
571 return false;
572 }
573
574 /**
575 * Possibly generate a memoised identifier if it is not static and has consequences.
576 */
577
578 maybeGenerateMemoised(node: t.Node, dontPush?: boolean) {
579 if (this.isStatic(node)) {
580 return null;
581 } else {
582 const id = this.generateUidIdentifierBasedOnNode(node);
583 if (!dontPush) {
584 this.push({ id });
585 return cloneNode(id);
586 }
587 return id;
588 }
589 }
590
591 checkBlockScopedCollisions(
592 local: Binding,
593 kind: BindingKind,
594 name: string,
595 id: any,
596 ) {
597 // ignore parameters
598 if (kind === "param") return;
599
600 // Ignore existing binding if it's the name of the current function or
601 // class expression
602 if (local.kind === "local") return;
603
604 const duplicate =
605 // don't allow duplicate bindings to exist alongside
606 kind === "let" ||
607 local.kind === "let" ||
608 local.kind === "const" ||
609 local.kind === "module" ||
610 // don't allow a local of param with a kind of let
611 (local.kind === "param" && kind === "const");
612
613 if (duplicate) {
614 throw this.hub.buildError(
615 id,
616 `Duplicate declaration "${name}"`,
617 TypeError,
618 );
619 }
620 }
621
622 rename(
623 oldName: string,
624 newName?: string,
625 // prettier-ignore
626 /* Babel 7 - block?: t.Pattern | t.Scopable */
627 ) {
628 const binding = this.getBinding(oldName);
629 if (binding) {
630 newName ||= this.generateUidIdentifier(oldName).name;
631 const renamer = new Renamer(binding, oldName, newName);
632 return process.env.BABEL_8_BREAKING
633 ? renamer.rename()
634 : // @ts-expect-error: babel 7->8
635 renamer.rename(arguments[2]);
636 }
637 }
638
639 /** @deprecated Not used in our codebase */
640 _renameFromMap(
641 map: Record<string | symbol, unknown>,
642 oldName: string | symbol,
643 newName: string | symbol,
644 value: unknown,
645 ) {
646 if (map[oldName]) {
647 map[newName] = value;
648 map[oldName] = null;
649 }
650 }
651
652 dump() {
653 const sep = "-".repeat(60);
654 console.log(sep);
655 let scope: Scope = this;
656 do {
657 console.log("#", scope.block.type);
658 for (const name of Object.keys(scope.bindings)) {
659 const binding = scope.bindings[name];
660 console.log(" -", name, {
661 constant: binding.constant,
662 references: binding.references,
663 violations: binding.constantViolations.length,
664 kind: binding.kind,
665 });
666 }
667 } while ((scope = scope.parent));
668 console.log(sep);
669 }
670
671 // TODO: (Babel 8) Split i in two parameters, and use an object of flags
672 toArray(
673 node: t.Node,
674 i?: number | boolean,
675 arrayLikeIsIterable?: boolean | void,
676 ) {
677 if (isIdentifier(node)) {
678 const binding = this.getBinding(node.name);
679 if (binding?.constant && binding.path.isGenericType("Array")) {
680 return node;
681 }
682 }
683
684 if (isArrayExpression(node)) {
685 return node;
686 }
687
688 if (isIdentifier(node, { name: "arguments" })) {
689 return callExpression(
690 memberExpression(
691 memberExpression(
692 memberExpression(identifier("Array"), identifier("prototype")),
693 identifier("slice"),
694 ),
695 identifier("call"),
696 ),
697 [node],
698 );
699 }
700
701 let helperName;
702 const args = [node];
703 if (i === true) {
704 // Used in array-spread to create an array.
705 helperName = "toConsumableArray";
706 } else if (typeof i === "number") {
707 args.push(numericLiteral(i));
708
709 // Used in array-rest to create an array from a subset of an iterable.
710 helperName = "slicedToArray";
711 // TODO if (this.hub.isLoose("es6.forOf")) helperName += "-loose";
712 } else {
713 // Used in array-rest to create an array
714 helperName = "toArray";
715 }
716
717 if (arrayLikeIsIterable) {
718 args.unshift(this.hub.addHelper(helperName));
719 helperName = "maybeArrayLike";
720 }
721
722 // @ts-expect-error todo(flow->ts): t.Node is not valid to use in args, function argument typeneeds to be clarified
723 return callExpression(this.hub.addHelper(helperName), args);
724 }
725
726 hasLabel(name: string) {
727 return !!this.getLabel(name);
728 }
729
730 getLabel(name: string) {
731 return this.labels.get(name);
732 }
733
734 registerLabel(path: NodePath<t.LabeledStatement>) {
735 this.labels.set(path.node.label.name, path);
736 }
737
738 registerDeclaration(path: NodePath) {
739 if (path.isLabeledStatement()) {
740 this.registerLabel(path);
741 } else if (path.isFunctionDeclaration()) {
742 this.registerBinding("hoisted", path.get("id"), path);
743 } else if (path.isVariableDeclaration()) {
744 const declarations = path.get("declarations");
745 const { kind } = path.node;
746 for (const declar of declarations) {
747 this.registerBinding(kind === "using" ? "const" : kind, declar);
748 }
749 } else if (path.isClassDeclaration()) {
750 if (path.node.declare) return;
751 this.registerBinding("let", path);
752 } else if (path.isImportDeclaration()) {
753 const isTypeDeclaration =
754 path.node.importKind === "type" || path.node.importKind === "typeof";
755 const specifiers = path.get("specifiers");
756 for (const specifier of specifiers) {
757 const isTypeSpecifier =
758 isTypeDeclaration ||
759 (specifier.isImportSpecifier() &&
760 (specifier.node.importKind === "type" ||
761 specifier.node.importKind === "typeof"));
762
763 this.registerBinding(isTypeSpecifier ? "unknown" : "module", specifier);
764 }
765 } else if (path.isExportDeclaration()) {
766 // todo: improve babel-types
767 const declar = path.get("declaration") as NodePath;
768 if (
769 declar.isClassDeclaration() ||
770 declar.isFunctionDeclaration() ||
771 declar.isVariableDeclaration()
772 ) {
773 this.registerDeclaration(declar);
774 }
775 } else {
776 this.registerBinding("unknown", path);
777 }
778 }
779
780 buildUndefinedNode() {
781 return unaryExpression("void", numericLiteral(0), true);
782 }
783
784 registerConstantViolation(path: NodePath) {
785 const ids = path.getBindingIdentifiers();
786 for (const name of Object.keys(ids)) {
787 const binding = this.getBinding(name);
788 if (binding) binding.reassign(path);
789 }
790 }
791
792 registerBinding(
793 kind: Binding["kind"],
794 path: NodePath,
795 bindingPath: NodePath = path,
796 ) {
797 if (!kind) throw new ReferenceError("no `kind`");
798
799 if (path.isVariableDeclaration()) {
800 const declarators: Array<NodePath> = path.get("declarations");
801 for (const declar of declarators) {
802 this.registerBinding(kind, declar);
803 }
804 return;
805 }
806
807 const parent = this.getProgramParent();
808 const ids = path.getOuterBindingIdentifiers(true);
809
810 for (const name of Object.keys(ids)) {
811 parent.references[name] = true;
812
813 for (const id of ids[name]) {
814 const local = this.getOwnBinding(name);
815
816 if (local) {
817 // same identifier so continue safely as we're likely trying to register it
818 // multiple times
819 if (local.identifier === id) continue;
820
821 this.checkBlockScopedCollisions(local, kind, name, id);
822 }
823
824 // A redeclaration of an existing variable is a modification
825 if (local) {
826 this.registerConstantViolation(bindingPath);
827 } else {
828 this.bindings[name] = new Binding({
829 identifier: id,
830 scope: this,
831 path: bindingPath,
832 kind: kind,
833 });
834 }
835 }
836 }
837 }
838
839 addGlobal(node: t.Identifier | t.JSXIdentifier) {
840 this.globals[node.name] = node;
841 }
842
843 hasUid(name: string): boolean {
844 let scope: Scope = this;
845
846 do {
847 if (scope.uids[name]) return true;
848 } while ((scope = scope.parent));
849
850 return false;
851 }
852
853 hasGlobal(name: string): boolean {
854 let scope: Scope = this;
855
856 do {
857 if (scope.globals[name]) return true;
858 } while ((scope = scope.parent));
859
860 return false;
861 }
862
863 hasReference(name: string): boolean {
864 return !!this.getProgramParent().references[name];
865 }
866
867 isPure(node: t.Node, constantsOnly?: boolean): boolean {
868 if (isIdentifier(node)) {
869 const binding = this.getBinding(node.name);
870 if (!binding) return false;
871 if (constantsOnly) return binding.constant;
872 return true;
873 } else if (
874 isThisExpression(node) ||
875 isMetaProperty(node) ||
876 isTopicReference(node) ||
877 isPrivateName(node)
878 ) {
879 return true;
880 } else if (isClass(node)) {
881 if (node.superClass && !this.isPure(node.superClass, constantsOnly)) {
882 return false;
883 }
884 if (node.decorators?.length > 0) {
885 return false;
886 }
887 return this.isPure(node.body, constantsOnly);
888 } else if (isClassBody(node)) {
889 for (const method of node.body) {
890 if (!this.isPure(method, constantsOnly)) return false;
891 }
892 return true;
893 } else if (isBinary(node)) {
894 return (
895 this.isPure(node.left, constantsOnly) &&
896 this.isPure(node.right, constantsOnly)
897 );
898 } else if (isArrayExpression(node) || isTupleExpression(node)) {
899 for (const elem of node.elements) {
900 if (elem !== null && !this.isPure(elem, constantsOnly)) return false;
901 }
902 return true;
903 } else if (isObjectExpression(node) || isRecordExpression(node)) {
904 for (const prop of node.properties) {
905 if (!this.isPure(prop, constantsOnly)) return false;
906 }
907 return true;
908 } else if (isMethod(node)) {
909 if (node.computed && !this.isPure(node.key, constantsOnly)) return false;
910 if (node.decorators?.length > 0) {
911 return false;
912 }
913 return true;
914 } else if (isProperty(node)) {
915 // @ts-expect-error todo(flow->ts): computed in not present on private properties
916 if (node.computed && !this.isPure(node.key, constantsOnly)) return false;
917 if (node.decorators?.length > 0) {
918 return false;
919 }
920 if (isObjectProperty(node) || node.static) {
921 if (node.value !== null && !this.isPure(node.value, constantsOnly)) {
922 return false;
923 }
924 }
925 return true;
926 } else if (isUnaryExpression(node)) {
927 return this.isPure(node.argument, constantsOnly);
928 } else if (isTaggedTemplateExpression(node)) {
929 return (
930 matchesPattern(node.tag, "String.raw") &&
931 !this.hasBinding("String", true) &&
932 this.isPure(node.quasi, constantsOnly)
933 );
934 } else if (isTemplateLiteral(node)) {
935 for (const expression of node.expressions) {
936 if (!this.isPure(expression, constantsOnly)) return false;
937 }
938 return true;
939 } else {
940 return isPureish(node);
941 }
942 }
943
944 /**
945 * Set some arbitrary data on the current scope.
946 */
947
948 setData(key: string | symbol, val: any) {
949 return (this.data[key] = val);
950 }
951
952 /**
953 * Recursively walk up scope tree looking for the data `key`.
954 */
955
956 getData(key: string | symbol): any {
957 let scope: Scope = this;
958 do {
959 const data = scope.data[key];
960 if (data != null) return data;
961 } while ((scope = scope.parent));
962 }
963
964 /**
965 * Recursively walk up scope tree looking for the data `key` and if it exists,
966 * remove it.
967 */
968
969 removeData(key: string) {
970 let scope: Scope = this;
971 do {
972 const data = scope.data[key];
973 if (data != null) scope.data[key] = null;
974 } while ((scope = scope.parent));
975 }
976
977 init() {
978 if (!this.inited) {
979 this.inited = true;
980 this.crawl();
981 }
982 }
983
984 crawl() {
985 const path = this.path;
986
987 this.references = Object.create(null);
988 this.bindings = Object.create(null);
989 this.globals = Object.create(null);
990 this.uids = Object.create(null);
991 this.data = Object.create(null);
992
993 const programParent = this.getProgramParent();
994 if (programParent.crawling) return;
995
996 const state: CollectVisitorState = {
997 references: [],
998 constantViolations: [],
999 assignments: [],
1000 };
1001
1002 this.crawling = true;
1003 // traverse does not visit the root node, here we explicitly collect
1004 // root node binding info when the root is not a Program.
1005 if (path.type !== "Program" && collectorVisitor._exploded) {
1006 // @ts-expect-error when collectorVisitor is exploded, `enter` always exists
1007 for (const visit of collectorVisitor.enter) {
1008 visit(path, state);
1009 }
1010 const typeVisitors = collectorVisitor[path.type];
1011 if (typeVisitors) {
1012 // @ts-expect-error when collectorVisitor is exploded, `enter` always exists
1013 for (const visit of typeVisitors.enter) {
1014 visit(path, state);
1015 }
1016 }
1017 }
1018 path.traverse(collectorVisitor, state);
1019 this.crawling = false;
1020
1021 // register assignments
1022 for (const path of state.assignments) {
1023 // register undeclared bindings as globals
1024 const ids = path.getBindingIdentifiers();
1025 for (const name of Object.keys(ids)) {
1026 if (path.scope.getBinding(name)) continue;
1027 programParent.addGlobal(ids[name]);
1028 }
1029
1030 // register as constant violation
1031 path.scope.registerConstantViolation(path);
1032 }
1033
1034 // register references
1035 for (const ref of state.references) {
1036 const binding = ref.scope.getBinding(ref.node.name);
1037 if (binding) {
1038 binding.reference(ref);
1039 } else {
1040 programParent.addGlobal(ref.node);
1041 }
1042 }
1043
1044 // register constant violations
1045 for (const path of state.constantViolations) {
1046 path.scope.registerConstantViolation(path);
1047 }
1048 }
1049
1050 push(opts: {
1051 id: t.LVal;
1052 init?: t.Expression;
1053 unique?: boolean;
1054 _blockHoist?: number | undefined;
1055 kind?: "var" | "let" | "const";
1056 }) {
1057 let path = this.path;
1058
1059 if (path.isPattern()) {
1060 path = this.getPatternParent().path;
1061 } else if (!path.isBlockStatement() && !path.isProgram()) {
1062 path = this.getBlockParent().path;
1063 }
1064
1065 if (path.isSwitchStatement()) {
1066 path = (this.getFunctionParent() || this.getProgramParent()).path;
1067 }
1068
1069 if (path.isLoop() || path.isCatchClause() || path.isFunction()) {
1070 // @ts-expect-error TS can not infer NodePath<Loop> | NodePath<CatchClause> as NodePath<Loop | CatchClause>
1071 path.ensureBlock();
1072 // @ts-expect-error todo(flow->ts): improve types
1073 path = path.get("body");
1074 }
1075
1076 const unique = opts.unique;
1077 const kind = opts.kind || "var";
1078 const blockHoist = opts._blockHoist == null ? 2 : opts._blockHoist;
1079
1080 const dataKey = `declaration:${kind}:${blockHoist}`;
1081 let declarPath = !unique && path.getData(dataKey);
1082
1083 if (!declarPath) {
1084 const declar = variableDeclaration(kind, []);
1085 // @ts-expect-error todo(flow->ts): avoid modifying nodes
1086 declar._blockHoist = blockHoist;
1087
1088 [declarPath] = (path as NodePath<t.BlockStatement>).unshiftContainer(
1089 "body",
1090 [declar],
1091 );
1092 if (!unique) path.setData(dataKey, declarPath);
1093 }
1094
1095 const declarator = variableDeclarator(opts.id, opts.init);
1096 const len = declarPath.node.declarations.push(declarator);
1097 path.scope.registerBinding(kind, declarPath.get("declarations")[len - 1]);
1098 }
1099
1100 /**
1101 * Walk up to the top of the scope tree and get the `Program`.
1102 */
1103
1104 getProgramParent() {
1105 let scope: Scope = this;
1106 do {
1107 if (scope.path.isProgram()) {
1108 return scope;
1109 }
1110 } while ((scope = scope.parent));
1111 throw new Error("Couldn't find a Program");
1112 }
1113
1114 /**
1115 * Walk up the scope tree until we hit either a Function or return null.
1116 */
1117
1118 getFunctionParent(): Scope | null {
1119 let scope: Scope = this;
1120 do {
1121 if (scope.path.isFunctionParent()) {
1122 return scope;
1123 }
1124 } while ((scope = scope.parent));
1125 return null;
1126 }
1127
1128 /**
1129 * Walk up the scope tree until we hit either a BlockStatement/Loop/Program/Function/Switch or reach the
1130 * very top and hit Program.
1131 */
1132
1133 getBlockParent() {
1134 let scope: Scope = this;
1135 do {
1136 if (scope.path.isBlockParent()) {
1137 return scope;
1138 }
1139 } while ((scope = scope.parent));
1140 throw new Error(
1141 "We couldn't find a BlockStatement, For, Switch, Function, Loop or Program...",
1142 );
1143 }
1144
1145 /**
1146 * Walk up from a pattern scope (function param initializer) until we hit a non-pattern scope,
1147 * then returns its block parent
1148 * @returns An ancestry scope whose path is a block parent
1149 */
1150 getPatternParent() {
1151 let scope: Scope = this;
1152 do {
1153 if (!scope.path.isPattern()) {
1154 return scope.getBlockParent();
1155 }
1156 } while ((scope = scope.parent.parent));
1157 throw new Error(
1158 "We couldn't find a BlockStatement, For, Switch, Function, Loop or Program...",
1159 );
1160 }
1161
1162 /**
1163 * Walks the scope tree and gathers **all** bindings.
1164 */
1165
1166 getAllBindings(): Record<string, Binding> {
1167 const ids = Object.create(null);
1168
1169 let scope: Scope = this;
1170 do {
1171 for (const key of Object.keys(scope.bindings)) {
1172 if (key in ids === false) {
1173 ids[key] = scope.bindings[key];
1174 }
1175 }
1176 scope = scope.parent;
1177 } while (scope);
1178
1179 return ids;
1180 }
1181
1182 /**
1183 * Walks the scope tree and gathers all declarations of `kind`.
1184 */
1185
1186 getAllBindingsOfKind(...kinds: string[]): Record<string, Binding> {
1187 const ids = Object.create(null);
1188
1189 for (const kind of kinds) {
1190 let scope: Scope = this;
1191 do {
1192 for (const name of Object.keys(scope.bindings)) {
1193 const binding = scope.bindings[name];
1194 if (binding.kind === kind) ids[name] = binding;
1195 }
1196 scope = scope.parent;
1197 } while (scope);
1198 }
1199
1200 return ids;
1201 }
1202
1203 bindingIdentifierEquals(name: string, node: t.Node): boolean {
1204 return this.getBindingIdentifier(name) === node;
1205 }
1206
1207 getBinding(name: string): Binding | undefined {
1208 let scope: Scope = this;
1209 let previousPath;
1210
1211 do {
1212 const binding = scope.getOwnBinding(name);
1213 if (binding) {
1214 // Check if a pattern is a part of parameter expressions.
1215 // Note: for performance reason we skip checking previousPath.parentPath.isFunction()
1216 // because `scope.path` is validated as scope in packages/babel-types/src/validators/isScope.js
1217 // That is, if a scope path is pattern, its parent must be Function/CatchClause
1218
1219 // Spec 9.2.10.28: The closure created by this expression should not have visibility of
1220 // declarations in the function body. If the binding is not a `param`-kind (as function parameters)
1221 // or `local`-kind (as id in function expression),
1222 // then it must be defined inside the function body, thus it should be skipped
1223 if (
1224 previousPath?.isPattern() &&
1225 binding.kind !== "param" &&
1226 binding.kind !== "local"
1227 ) {
1228 // do nothing
1229 } else {
1230 return binding;
1231 }
1232 } else if (
1233 !binding &&
1234 name === "arguments" &&
1235 scope.path.isFunction() &&
1236 !scope.path.isArrowFunctionExpression()
1237 ) {
1238 break;
1239 }
1240 previousPath = scope.path;
1241 } while ((scope = scope.parent));
1242 }
1243
1244 getOwnBinding(name: string): Binding | undefined {
1245 return this.bindings[name];
1246 }
1247
1248 // todo: return probably can be undefined…
1249 getBindingIdentifier(name: string): t.Identifier {
1250 return this.getBinding(name)?.identifier;
1251 }
1252
1253 // todo: flow->ts return probably can be undefined
1254 getOwnBindingIdentifier(name: string): t.Identifier {
1255 const binding = this.bindings[name];
1256 return binding?.identifier;
1257 }
1258
1259 hasOwnBinding(name: string) {
1260 return !!this.getOwnBinding(name);
1261 }
1262
1263 // By default, we consider generated UIDs as bindings.
1264 // This is because they are almost always used to declare variables,
1265 // and since the scope isn't always up-to-date it's better to assume that
1266 // there is a variable with that name. The `noUids` option can be used to
1267 // turn off this behavior, for example if you know that the generate UID
1268 // was used to declare a variable in a different scope.
1269 hasBinding(
1270 name: string,
1271 opts?: boolean | { noGlobals?: boolean; noUids?: boolean },
1272 ) {
1273 if (!name) return false;
1274 if (this.hasOwnBinding(name)) return true;
1275 {
1276 // TODO: Only accept the object form.
1277 if (typeof opts === "boolean") opts = { noGlobals: opts };
1278 }
1279 if (this.parentHasBinding(name, opts)) return true;
1280 if (!opts?.noUids && this.hasUid(name)) return true;
1281 if (!opts?.noGlobals && Scope.globals.includes(name)) return true;
1282 if (!opts?.noGlobals && Scope.contextVariables.includes(name)) return true;
1283 return false;
1284 }
1285
1286 parentHasBinding(
1287 name: string,
1288 opts?: { noGlobals?: boolean; noUids?: boolean },
1289 ) {
1290 return this.parent?.hasBinding(name, opts);
1291 }
1292
1293 /**
1294 * Move a binding of `name` to another `scope`.
1295 */
1296
1297 moveBindingTo(name: string, scope: Scope) {
1298 const info = this.getBinding(name);
1299 if (info) {
1300 info.scope.removeOwnBinding(name);
1301 info.scope = scope;
1302 scope.bindings[name] = info;
1303 }
1304 }
1305
1306 removeOwnBinding(name: string) {
1307 delete this.bindings[name];
1308 }
1309
1310 removeBinding(name: string) {
1311 // clear literal binding
1312 this.getBinding(name)?.scope.removeOwnBinding(name);
1313
1314 // clear uids with this name - https://github.com/babel/babel/issues/2101
1315 let scope: Scope = this;
1316 do {
1317 if (scope.uids[name]) {
1318 scope.uids[name] = false;
1319 }
1320 } while ((scope = scope.parent));
1321 }
1322 }