Debian Codegraph @

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

raw symbols ◀ ▶ SCIP
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 // @ts-ignore
113 return this.isScope() ? new Scope(this) : scope;
114 }
115
116 setData(key: string | symbol, val: any): any {
117 if (this.data == null) {
118 this.data = Object.create(null);
119 }
120 return (this.data[key] = val);
121 }
122
123 getData(key: string | symbol, def?: any): any {
124 if (this.data == null) {
125 this.data = Object.create(null);
126 }
127 let val = this.data[key];
128 if (val === undefined && def !== undefined) val = this.data[key] = def;
129 return val;
130 }
131
132 hasNode(): this is NodePath<NonNullable<this["node"]>> {
133 return this.node != null;
134 }
135
136 buildCodeFrameError(
137 msg: string,
138 Error: new () => Error = SyntaxError,
139 ): Error {
140 return this.hub.buildError(this.node, msg, Error);
141 }
142
143 traverse<T>(visitor: Visitor<T>, state: T): void;
144 traverse(visitor: Visitor): void;
145 traverse(visitor: any, state?: any) {
146 traverse(this.node, visitor, this.scope, state, this);
147 }
148
149 set(key: string, node: any) {
150 validate(this.node, key, node);
151 // @ts-expect-error key must present in this.node
152 this.node[key] = node;
153 }
154
155 getPathLocation(): string {
156 const parts = [];
157 let path: NodePath = this;
158 do {
159 let key = path.key;
160 if (path.inList) key = `${path.listKey}[${key}]`;
161 parts.unshift(key);
162 } while ((path = path.parentPath));
163 return parts.join(".");
164 }
165
166 debug(message: string) {
167 if (!debug.enabled) return;
168 debug(`${this.getPathLocation()} ${this.type}: ${message}`);
169 }
170
171 toString() {
172 return generator(this.node).code;
173 }
174
175 get inList() {
176 return !!this.listKey;
177 }
178
179 set inList(inList) {
180 if (!inList) {
181 this.listKey = null;
182 }
183 // ignore inList = true as it should depend on `listKey`
184 }
185
186 get parentKey(): string {
187 return (this.listKey || this.key) as string;
188 }
189
190 get shouldSkip() {
191 return !!(this._traverseFlags & SHOULD_SKIP);
192 }
193
194 set shouldSkip(v) {
195 if (v) {
196 this._traverseFlags |= SHOULD_SKIP;
197 } else {
198 this._traverseFlags &= ~SHOULD_SKIP;
199 }
200 }
201
202 get shouldStop() {
203 return !!(this._traverseFlags & SHOULD_STOP);
204 }
205
206 set shouldStop(v) {
207 if (v) {
208 this._traverseFlags |= SHOULD_STOP;
209 } else {
210 this._traverseFlags &= ~SHOULD_STOP;
211 }
212 }
213
214 get removed() {
215 return !!(this._traverseFlags & REMOVED);
216 }
217 set removed(v) {
218 if (v) {
219 this._traverseFlags |= REMOVED;
220 } else {
221 this._traverseFlags &= ~REMOVED;
222 }
223 }
224 }
225
226 Object.assign(
227 NodePath.prototype,
228 NodePath_ancestry,
229 NodePath_inference,
230 NodePath_replacement,
231 NodePath_evaluation,
232 NodePath_conversion,
233 NodePath_introspection,
234 NodePath_context,
235 NodePath_removal,
236 NodePath_modification,
237 NodePath_family,
238 NodePath_comments,
239 );
240
241 if (!process.env.BABEL_8_BREAKING) {
242 // @ts-expect-error The original _guessExecutionStatusRelativeToDifferentFunctions only worked for paths in
243 // different functions, but _guessExecutionStatusRelativeTo works as a replacement in those cases.
244 NodePath.prototype._guessExecutionStatusRelativeToDifferentFunctions =
245 NodePath_introspection._guessExecutionStatusRelativeTo;
246 }
247
248 // we can not use `import { TYPES } from "@babel/types"` here
249 // because the transformNamedBabelTypesImportToDestructuring plugin in babel.config.js
250 // does not offer live bindings for `TYPES`
251 // we can change to `import { TYPES }` when we are publishing ES modules only
252 for (const type of t.TYPES) {
253 const typeKey = `is${type}`;
254 // @ts-expect-error typeKey must present in t
255 const fn = t[typeKey];
256 // @ts-expect-error augmenting NodePath prototype
257 NodePath.prototype[typeKey] = function (opts: any) {
258 return fn(this.node, opts);
259 };
260
261 // @ts-expect-error augmenting NodePath prototype
262 NodePath.prototype[`assert${type}`] = function (opts: any) {
263 if (!fn(this.node, opts)) {
264 throw new TypeError(`Expected node path of type ${type}`);
265 }
266 };
267 }
268
269 // Register virtual types validators after base types validators
270 Object.assign(NodePath.prototype, NodePath_virtual_types_validator);
271
272 for (const type of Object.keys(virtualTypes) as (keyof typeof virtualTypes)[]) {
273 if (type[0] === "_") continue;
274 if (!t.TYPES.includes(type)) t.TYPES.push(type);
275 }
276
277 type NodePathMixins = typeof NodePath_ancestry &
278 typeof NodePath_inference &
279 typeof NodePath_replacement &
280 typeof NodePath_evaluation &
281 typeof NodePath_conversion &
282 typeof NodePath_introspection &
283 typeof NodePath_context &
284 typeof NodePath_removal &
285 typeof NodePath_modification &
286 typeof NodePath_family &
287 typeof NodePath_comments;
288
289 // @ts-expect-error TS throws because ensureBlock returns the body node path
290 // however, we don't use the return value and treat it as a transform and
291 // assertion utilities. For better type inference we annotate it as an
292 // assertion method
293 // eslint-disable-next-line @typescript-eslint/no-unused-vars
294 interface NodePath<T>
295 extends NodePathAssertions,
296 NodePathValidators,
297 NodePathMixins {
298 /**
299 * @see ./conversion.ts for implementation
300 */
301 ensureBlock<
302 T extends
303 | t.Loop
304 | t.WithStatement
305 | t.Function
306 | t.LabeledStatement
307 | t.CatchClause,
308 >(
309 this: NodePath<T>,
310 ): asserts this is NodePath<T & { body: t.BlockStatement }>;
311 }
312
313 export default NodePath;