Debian Codegraph @

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

raw symbols ◀ ▶ SCIP
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 // @ts-ignore
199 (this.isJSXMemberExpression() &&
•200 // @ts-ignore
201 this.node.property.name === importName) ||
•202 // @ts-ignore
203 ((this.isMemberExpression() || this.isOptionalMemberExpression()) &&
•204 // @ts-ignore
205 (this.node.computed
•206 // @ts-ignore
207 ? isStringLiteral(this.node.property, { value: importName })
•208 // @ts-ignore
209 : (this.node.property as t.Identifier).name === importName))
210 ) {
211 const object = (
212 this as NodePath<t.MemberExpression | t.OptionalMemberExpression>
213 ).get("object");
214 return (
215 object.isReferencedIdentifier() &&
216 object.referencesImport(moduleSource, "*")
217 );
218 }
219
220 return false;
221 }
222
223 const binding = this.scope.getBinding((this.node as t.Identifier).name);
224 if (!binding || binding.kind !== "module") return false;
225
226 const path = binding.path;
227 const parent = path.parentPath;
228 if (!parent.isImportDeclaration()) return false;
229
230 // check moduleSource
231 if (parent.node.source.value === moduleSource) {
232 if (!importName) return true;
233 } else {
234 return false;
235 }
236
237 if (path.isImportDefaultSpecifier() && importName === "default") {
238 return true;
239 }
240
241 if (path.isImportNamespaceSpecifier() && importName === "*") {
242 return true;
243 }
244
245 if (
246 path.isImportSpecifier() &&
247 isIdentifier(path.node.imported, { name: importName })
248 ) {
249 return true;
250 }
251
252 return false;
253 }
254
255 /**
256 * Get the source code associated with this node.
257 */
258
259 export function getSource(this: NodePath): string {
260 const node = this.node;
261 if (node.end) {
262 const code = this.hub.getCode();
263 if (code) return code.slice(node.start, node.end);
264 }
265 return "";
266 }
267
268 export function willIMaybeExecuteBefore(
269 this: NodePath,
270 target: NodePath,
271 ): boolean {
272 return this._guessExecutionStatusRelativeTo(target) !== "after";
273 }
274
275 function getOuterFunction(path: NodePath) {
276 return path.isProgram()
277 ? path
278 : (
279 path.parentPath.scope.getFunctionParent() ||
280 path.parentPath.scope.getProgramParent()
281 ).path;
282 }
283
284 function isExecutionUncertain(type: t.Node["type"], key: string) {
285 switch (type) {
286 // a && FOO
287 // a || FOO
288 case "LogicalExpression":
289 return key === "right";
290
291 // a ? FOO : FOO
292 // if (a) FOO; else FOO;
293 case "ConditionalExpression":
294 case "IfStatement":
295 return key === "consequent" || key === "alternate";
296
297 // while (a) FOO;
298 case "WhileStatement":
299 case "DoWhileStatement":
300 case "ForInStatement":
301 case "ForOfStatement":
302 return key === "body";
303
304 // for (a; b; FOO) FOO;
305 case "ForStatement":
306 return key === "body" || key === "update";
307
308 // switch (a) { FOO }
309 case "SwitchStatement":
310 return key === "cases";
311
312 // try { a } catch FOO finally { b }
313 case "TryStatement":
314 return key === "handler";
315
316 // var [ x = FOO ]
317 case "AssignmentPattern":
318 return key === "right";
319
320 // a?.[FOO]
321 case "OptionalMemberExpression":
322 return key === "property";
323
324 // a?.(FOO)
325 case "OptionalCallExpression":
326 return key === "arguments";
327
328 default:
329 return false;
330 }
331 }
332
333 function isExecutionUncertainInList(paths: NodePath[], maxIndex: number) {
334 for (let i = 0; i < maxIndex; i++) {
335 const path = paths[i];
336 if (isExecutionUncertain(path.parent.type, path.parentKey)) {
337 return true;
338 }
339 }
340 return false;
341 }
342
343 // TODO (Babel 8)
344 // This can be { before: boolean, after: boolean, unknown: boolean }.
345 // This allows transforms like the tdz one to treat cases when the status
346 // is both before and unknown/after like if it were before.
347 type RelativeExecutionStatus = "before" | "after" | "unknown";
348
349 // Used to avoid infinite recursion in cases like
350 // function f() { if (false) f(); }
351 // f();
352 // It also works with indirect recursion.
353 const SYMBOL_CHECKING = Symbol();
354
355 type ExecutionStatusCache = Map<
356 t.Node,
357 Map<t.Node, RelativeExecutionStatus | typeof SYMBOL_CHECKING>
358 >;
359
360 /**
361 * Given a `target` check the execution status of it relative to the current path.
362 *
363 * "Execution status" simply refers to where or not we **think** this will execute
364 * before or after the input `target` element.
365 */
366
367 export function _guessExecutionStatusRelativeTo(
368 this: NodePath,
369 target: NodePath,
370 ): RelativeExecutionStatus {
371 return _guessExecutionStatusRelativeToCached(this, target, new Map());
372 }
373
374 function _guessExecutionStatusRelativeToCached(
375 base: NodePath,
376 target: NodePath,
377 cache: ExecutionStatusCache,
378 ): RelativeExecutionStatus {
379 // check if the two paths are in different functions, we can't track execution of these
380 const funcParent = {
381 this: getOuterFunction(base),
382 target: getOuterFunction(target),
383 };
384
385 // here we check the `node` equality as sometimes we may have different paths for the
386 // same node due to path thrashing
387 if (funcParent.target.node !== funcParent.this.node) {
388 return _guessExecutionStatusRelativeToDifferentFunctionsCached(
389 base,
390 funcParent.target,
391 cache,
392 );
393 }
394
395 const paths = {
396 target: target.getAncestry(),
397 this: base.getAncestry(),
398 };
399
400 // If this is an ancestor of the target path,
401 // e.g. f(g); where this is f and target is g.
402 if (paths.target.indexOf(base) >= 0) return "after";
403 if (paths.this.indexOf(target) >= 0) return "before";
404
405 // get ancestor where the branches intersect
406 let commonPath;
407 const commonIndex = { target: 0, this: 0 };
408
409 while (!commonPath && commonIndex.this < paths.this.length) {
410 const path = paths.this[commonIndex.this];
411 commonIndex.target = paths.target.indexOf(path);
412 if (commonIndex.target >= 0) {
413 commonPath = path;
414 } else {
415 commonIndex.this++;
416 }
417 }
418
419 if (!commonPath) {
420 throw new Error(
421 "Internal Babel error - The two compared nodes" +
422 " don't appear to belong to the same program.",
423 );
424 }
425
426 if (
427 isExecutionUncertainInList(paths.this, commonIndex.this - 1) ||
428 isExecutionUncertainInList(paths.target, commonIndex.target - 1)
429 ) {
430 return "unknown";
431 }
432
433 const divergence = {
434 this: paths.this[commonIndex.this - 1],
435 target: paths.target[commonIndex.target - 1],
436 };
437
438 // container list so let's see which one is after the other
439 // e.g. [ THIS, TARGET ]
440 if (
441 divergence.target.listKey &&
442 divergence.this.listKey &&
443 divergence.target.container === divergence.this.container
444 ) {
445 return divergence.target.key > divergence.this.key ? "before" : "after";
446 }
447
448 // otherwise we're associated by a parent node, check which key comes before the other
449 const keys = VISITOR_KEYS[commonPath.type];
450 const keyPosition = {
451 this: keys.indexOf(divergence.this.parentKey),
452 target: keys.indexOf(divergence.target.parentKey),
453 };
454 return keyPosition.target > keyPosition.this ? "before" : "after";
455 }
456
457 function _guessExecutionStatusRelativeToDifferentFunctionsInternal(
458 base: NodePath,
459 target: NodePath,
460 cache: ExecutionStatusCache,
461 ): RelativeExecutionStatus {
462 if (!target.isFunctionDeclaration()) {
463 if (
464 _guessExecutionStatusRelativeToCached(base, target, cache) === "before"
465 ) {
466 return "before";
467 }
468 return "unknown";
469 } else if (target.parentPath.isExportDeclaration()) {
470 return "unknown";
471 }
472
473 // so we're in a completely different function, if this is a function declaration
474 // then we can be a bit smarter and handle cases where the function is either
475 // a. not called at all (part of an export)
476 // b. called directly
477 const binding = target.scope.getBinding(target.node.id.name);
478
479 // no references!
480 if (!binding.references) return "before";
481
482 const referencePaths: Array<NodePath> = binding.referencePaths;
483
484 let allStatus;
485
486 // verify that all the calls have the same execution status
487 for (const path of referencePaths) {
488 // if a reference is a child of the function we're checking against then we can
489 // safely ignore it
490 const childOfFunction = !!path.find(path => path.node === target.node);
491 if (childOfFunction) continue;
492
493 if (path.key !== "callee" || !path.parentPath.isCallExpression()) {
494 // This function is passed as a reference, so we don't
495 // know when it will be called.
496 return "unknown";
497 }
498
499 const status = _guessExecutionStatusRelativeToCached(base, path, cache);
500
501 if (allStatus && allStatus !== status) {
502 return "unknown";
503 } else {
504 allStatus = status;
505 }
506 }
507
508 return allStatus;
509 }
510
511 function _guessExecutionStatusRelativeToDifferentFunctionsCached(
512 base: NodePath,
513 target: NodePath,
514 cache: ExecutionStatusCache,
515 ): RelativeExecutionStatus {
516 let nodeMap = cache.get(base.node);
517 let cached;
518
519 if (!nodeMap) {
520 cache.set(base.node, (nodeMap = new Map()));
521 } else if ((cached = nodeMap.get(target.node))) {
522 if (cached === SYMBOL_CHECKING) {
523 return "unknown";
524 }
525 return cached;
526 }
527
528 nodeMap.set(target.node, SYMBOL_CHECKING);
529
530 const result = _guessExecutionStatusRelativeToDifferentFunctionsInternal(
531 base,
532 target,
533 cache,
534 );
535
536 nodeMap.set(target.node, result);
537 return result;
538 }
539
540 /**
541 * Resolve a "pointer" `NodePath` to it's absolute path.
542 */
543 export function resolve(
544 this: NodePath,
545 dangerous?: boolean,
546 resolved?: NodePath[],
547 ) {
548 return this._resolve(dangerous, resolved) || this;
549 }
550
551 export function _resolve(
552 this: NodePath,
553 dangerous?: boolean,
554 resolved?: NodePath[],
555 ): NodePath | undefined | null {
556 // detect infinite recursion
557 // todo: possibly have a max length on this just to be safe
558 if (resolved && resolved.indexOf(this) >= 0) return;
559
560 // we store all the paths we've "resolved" in this array to prevent infinite recursion
561 resolved = resolved || [];
562 resolved.push(this);
563
564 if (this.isVariableDeclarator()) {
565 if (this.get("id").isIdentifier()) {
566 return this.get("init").resolve(dangerous, resolved);
567 } else {
568 // otherwise it's a request for a pattern and that's a bit more tricky
569 }
570 } else if (this.isReferencedIdentifier()) {
•571 // @ts-ignore
572 const binding = this.scope.getBinding(this.node.name);
573 if (!binding) return;
574
575 // reassigned so we can't really resolve it
576 if (!binding.constant) return;
577
578 // todo - lookup module in dependency graph
579 if (binding.kind === "module") return;
580
581 if (binding.path !== this) {
582 const ret = binding.path.resolve(dangerous, resolved);
583 // If the identifier resolves to parent node then we can't really resolve it.
584 if (this.find(parent => parent.node === ret.node)) return;
585 return ret;
586 }
•587 // @ts-ignore
588 } else if (this.isTypeCastExpression()) {
589 // @ ts-ignore todo: babel-types
•590 // @ts-ignore
591 return this.get("expression").resolve(dangerous, resolved);
•592 // @ts-ignore
593 } else if (dangerous && this.isMemberExpression()) {
594 // this is dangerous, as non-direct target assignments will mutate it's state
595 // making this resolution inaccurate
596
•597 // @ts-ignore
598 const targetKey = this.toComputedKey();
599 if (!isLiteral(targetKey)) return;
600
601 // @ts-expect-error todo(flow->ts): NullLiteral
602 const targetName = targetKey.value;
603
•604 // @ts-ignore
605 const target = this.get("object").resolve(dangerous, resolved);
606
607 if (target.isObjectExpression()) {
608 const props = target.get("properties");
609 for (const prop of props as any[]) {
610 if (!prop.isProperty()) continue;
611
612 const key = prop.get("key");
613
614 // { foo: obj }
615 let match =
616 prop.isnt("computed") && key.isIdentifier({ name: targetName });
617
618 // { "foo": "obj" } or { ["foo"]: "obj" }
619 match = match || key.isLiteral({ value: targetName });
620
621 if (match) return prop.get("value").resolve(dangerous, resolved);
622 }
623 } else if (target.isArrayExpression() && !isNaN(+targetName)) {
624 const elems = target.get("elements");
625 const elem = elems[targetName];
626 if (elem) return elem.resolve(dangerous, resolved);
627 }
628 }
629 }
630
631 export function isConstantExpression(this: NodePath): boolean {
632 if (this.isIdentifier()) {
633 const binding = this.scope.getBinding(this.node.name);
634 if (!binding) return false;
635 return binding.constant;
636 }
637
638 if (this.isLiteral()) {
639 if (this.isRegExpLiteral()) {
640 return false;
641 }
642
643 if (this.isTemplateLiteral()) {
644 return this.get("expressions").every(expression =>
645 expression.isConstantExpression(),
646 );
647 }
648
649 return true;
650 }
651
652 if (this.isUnaryExpression()) {
653 if (this.node.operator !== "void") {
654 return false;
655 }
656
657 return this.get("argument").isConstantExpression();
658 }
659
660 if (this.isBinaryExpression()) {
661 const { operator } = this.node;
662 return (
663 operator !== "in" &&
664 operator !== "instanceof" &&
665 this.get("left").isConstantExpression() &&
666 this.get("right").isConstantExpression()
667 );
668 }
669
670 return false;
671 }
672
673 export function isInStrictMode(this: NodePath) {
674 const start = this.isProgram() ? this : this.parentPath;
675
676 const strictParent = start.find(path => {
677 if (path.isProgram({ sourceType: "module" })) return true;
678
679 if (path.isClass()) return true;
680
681 if (
682 path.isArrowFunctionExpression() &&
683 !path.get("body").isBlockStatement()
684 ) {
685 return false;
686 }
687
688 let body: t.BlockStatement | t.Program;
689 if (path.isFunction()) {
690 body = path.node.body as t.BlockStatement;
691 } else if (path.isProgram()) {
692 body = path.node;
693 } else {
694 return false;
695 }
696
697 for (const directive of body.directives) {
698 if (directive.value.value === "use strict") {
699 return true;
700 }
701 }
702 });
703
704 return !!strictParent;
705 }