Debian Codegraph @

packages/babel-traverse/src/path/introspection.ts

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 // This file contains methods responsible for introspecting the current path for certain values.
2
3 import type NodePath from "./index";
4 import {
5 STATEMENT_OR_BLOCK_KEYS,
6 VISITOR_KEYS,
7 isBlockStatement,
8 isExpression,
9 isIdentifier,
10 isLiteral,
11 isStringLiteral,
12 isType,
13 matchesPattern as _matchesPattern,
14 } from "@babel/types";
15 import type * as t from "@babel/types";
16
17 /**
18 * Match the current node if it matches the provided `pattern`.
19 *
20 * For example, given the match `React.createClass` it would match the
21 * parsed nodes of `React.createClass` and `React["createClass"]`.
22 */
23
24 export function matchesPattern(
25 this: NodePath,
26 pattern: string,
27 allowPartial?: boolean,
28 ): boolean {
29 return _matchesPattern(this.node, pattern, allowPartial);
30 }
31
32 /**
33 * Check whether we have the input `key`. If the `key` references an array then we check
34 * if the array has any items, otherwise we just check if it's falsy.
35 */
36
37 export function has<N extends t.Node>(
38 this: NodePath<N>,
39 key: keyof N,
40 ): boolean {
41 const val = this.node && this.node[key];
42 if (val && Array.isArray(val)) {
43 return !!val.length;
44 } else {
45 return !!val;
46 }
47 }
48
49 /**
50 * Description
51 */
52
53 export function isStatic(this: NodePath): boolean {
54 return this.scope.isStatic(this.node);
55 }
56
57 /**
58 * Alias of `has`.
59 */
60
61 export const is = has;
62
63 /**
64 * Opposite of `has`.
65 */
66
67 export function isnt<N extends t.Node>(
68 this: NodePath<N>,
69 key: keyof N,
70 ): boolean {
71 return !this.has(key);
72 }
73
74 /**
75 * Check whether the path node `key` strict equals `value`.
76 */
77
78 export function equals<N extends t.Node>(
79 this: NodePath<N>,
80 key: keyof N,
81 value: any,
82 ): boolean {
83 return this.node[key] === value;
84 }
85
86 /**
87 * Check the type against our stored internal type of the node. This is handy when a node has
88 * been removed yet we still internally know the type and need it to calculate node replacement.
89 */
90
91 export function isNodeType(this: NodePath, type: string): boolean {
92 return isType(this.type, type);
93 }
94
95 /**
96 * This checks whether or not we're in one of the following positions:
97 *
98 * for (KEY in right);
99 * for (KEY;;);
100 *
101 * This is because these spots allow VariableDeclarations AND normal expressions so we need
102 * to tell the path replacement that it's ok to replace this with an expression.
103 */
104
105 export function canHaveVariableDeclarationOrExpression(this: NodePath) {
106 return (
107 (this.key === "init" || this.key === "left") && this.parentPath.isFor()
108 );
109 }
110
111 /**
112 * This checks whether we are swapping an arrow function's body between an
113 * expression and a block statement (or vice versa).
114 *
115 * This is because arrow functions may implicitly return an expression, which
116 * is the same as containing a block statement.
117 */
118
119 export function canSwapBetweenExpressionAndStatement(
120 this: NodePath,
121 replacement: t.Node,
122 ): boolean {
123 if (this.key !== "body" || !this.parentPath.isArrowFunctionExpression()) {
124 return false;
125 }
126
127 if (this.isExpression()) {
128 return isBlockStatement(replacement);
129 } else if (this.isBlockStatement()) {
130 return isExpression(replacement);
131 }
132
133 return false;
134 }
135
136 /**
137 * Check whether the current path references a completion record
138 */
139
140 export function isCompletionRecord(
141 this: NodePath,
142 allowInsideFunction?: boolean,
143 ): boolean {
144 let path = this;
145 let first = true;
146
147 do {
148 const { type, container } = path;
149
150 // we're in a function so can't be a completion record
151 if (!first && (path.isFunction() || type === "StaticBlock")) {
152 return !!allowInsideFunction;
153 }
154
155 first = false;
156
157 // check to see if we're the last item in the container and if we are
158 // we're a completion record!
159 if (Array.isArray(container) && path.key !== container.length - 1) {
160 return false;
161 }
162 } while (
163 (path = path.parentPath) &&
164 !path.isProgram() &&
165 !path.isDoExpression()
166 );
167
168 return true;
169 }
170
171 /**
172 * Check whether or not the current `key` allows either a single statement or block statement
173 * so we can explode it if necessary.
174 */
175
176 export function isStatementOrBlock(this: NodePath): boolean {
177 if (
178 this.parentPath.isLabeledStatement() ||
179 isBlockStatement(this.container)
180 ) {
181 return false;
182 } else {
183 return STATEMENT_OR_BLOCK_KEYS.includes(this.key as string);
184 }
185 }
186
187 /**
188 * Check if the currently assigned path references the `importName` of `moduleSource`.
189 */
190
191 export function referencesImport(
192 this: NodePath,
193 moduleSource: string,
194 importName: string,
195 ): boolean {
196 if (!this.isReferencedIdentifier()) {
197 if (
198 (this.isJSXMemberExpression() &&
199 this.node.property.name === importName) ||
200 ((this.isMemberExpression() || this.isOptionalMemberExpression()) &&
201 (this.node.computed
202 ? isStringLiteral(this.node.property, { value: importName })
203 : (this.node.property as t.Identifier).name === importName))
204 ) {
205 const object = (
206 this as NodePath<t.MemberExpression | t.OptionalMemberExpression>
207 ).get("object");
208 return (
209 object.isReferencedIdentifier() &&
210 object.referencesImport(moduleSource, "*")
211 );
212 }
213
214 return false;
215 }
216
217 const binding = this.scope.getBinding((this.node as t.Identifier).name);
218 if (!binding || binding.kind !== "module") return false;
219
220 const path = binding.path;
221 const parent = path.parentPath;
222 if (!parent.isImportDeclaration()) return false;
223
224 // check moduleSource
225 if (parent.node.source.value === moduleSource) {
226 if (!importName) return true;
227 } else {
228 return false;
229 }
230
231 if (path.isImportDefaultSpecifier() && importName === "default") {
232 return true;
233 }
234
235 if (path.isImportNamespaceSpecifier() && importName === "*") {
236 return true;
237 }
238
239 if (
240 path.isImportSpecifier() &&
241 isIdentifier(path.node.imported, { name: importName })
242 ) {
243 return true;
244 }
245
246 return false;
247 }
248
249 /**
250 * Get the source code associated with this node.
251 */
252
253 export function getSource(this: NodePath): string {
254 const node = this.node;
255 if (node.end) {
256 const code = this.hub.getCode();
257 if (code) return code.slice(node.start, node.end);
258 }
259 return "";
260 }
261
262 export function willIMaybeExecuteBefore(
263 this: NodePath,
264 target: NodePath,
265 ): boolean {
266 return this._guessExecutionStatusRelativeTo(target) !== "after";
267 }
268
269 function getOuterFunction(path: NodePath) {
270 return path.isProgram()
271 ? path
272 : (
273 path.parentPath.scope.getFunctionParent() ||
274 path.parentPath.scope.getProgramParent()
275 ).path;
276 }
277
278 function isExecutionUncertain(type: t.Node["type"], key: string) {
279 switch (type) {
280 // a && FOO
281 // a || FOO
282 case "LogicalExpression":
283 return key === "right";
284
285 // a ? FOO : FOO
286 // if (a) FOO; else FOO;
287 case "ConditionalExpression":
288 case "IfStatement":
289 return key === "consequent" || key === "alternate";
290
291 // while (a) FOO;
292 case "WhileStatement":
293 case "DoWhileStatement":
294 case "ForInStatement":
295 case "ForOfStatement":
296 return key === "body";
297
298 // for (a; b; FOO) FOO;
299 case "ForStatement":
300 return key === "body" || key === "update";
301
302 // switch (a) { FOO }
303 case "SwitchStatement":
304 return key === "cases";
305
306 // try { a } catch FOO finally { b }
307 case "TryStatement":
308 return key === "handler";
309
310 // var [ x = FOO ]
311 case "AssignmentPattern":
312 return key === "right";
313
314 // a?.[FOO]
315 case "OptionalMemberExpression":
316 return key === "property";
317
318 // a?.(FOO)
319 case "OptionalCallExpression":
320 return key === "arguments";
321
322 default:
323 return false;
324 }
325 }
326
327 function isExecutionUncertainInList(paths: NodePath[], maxIndex: number) {
328 for (let i = 0; i < maxIndex; i++) {
329 const path = paths[i];
330 if (isExecutionUncertain(path.parent.type, path.parentKey)) {
331 return true;
332 }
333 }
334 return false;
335 }
336
337 // TODO (Babel 8)
338 // This can be { before: boolean, after: boolean, unknown: boolean }.
339 // This allows transforms like the tdz one to treat cases when the status
340 // is both before and unknown/after like if it were before.
341 type RelativeExecutionStatus = "before" | "after" | "unknown";
342
343 // Used to avoid infinite recursion in cases like
344 // function f() { if (false) f(); }
345 // f();
346 // It also works with indirect recursion.
347 const SYMBOL_CHECKING = Symbol();
348
349 type ExecutionStatusCache = Map<
350 t.Node,
351 Map<t.Node, RelativeExecutionStatus | typeof SYMBOL_CHECKING>
352 >;
353
354 /**
355 * Given a `target` check the execution status of it relative to the current path.
356 *
357 * "Execution status" simply refers to where or not we **think** this will execute
358 * before or after the input `target` element.
359 */
360
361 export function _guessExecutionStatusRelativeTo(
362 this: NodePath,
363 target: NodePath,
364 ): RelativeExecutionStatus {
365 return _guessExecutionStatusRelativeToCached(this, target, new Map());
366 }
367
368 function _guessExecutionStatusRelativeToCached(
369 base: NodePath,
370 target: NodePath,
371 cache: ExecutionStatusCache,
372 ): RelativeExecutionStatus {
373 // check if the two paths are in different functions, we can't track execution of these
374 const funcParent = {
375 this: getOuterFunction(base),
376 target: getOuterFunction(target),
377 };
378
379 // here we check the `node` equality as sometimes we may have different paths for the
380 // same node due to path thrashing
381 if (funcParent.target.node !== funcParent.this.node) {
382 return _guessExecutionStatusRelativeToDifferentFunctionsCached(
383 base,
384 funcParent.target,
385 cache,
386 );
387 }
388
389 const paths = {
390 target: target.getAncestry(),
391 this: base.getAncestry(),
392 };
393
394 // If this is an ancestor of the target path,
395 // e.g. f(g); where this is f and target is g.
396 if (paths.target.indexOf(base) >= 0) return "after";
397 if (paths.this.indexOf(target) >= 0) return "before";
398
399 // get ancestor where the branches intersect
400 let commonPath;
401 const commonIndex = { target: 0, this: 0 };
402
403 while (!commonPath && commonIndex.this < paths.this.length) {
404 const path = paths.this[commonIndex.this];
405 commonIndex.target = paths.target.indexOf(path);
406 if (commonIndex.target >= 0) {
407 commonPath = path;
408 } else {
409 commonIndex.this++;
410 }
411 }
412
413 if (!commonPath) {
414 throw new Error(
415 "Internal Babel error - The two compared nodes" +
416 " don't appear to belong to the same program.",
417 );
418 }
419
420 if (
421 isExecutionUncertainInList(paths.this, commonIndex.this - 1) ||
422 isExecutionUncertainInList(paths.target, commonIndex.target - 1)
423 ) {
424 return "unknown";
425 }
426
427 const divergence = {
428 this: paths.this[commonIndex.this - 1],
429 target: paths.target[commonIndex.target - 1],
430 };
431
432 // container list so let's see which one is after the other
433 // e.g. [ THIS, TARGET ]
434 if (
435 divergence.target.listKey &&
436 divergence.this.listKey &&
437 divergence.target.container === divergence.this.container
438 ) {
439 return divergence.target.key > divergence.this.key ? "before" : "after";
440 }
441
442 // otherwise we're associated by a parent node, check which key comes before the other
443 const keys = VISITOR_KEYS[commonPath.type];
444 const keyPosition = {
445 this: keys.indexOf(divergence.this.parentKey),
446 target: keys.indexOf(divergence.target.parentKey),
447 };
448 return keyPosition.target > keyPosition.this ? "before" : "after";
449 }
450
451 function _guessExecutionStatusRelativeToDifferentFunctionsInternal(
452 base: NodePath,
453 target: NodePath,
454 cache: ExecutionStatusCache,
455 ): RelativeExecutionStatus {
456 if (!target.isFunctionDeclaration()) {
457 if (
458 _guessExecutionStatusRelativeToCached(base, target, cache) === "before"
459 ) {
460 return "before";
461 }
462 return "unknown";
463 } else if (target.parentPath.isExportDeclaration()) {
464 return "unknown";
465 }
466
467 // so we're in a completely different function, if this is a function declaration
468 // then we can be a bit smarter and handle cases where the function is either
469 // a. not called at all (part of an export)
470 // b. called directly
471 const binding = target.scope.getBinding(target.node.id.name);
472
473 // no references!
474 if (!binding.references) return "before";
475
476 const referencePaths: Array<NodePath> = binding.referencePaths;
477
478 let allStatus;
479
480 // verify that all the calls have the same execution status
481 for (const path of referencePaths) {
482 // if a reference is a child of the function we're checking against then we can
483 // safely ignore it
484 const childOfFunction = !!path.find(path => path.node === target.node);
485 if (childOfFunction) continue;
486
487 if (path.key !== "callee" || !path.parentPath.isCallExpression()) {
488 // This function is passed as a reference, so we don't
489 // know when it will be called.
490 return "unknown";
491 }
492
493 const status = _guessExecutionStatusRelativeToCached(base, path, cache);
494
495 if (allStatus && allStatus !== status) {
496 return "unknown";
497 } else {
498 allStatus = status;
499 }
500 }
501
502 return allStatus;
503 }
504
505 function _guessExecutionStatusRelativeToDifferentFunctionsCached(
506 base: NodePath,
507 target: NodePath,
508 cache: ExecutionStatusCache,
509 ): RelativeExecutionStatus {
510 let nodeMap = cache.get(base.node);
511 let cached;
512
513 if (!nodeMap) {
514 cache.set(base.node, (nodeMap = new Map()));
515 } else if ((cached = nodeMap.get(target.node))) {
516 if (cached === SYMBOL_CHECKING) {
517 return "unknown";
518 }
519 return cached;
520 }
521
522 nodeMap.set(target.node, SYMBOL_CHECKING);
523
524 const result = _guessExecutionStatusRelativeToDifferentFunctionsInternal(
525 base,
526 target,
527 cache,
528 );
529
530 nodeMap.set(target.node, result);
531 return result;
532 }
533
534 /**
535 * Resolve a "pointer" `NodePath` to it's absolute path.
536 */
537 export function resolve(
538 this: NodePath,
539 dangerous?: boolean,
540 resolved?: NodePath[],
541 ) {
542 return this._resolve(dangerous, resolved) || this;
543 }
544
545 export function _resolve(
546 this: NodePath,
547 dangerous?: boolean,
548 resolved?: NodePath[],
549 ): NodePath | undefined | null {
550 // detect infinite recursion
551 // todo: possibly have a max length on this just to be safe
552 if (resolved && resolved.indexOf(this) >= 0) return;
553
554 // we store all the paths we've "resolved" in this array to prevent infinite recursion
555 resolved = resolved || [];
556 resolved.push(this);
557
558 if (this.isVariableDeclarator()) {
559 if (this.get("id").isIdentifier()) {
560 return this.get("init").resolve(dangerous, resolved);
561 } else {
562 // otherwise it's a request for a pattern and that's a bit more tricky
563 }
564 } else if (this.isReferencedIdentifier()) {
565 const binding = this.scope.getBinding(this.node.name);
566 if (!binding) return;
567
568 // reassigned so we can't really resolve it
569 if (!binding.constant) return;
570
571 // todo - lookup module in dependency graph
572 if (binding.kind === "module") return;
573
574 if (binding.path !== this) {
575 const ret = binding.path.resolve(dangerous, resolved);
576 // If the identifier resolves to parent node then we can't really resolve it.
577 if (this.find(parent => parent.node === ret.node)) return;
578 return ret;
579 }
580 } else if (this.isTypeCastExpression()) {
581 // @ ts-ignore todo: babel-types
582 return this.get("expression").resolve(dangerous, resolved);
583 } else if (dangerous && this.isMemberExpression()) {
584 // this is dangerous, as non-direct target assignments will mutate it's state
585 // making this resolution inaccurate
586
587 const targetKey = this.toComputedKey();
588 if (!isLiteral(targetKey)) return;
589
590 // @ts-expect-error todo(flow->ts): NullLiteral
591 const targetName = targetKey.value;
592
593 const target = this.get("object").resolve(dangerous, resolved);
594
595 if (target.isObjectExpression()) {
596 const props = target.get("properties");
597 for (const prop of props as any[]) {
598 if (!prop.isProperty()) continue;
599
600 const key = prop.get("key");
601
602 // { foo: obj }
603 let match =
604 prop.isnt("computed") && key.isIdentifier({ name: targetName });
605
606 // { "foo": "obj" } or { ["foo"]: "obj" }
607 match = match || key.isLiteral({ value: targetName });
608
609 if (match) return prop.get("value").resolve(dangerous, resolved);
610 }
611 } else if (target.isArrayExpression() && !isNaN(+targetName)) {
612 const elems = target.get("elements");
613 const elem = elems[targetName];
614 if (elem) return elem.resolve(dangerous, resolved);
615 }
616 }
617 }
618
619 export function isConstantExpression(this: NodePath): boolean {
620 if (this.isIdentifier()) {
621 const binding = this.scope.getBinding(this.node.name);
622 if (!binding) return false;
623 return binding.constant;
624 }
625
626 if (this.isLiteral()) {
627 if (this.isRegExpLiteral()) {
628 return false;
629 }
630
631 if (this.isTemplateLiteral()) {
632 return this.get("expressions").every(expression =>
633 expression.isConstantExpression(),
634 );
635 }
636
637 return true;
638 }
639
640 if (this.isUnaryExpression()) {
641 if (this.node.operator !== "void") {
642 return false;
643 }
644
645 return this.get("argument").isConstantExpression();
646 }
647
648 if (this.isBinaryExpression()) {
649 const { operator } = this.node;
650 return (
651 operator !== "in" &&
652 operator !== "instanceof" &&
653 this.get("left").isConstantExpression() &&
654 this.get("right").isConstantExpression()
655 );
656 }
657
658 return false;
659 }
660
661 export function isInStrictMode(this: NodePath) {
662 const start = this.isProgram() ? this : this.parentPath;
663
664 const strictParent = start.find(path => {
665 if (path.isProgram({ sourceType: "module" })) return true;
666
667 if (path.isClass()) return true;
668
669 if (
670 path.isArrowFunctionExpression() &&
671 !path.get("body").isBlockStatement()
672 ) {
673 return false;
674 }
675
676 let body: t.BlockStatement | t.Program;
677 if (path.isFunction()) {
678 body = path.node.body as t.BlockStatement;
679 } else if (path.isProgram()) {
680 body = path.node;
681 } else {
682 return false;
683 }
684
685 for (const directive of body.directives) {
686 if (directive.value.value === "use strict") {
687 return true;
688 }
689 }
690 });
691
692 return !!strictParent;
693 }