Debian Codegraph @

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

raw symbols SCIP
1 // This file contains methods responsible for dealing with/retrieving children or siblings.
2
3 import type TraversalContext from "../context";
4 import NodePath from "./index";
5 import {
6 getBindingIdentifiers as _getBindingIdentifiers,
7 getOuterBindingIdentifiers as _getOuterBindingIdentifiers,
8 isDeclaration,
9 numericLiteral,
10 unaryExpression,
11 } from "@babel/types";
12 import type * as t from "@babel/types";
13
14 const NORMAL_COMPLETION = 0 as const;
15 const BREAK_COMPLETION = 1 as const;
16
17 type Completion = {
18 path: NodePath;
19 type: 0 | 1;
20 };
21
22 type CompletionContext = {
23 // whether the current context allows `break` statement. When it allows, we have
24 // to search all the statements for potential `break`
25 canHaveBreak: boolean;
26 // whether the statement is an immediate descendant of a switch case clause
27 inCaseClause: boolean;
28 // whether the `break` statement record should be populated to upper level
29 // when a `break` statement is an immediate descendant of a block statement, e.g.
30 // `{ break }`, it can influence the control flow in the upper levels.
31 shouldPopulateBreak: boolean;
32 };
33
34 function NormalCompletion(path: NodePath) {
35 return { type: NORMAL_COMPLETION, path };
36 }
37
38 function BreakCompletion(path: NodePath) {
39 return { type: BREAK_COMPLETION, path };
40 }
41
42 export function getOpposite(this: NodePath): NodePath | null {
43 if (this.key === "left") {
44 return this.getSibling("right");
45 } else if (this.key === "right") {
46 return this.getSibling("left");
47 }
48 return null;
49 }
50
51 function addCompletionRecords(
52 path: NodePath | null | undefined,
53 records: Completion[],
54 context: CompletionContext,
55 ): Completion[] {
56 if (path) {
57 records.push(..._getCompletionRecords(path, context));
58 }
59 return records;
60 }
61
62 function completionRecordForSwitch(
63 cases: NodePath<t.SwitchCase>[],
64 records: Completion[],
65 context: CompletionContext,
66 ): Completion[] {
67 // https://tc39.es/ecma262/#sec-runtime-semantics-caseblockevaluation
68 let lastNormalCompletions: Completion[] = [];
69 for (let i = 0; i < cases.length; i++) {
70 const casePath = cases[i];
71 const caseCompletions = _getCompletionRecords(casePath, context);
72 const normalCompletions = [];
73 const breakCompletions = [];
74 for (const c of caseCompletions) {
75 if (c.type === NORMAL_COMPLETION) {
76 normalCompletions.push(c);
77 }
78 if (c.type === BREAK_COMPLETION) {
79 breakCompletions.push(c);
80 }
81 }
82 if (normalCompletions.length) {
83 lastNormalCompletions = normalCompletions;
84 }
85 records.push(...breakCompletions);
86 }
87 records.push(...lastNormalCompletions);
88 return records;
89 }
90
91 function normalCompletionToBreak(completions: Completion[]) {
92 completions.forEach(c => {
93 c.type = BREAK_COMPLETION;
94 });
95 }
96
97 /**
98 * Determine how we should handle the break statement for break completions
99 *
100 * @param {Completion[]} completions
101 * @param {boolean} reachable Whether the break statement is reachable after
102 we mark the normal completions _before_ the given break completions as the final
103 completions. For example,
104 `{ 0 }; break;` is transformed to `{ return 0 }; break;`, the `break` here is unreachable
105 and thus can be removed without consequences. We may in the future reserve them instead since
106 we do not consistently remove unreachable statements _after_ break
107 `{ var x = 0 }; break;` is transformed to `{ var x = 0 }; return void 0;`, the `break` is reachable
108 because we can not wrap variable declaration under a return statement
109 */
110 function replaceBreakStatementInBreakCompletion(
111 completions: Completion[],
112 reachable: boolean,
113 ) {
114 completions.forEach(c => {
115 if (c.path.isBreakStatement({ label: null })) {
116 if (reachable) {
117 c.path.replaceWith(unaryExpression("void", numericLiteral(0)));
118 } else {
119 c.path.remove();
120 }
121 }
122 });
123 }
124
125 function getStatementListCompletion(
126 paths: NodePath[],
127 context: CompletionContext,
128 ): Completion[] {
129 const completions = [];
130 if (context.canHaveBreak) {
131 let lastNormalCompletions = [];
132 for (let i = 0; i < paths.length; i++) {
133 const path = paths[i];
134 const newContext = { ...context, inCaseClause: false };
135 if (
136 path.isBlockStatement() &&
137 (context.inCaseClause || // case test: { break }
138 context.shouldPopulateBreak) // case test: { { break } }
139 ) {
140 newContext.shouldPopulateBreak = true;
141 } else {
142 newContext.shouldPopulateBreak = false;
143 }
144 const statementCompletions = _getCompletionRecords(path, newContext);
145 if (
146 statementCompletions.length > 0 &&
147 // we can stop search `paths` when we have seen a `path` that is
148 // effectively a `break` statement. Examples are
149 // - `break`
150 // - `if (true) { 1; break } else { 2; break }`
151 // - `{ break }```
152 // In other words, the paths after this `path` are unreachable
153 statementCompletions.every(c => c.type === BREAK_COMPLETION)
154 ) {
155 if (
156 lastNormalCompletions.length > 0 &&
157 statementCompletions.every(c =>
158 c.path.isBreakStatement({ label: null }),
159 )
160 ) {
161 // when a break completion has a path as BreakStatement, it must be `{ break }`
162 // whose completion value we can not determine, otherwise it would have been
163 // replaced by `replaceBreakStatementInBreakCompletion`
164 // When we have seen normal completions from the last statement
165 // it is safe to stop populating break and mark normal completions as break
166 normalCompletionToBreak(lastNormalCompletions);
167 completions.push(...lastNormalCompletions);
168 // Declarations have empty completion record, however they can not be nested
169 // directly in return statement, i.e. `return (var a = 1)` is invalid.
170 if (lastNormalCompletions.some(c => c.path.isDeclaration())) {
171 completions.push(...statementCompletions);
172 replaceBreakStatementInBreakCompletion(
173 statementCompletions,
174 /* reachable */ true,
175 );
176 }
177 replaceBreakStatementInBreakCompletion(
178 statementCompletions,
179 /* reachable */ false,
180 );
181 } else {
182 completions.push(...statementCompletions);
183 if (!context.shouldPopulateBreak) {
184 replaceBreakStatementInBreakCompletion(
185 statementCompletions,
186 /* reachable */ true,
187 );
188 }
189 }
190 break;
191 }
192 if (i === paths.length - 1) {
193 completions.push(...statementCompletions);
194 } else {
195 lastNormalCompletions = [];
196 for (let i = 0; i < statementCompletions.length; i++) {
197 const c = statementCompletions[i];
198 if (c.type === BREAK_COMPLETION) {
199 completions.push(c);
200 }
201 if (c.type === NORMAL_COMPLETION) {
202 lastNormalCompletions.push(c);
203 }
204 }
205 }
206 }
207 } else if (paths.length) {
208 // When we are in a context where `break` must not exist, we can skip linear
209 // search on statement lists and assume that the last
210 // non-variable-declaration statement determines the completion.
211 for (let i = paths.length - 1; i >= 0; i--) {
212 const pathCompletions = _getCompletionRecords(paths[i], context);
213 if (
214 pathCompletions.length > 1 ||
215 (pathCompletions.length === 1 &&
216 !pathCompletions[0].path.isVariableDeclaration())
217 ) {
218 completions.push(...pathCompletions);
219 break;
220 }
221 }
222 }
223 return completions;
224 }
225
226 function _getCompletionRecords(
227 path: NodePath,
228 context: CompletionContext,
229 ): Completion[] {
230 let records: Completion[] = [];
231 if (path.isIfStatement()) {
232 records = addCompletionRecords(path.get("consequent"), records, context);
233 records = addCompletionRecords(path.get("alternate"), records, context);
234 } else if (
235 path.isDoExpression() ||
236 path.isFor() ||
237 path.isWhile() ||
238 path.isLabeledStatement()
239 ) {
240 // @ts-expect-error(flow->ts): todo
241 return addCompletionRecords(path.get("body"), records, context);
242 } else if (path.isProgram() || path.isBlockStatement()) {
243 // @ts-expect-error(flow->ts): todo
244 return getStatementListCompletion(path.get("body"), context);
245 } else if (path.isFunction()) {
246 return _getCompletionRecords(path.get("body"), context);
247 } else if (path.isTryStatement()) {
248 records = addCompletionRecords(path.get("block"), records, context);
249 records = addCompletionRecords(path.get("handler"), records, context);
250 } else if (path.isCatchClause()) {
251 return addCompletionRecords(path.get("body"), records, context);
252 } else if (path.isSwitchStatement()) {
253 return completionRecordForSwitch(path.get("cases"), records, context);
254 } else if (path.isSwitchCase()) {
255 return getStatementListCompletion(path.get("consequent"), {
256 canHaveBreak: true,
257 shouldPopulateBreak: false,
258 inCaseClause: true,
259 });
260 } else if (path.isBreakStatement()) {
261 records.push(BreakCompletion(path));
262 } else {
263 records.push(NormalCompletion(path));
264 }
265
266 return records;
267 }
268
269 /**
270 * Retrieve the completion records of a given path.
271 * Note: to ensure proper support on `break` statement, this method
272 * will manipulate the AST around the break statement. Do not call the method
273 * twice for the same path.
274 *
275 * @export
276 * @param {NodePath} this
277 * @returns {NodePath[]} Completion records
278 */
279 export function getCompletionRecords(this: NodePath): NodePath[] {
280 const records = _getCompletionRecords(this, {
281 canHaveBreak: false,
282 shouldPopulateBreak: false,
283 inCaseClause: false,
284 });
285 return records.map(r => r.path);
286 }
287
288 export function getSibling(this: NodePath, key: string | number): NodePath {
289 return NodePath.get({
290 parentPath: this.parentPath,
291 parent: this.parent,
292 container: this.container,
293 listKey: this.listKey,
294 key: key,
295 }).setContext(this.context);
296 }
297
298 export function getPrevSibling(this: NodePath): NodePath {
299 // @ts-expect-error todo(flow->ts) this.key could be a string
300 return this.getSibling(this.key - 1);
301 }
302
303 export function getNextSibling(this: NodePath): NodePath {
304 // @ts-expect-error todo(flow->ts) this.key could be a string
305 return this.getSibling(this.key + 1);
306 }
307
308 export function getAllNextSiblings(this: NodePath): NodePath[] {
309 // @ts-expect-error todo(flow->ts) this.key could be a string
310 let _key: number = this.key;
311 let sibling = this.getSibling(++_key);
312 const siblings = [];
313 while (sibling.node) {
314 siblings.push(sibling);
315 sibling = this.getSibling(++_key);
316 }
317 return siblings;
318 }
319
320 export function getAllPrevSiblings(this: NodePath): NodePath[] {
321 // @ts-expect-error todo(flow->ts) this.key could be a string
322 let _key: number = this.key;
323 let sibling = this.getSibling(--_key);
324 const siblings = [];
325 while (sibling.node) {
326 siblings.push(sibling);
327 sibling = this.getSibling(--_key);
328 }
329 return siblings;
330 }
331
332 // convert "1" to 1 (string index to number index)
333 type MaybeToIndex<T extends string> = T extends `${bigint}` ? number : T;
334
335 type Pattern<Obj extends string, Prop extends string> = `${Obj}.${Prop}`;
336
337 // split "body.body.1" to ["body", "body", 1]
338 type Split<P extends string> = P extends Pattern<infer O, infer U>
339 ? [MaybeToIndex<O>, ...Split<U>]
340 : [MaybeToIndex<P>];
341
342 // get all K with Node[K] is t.Node | t.Node[]
343 type NodeKeyOf<Node extends t.Node | t.Node[]> = keyof Pick<
344 Node,
345 {
346 [Key in keyof Node]-?: Node[Key] extends t.Node | t.Node[] ? Key : never;
347 }[keyof Node]
348 >;
349
350 // traverse the Node with tuple path ["body", "body", 1]
351 // Path should be created with Split
352 type Trav<
353 Node extends t.Node | t.Node[],
354 Path extends unknown[],
355 > = Path extends [infer K, ...infer R]
356 ? K extends NodeKeyOf<Node>
357 ? R extends []
358 ? Node[K]
359 : // @ts-expect-error ignore since TS is not smart enough
360 Trav<Node[K], R>
361 : never
362 : never;
363
364 type ToNodePath<T> = T extends Array<t.Node | null | undefined>
365 ? Array<NodePath<T[number]>>
366 : T extends t.Node | null | undefined
367 ? NodePath<T>
368 : never;
369
370 function get<T extends t.Node, K extends keyof T>(
371 this: NodePath<T>,
372 key: K,
373 context?: boolean | TraversalContext,
374 ): T[K] extends Array<t.Node | null | undefined>
375 ? Array<NodePath<T[K][number]>>
376 : T[K] extends t.Node | null | undefined
377 ? NodePath<T[K]>
378 : never;
379
380 function get<T extends t.Node, K extends string>(
381 this: NodePath<T>,
382 key: K,
383 context?: boolean | TraversalContext,
384 ): ToNodePath<Trav<T, Split<K>>>;
385
386 function get<T extends t.Node>(
387 this: NodePath<T>,
388 key: string,
389 context?: true | TraversalContext,
390 ): NodePath | NodePath[];
391
392 function get<T extends t.Node>(
393 this: NodePath<T>,
394 key: string,
395 context: true | TraversalContext = true,
396 ): NodePath | NodePath[] {
397 if (context === true) context = this.context;
398 const parts = key.split(".");
399 if (parts.length === 1) {
400 // "foo"
401 // @ts-expect-error key may not index T
402 return this._getKey(key, context);
403 } else {
404 // "foo.bar"
405 return this._getPattern(parts, context);
406 }
407 }
408
409 export { get };
410
411 export function _getKey<T extends t.Node>(
412 this: NodePath<T>,
413 key: keyof T & string,
414 context?: TraversalContext,
415 ): NodePath | NodePath[] {
416 const node = this.node;
417 const container = node[key];
418
419 if (Array.isArray(container)) {
420 // requested a container so give them all the paths
421 return container.map((_, i) => {
422 return NodePath.get({
423 listKey: key,
424 parentPath: this,
425 parent: node,
426 container: container,
427 key: i,
428 }).setContext(context);
429 });
430 } else {
431 return NodePath.get({
432 parentPath: this,
433 parent: node,
434 container: node,
435 key: key,
436 }).setContext(context);
437 }
438 }
439
440 export function _getPattern(
441 this: NodePath,
442 parts: string[],
443 context?: TraversalContext,
444 ): NodePath | NodePath[] {
445 let path: NodePath | NodePath[] = this;
446 for (const part of parts) {
447 if (part === ".") {
448 // @ts-expect-error todo(flow-ts): Can path be an array here?
449 path = path.parentPath;
450 } else {
451 if (Array.isArray(path)) {
452 // @ts-expect-error part may not index path
453 path = path[part];
454 } else {
455 path = path.get(part, context);
456 }
457 }
458 }
459 return path;
460 }
461
462 function getBindingIdentifiers(
463 duplicates: true,
464 ): Record<string, t.Identifier[]>;
465 function getBindingIdentifiers(
466 duplicates?: false,
467 ): Record<string, t.Identifier>;
468 function getBindingIdentifiers(
469 duplicates: boolean,
470 ): Record<string, t.Identifier[] | t.Identifier>;
471
472 function getBindingIdentifiers(
473 this: NodePath,
474 duplicates?: boolean,
475 ): Record<string, t.Identifier[] | t.Identifier> {
476 return _getBindingIdentifiers(this.node, duplicates);
477 }
478
479 export { getBindingIdentifiers };
480
481 function getOuterBindingIdentifiers(
482 duplicates: true,
483 ): Record<string, t.Identifier[]>;
484 function getOuterBindingIdentifiers(
485 duplicates?: false,
486 ): Record<string, t.Identifier>;
487 function getOuterBindingIdentifiers(
488 duplicates: boolean,
489 ): Record<string, t.Identifier[] | t.Identifier>;
490
491 function getOuterBindingIdentifiers(
492 this: NodePath,
493 duplicates?: boolean,
494 ): Record<string, t.Identifier[] | t.Identifier> {
495 return _getOuterBindingIdentifiers(this.node, duplicates);
496 }
497
498 export { getOuterBindingIdentifiers };
499
500 function getBindingIdentifierPaths(
501 duplicates: true,
502 outerOnly?: boolean,
503 ): Record<string, NodePath<t.Identifier>[]>;
504 function getBindingIdentifierPaths(
505 duplicates: false,
506 outerOnly?: boolean,
507 ): Record<string, NodePath<t.Identifier>>;
508 function getBindingIdentifierPaths(
509 duplicates?: boolean,
510 outerOnly?: boolean,
511 ): Record<string, NodePath<t.Identifier> | NodePath<t.Identifier>[]>;
512
513 // original source - https://github.com/babel/babel/blob/main/packages/babel-types/src/retrievers/getBindingIdentifiers.js
514 // path.getBindingIdentifiers returns nodes where the following re-implementation returns paths
515 function getBindingIdentifierPaths(
516 this: NodePath,
517 duplicates: boolean = false,
518 outerOnly: boolean = false,
519 ): Record<string, NodePath<t.Identifier> | NodePath<t.Identifier>[]> {
520 const path = this;
521 const search = [path];
522 const ids = Object.create(null);
523
524 while (search.length) {
525 const id = search.shift();
526 if (!id) continue;
527 if (!id.node) continue;
528
529 const keys =
530 // @ts-expect-error _getBindingIdentifiers.keys do not cover all node types
531 _getBindingIdentifiers.keys[id.node.type];
532
533 if (id.isIdentifier()) {
534 if (duplicates) {
535 const _ids = (ids[id.node.name] = ids[id.node.name] || []);
536 _ids.push(id);
537 } else {
538 ids[id.node.name] = id;
539 }
540 continue;
541 }
542
543 if (id.isExportDeclaration()) {
544 const declaration = id.get("declaration");
545 if (isDeclaration(declaration)) {
546 search.push(declaration);
547 }
548 continue;
549 }
550
551 if (outerOnly) {
552 if (id.isFunctionDeclaration()) {
553 search.push(id.get("id"));
554 continue;
555 }
556 if (id.isFunctionExpression()) {
557 continue;
558 }
559 }
560
561 if (keys) {
562 for (let i = 0; i < keys.length; i++) {
563 const key = keys[i];
564 const child = id.get(key);
565 if (Array.isArray(child)) {
566 search.push(...child);
567 } else if (child.node) {
568 search.push(child);
569 }
570 }
571 }
572 }
573
574 return ids;
575 }
576
577 export { getBindingIdentifierPaths };
578
579 function getOuterBindingIdentifierPaths(
580 duplicates: true,
581 ): Record<string, NodePath<t.Identifier>[]>;
582 function getOuterBindingIdentifierPaths(
583 duplicates?: false,
584 ): Record<string, NodePath<t.Identifier>>;
585 function getOuterBindingIdentifierPaths(
586 duplicates?: boolean,
587 ): Record<string, NodePath<t.Identifier> | NodePath<t.Identifier>[]>;
588
589 function getOuterBindingIdentifierPaths(
590 this: NodePath,
591 duplicates: boolean = false,
592 ) {
593 return this.getBindingIdentifierPaths(duplicates, true);
594 }
595
596 export { getOuterBindingIdentifierPaths };