Debian Codegraph @

packages/babel-traverse/src/path/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 type { HubInterface } from "../hub";
2 import type TraversalContext from "../context";
3 import * as virtualTypes from "./lib/virtual-types";
4 import buildDebug from "debug";
5 import traverse from "../index";
6 import type { Visitor } from "../types";
7 import Scope from "../scope";
8 import { validate } from "@babel/types";
9 import * as t from "@babel/types";
10 import { path as pathCache } from "../cache";
11 import generator from "@babel/generator";
12
13 // NodePath is split across many files.
14 import * as NodePath_ancestry from "./ancestry";
15 import * as NodePath_inference from "./inference";
16 import * as NodePath_replacement from "./replacement";
17 import * as NodePath_evaluation from "./evaluation";
18 import * as NodePath_conversion from "./conversion";
19 import * as NodePath_introspection from "./introspection";
20 import * as NodePath_context from "./context";
21 import * as NodePath_removal from "./removal";
22 import * as NodePath_modification from "./modification";
23 import * as NodePath_family from "./family";
24 import * as NodePath_comments from "./comments";
25 import * as NodePath_virtual_types_validator from "./lib/virtual-types-validator";
26 import type { NodePathAssertions } from "./generated/asserts";
27 import type { NodePathValidators } from "./generated/validators";
28
29 const debug = buildDebug("babel");
30
31 export const REMOVED = 1 << 0;
32 export const SHOULD_STOP = 1 << 1;
33 export const SHOULD_SKIP = 1 << 2;
34
35 class NodePath<T extends t.Node = t.Node> {
36 constructor(hub: HubInterface, parent: t.ParentMaps[T["type"]]) {
37 this.parent = parent;
38 this.hub = hub;
39 this.data = null;
40
41 this.context = null;
42 this.scope = null;
43 }
44
45 declare parent: t.ParentMaps[T["type"]];
46 declare hub: HubInterface;
47 declare data: Record<string | symbol, unknown>;
48 // TraversalContext is configured by setContext
49 declare context: TraversalContext;
50 declare scope: Scope;
51
52 contexts: Array<TraversalContext> = [];
53 state: any = null;
54 opts: any = null;
55 // this.shouldSkip = false; this.shouldStop = false; this.removed = false;
56 _traverseFlags: number = 0;
57 skipKeys: any = null;
58 parentPath: t.ParentMaps[T["type"]] extends null
59 ? null
60 : NodePath<t.ParentMaps[T["type"]]> | null = null;
61 container: t.Node | Array<t.Node> | null = null;
62 listKey: string | null = null;
63 key: string | number | null = null;
64 node: T = null;
65 type: T["type"] | null = null;
66
67 static get({
68 hub,
69 parentPath,
70 parent,
71 container,
72 listKey,
73 key,
74 }: {
75 hub?: HubInterface;
76 parentPath: NodePath | null;
77 parent: t.Node;
78 container: t.Node | t.Node[];
79 listKey?: string;
80 key: string | number;
81 }): NodePath {
82 if (!hub && parentPath) {
83 hub = parentPath.hub;
84 }
85
86 if (!parent) {
87 throw new Error("To get a node path the parent needs to exist");
88 }
89
90 const targetNode =
91 // @ts-expect-error key must present in container
92 container[key];
93
94 let paths = pathCache.get(parent);
95 if (!paths) {
96 paths = new Map();
97 pathCache.set(parent, paths);
98 }
99
100 let path = paths.get(targetNode);
101 if (!path) {
102 path = new NodePath(hub, parent);
103 if (targetNode) paths.set(targetNode, path);
104 }
105
106 path.setup(parentPath, container, listKey, key);
107
108 return path;
109 }
110
111 getScope(scope: Scope): Scope {
112 return this.isScope() ? new Scope(this) : scope;
113 }
114
115 setData(key: string | symbol, val: any): any {
116 if (this.data == null) {
117 this.data = Object.create(null);
118 }
119 return (this.data[key] = val);
120 }
121
122 getData(key: string | symbol, def?: any): any {
123 if (this.data == null) {
124 this.data = Object.create(null);
125 }
126 let val = this.data[key];
127 if (val === undefined && def !== undefined) val = this.data[key] = def;
128 return val;
129 }
130
131 hasNode(): this is NodePath<NonNullable<this["node"]>> {
132 return this.node != null;
133 }
134
135 buildCodeFrameError(
136 msg: string,
137 Error: new () => Error = SyntaxError,
138 ): Error {
139 return this.hub.buildError(this.node, msg, Error);
140 }
141
142 traverse<T>(visitor: Visitor<T>, state: T): void;
143 traverse(visitor: Visitor): void;
144 traverse(visitor: any, state?: any) {
145 traverse(this.node, visitor, this.scope, state, this);
146 }
147
148 set(key: string, node: any) {
149 validate(this.node, key, node);
150 // @ts-expect-error key must present in this.node
151 this.node[key] = node;
152 }
153
154 getPathLocation(): string {
155 const parts = [];
156 let path: NodePath = this;
157 do {
158 let key = path.key;
159 if (path.inList) key = `${path.listKey}[${key}]`;
160 parts.unshift(key);
161 } while ((path = path.parentPath));
162 return parts.join(".");
163 }
164
165 debug(message: string) {
166 if (!debug.enabled) return;
167 debug(`${this.getPathLocation()} ${this.type}: ${message}`);
168 }
169
170 toString() {
171 return generator(this.node).code;
172 }
173
174 get inList() {
175 return !!this.listKey;
176 }
177
178 set inList(inList) {
179 if (!inList) {
180 this.listKey = null;
181 }
182 // ignore inList = true as it should depend on `listKey`
183 }
184
185 get parentKey(): string {
186 return (this.listKey || this.key) as string;
187 }
188
189 get shouldSkip() {
190 return !!(this._traverseFlags & SHOULD_SKIP);
191 }
192
193 set shouldSkip(v) {
194 if (v) {
195 this._traverseFlags |= SHOULD_SKIP;
196 } else {
197 this._traverseFlags &= ~SHOULD_SKIP;
198 }
199 }
200
201 get shouldStop() {
202 return !!(this._traverseFlags & SHOULD_STOP);
203 }
204
205 set shouldStop(v) {
206 if (v) {
207 this._traverseFlags |= SHOULD_STOP;
208 } else {
209 this._traverseFlags &= ~SHOULD_STOP;
210 }
211 }
212
213 get removed() {
214 return !!(this._traverseFlags & REMOVED);
215 }
216 set removed(v) {
217 if (v) {
218 this._traverseFlags |= REMOVED;
219 } else {
220 this._traverseFlags &= ~REMOVED;
221 }
222 }
223 }
224
225 Object.assign(
226 NodePath.prototype,
227 NodePath_ancestry,
228 NodePath_inference,
229 NodePath_replacement,
230 NodePath_evaluation,
231 NodePath_conversion,
232 NodePath_introspection,
233 NodePath_context,
234 NodePath_removal,
235 NodePath_modification,
236 NodePath_family,
237 NodePath_comments,
238 );
239
240 if (!process.env.BABEL_8_BREAKING) {
241 // @ts-expect-error The original _guessExecutionStatusRelativeToDifferentFunctions only worked for paths in
242 // different functions, but _guessExecutionStatusRelativeTo works as a replacement in those cases.
243 NodePath.prototype._guessExecutionStatusRelativeToDifferentFunctions =
244 NodePath_introspection._guessExecutionStatusRelativeTo;
245 }
246
247 // we can not use `import { TYPES } from "@babel/types"` here
248 // because the transformNamedBabelTypesImportToDestructuring plugin in babel.config.js
249 // does not offer live bindings for `TYPES`
250 // we can change to `import { TYPES }` when we are publishing ES modules only
251 for (const type of t.TYPES) {
252 const typeKey = `is${type}`;
253 // @ts-expect-error typeKey must present in t
254 const fn = t[typeKey];
255 // @ts-expect-error augmenting NodePath prototype
256 NodePath.prototype[typeKey] = function (opts: any) {
257 return fn(this.node, opts);
258 };
259
260 // @ts-expect-error augmenting NodePath prototype
261 NodePath.prototype[`assert${type}`] = function (opts: any) {
262 if (!fn(this.node, opts)) {
263 throw new TypeError(`Expected node path of type ${type}`);
264 }
265 };
266 }
267
268 // Register virtual types validators after base types validators
269 Object.assign(NodePath.prototype, NodePath_virtual_types_validator);
270
271 for (const type of Object.keys(virtualTypes) as (keyof typeof virtualTypes)[]) {
272 if (type[0] === "_") continue;
273 if (!t.TYPES.includes(type)) t.TYPES.push(type);
274 }
275
276 type NodePathMixins = typeof NodePath_ancestry &
277 typeof NodePath_inference &
278 typeof NodePath_replacement &
279 typeof NodePath_evaluation &
280 typeof NodePath_conversion &
281 typeof NodePath_introspection &
282 typeof NodePath_context &
283 typeof NodePath_removal &
284 typeof NodePath_modification &
285 typeof NodePath_family &
286 typeof NodePath_comments;
287
288 // @ts-expect-error TS throws because ensureBlock returns the body node path
289 // however, we don't use the return value and treat it as a transform and
290 // assertion utilities. For better type inference we annotate it as an
291 // assertion method
292 // eslint-disable-next-line @typescript-eslint/no-unused-vars
293 interface NodePath<T>
294 extends NodePathAssertions,
295 NodePathValidators,
296 NodePathMixins {
297 /**
298 * @see ./conversion.ts for implementation
299 */
300 ensureBlock<
301 T extends
302 | t.Loop
303 | t.WithStatement
304 | t.Function
305 | t.LabeledStatement
306 | t.CatchClause,
307 >(
308 this: NodePath<T>,
309 ): asserts this is NodePath<T & { body: t.BlockStatement }>;
310 }
311
312 export default NodePath;