/
index.ts
421 lines (367 loc) 路 14.1 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
import type { HubInterface } from "../hub.ts";
import type TraversalContext from "../context.ts";
import type { ExplodedTraverseOptions } from "../index.ts";
import * as virtualTypes from "./lib/virtual-types.ts";
import buildDebug from "debug";
import traverse from "../index.ts";
import type { Visitor } from "../types.ts";
import Scope from "../scope/index.ts";
import { validate } from "@babel/types";
import * as t from "@babel/types";
import * as cache from "../cache.ts";
import generator from "@babel/generator";
// NodePath is split across many files.
import * as NodePath_ancestry from "./ancestry.ts";
import * as NodePath_inference from "./inference/index.ts";
import * as NodePath_replacement from "./replacement.ts";
import * as NodePath_evaluation from "./evaluation.ts";
import * as NodePath_conversion from "./conversion.ts";
import * as NodePath_introspection from "./introspection.ts";
import * as NodePath_context from "./context.ts";
import * as NodePath_removal from "./removal.ts";
import * as NodePath_modification from "./modification.ts";
import * as NodePath_family from "./family.ts";
import * as NodePath_comments from "./comments.ts";
import * as NodePath_virtual_types_validator from "./lib/virtual-types-validator.ts";
import type { NodePathAssertions } from "./generated/asserts.ts";
import type { NodePathValidators } from "./generated/validators.ts";
const debug = buildDebug("babel");
export const REMOVED = 1 << 0;
export const SHOULD_STOP = 1 << 1;
export const SHOULD_SKIP = 1 << 2;
declare const bit: import("../../../../scripts/babel-plugin-bit-decorator/types.d.ts").BitDecorator<any>;
const NodePath_Final = class NodePath {
constructor(hub: HubInterface, parent: t.Node | null) {
this.parent = parent;
this.hub = hub;
this.data = null;
this.context = null;
this.scope = null;
}
declare parent: t.Node;
declare hub: HubInterface;
declare data: Record<string | symbol, unknown>;
// TraversalContext is configured by setContext
declare context: TraversalContext;
declare scope: Scope;
contexts: Array<TraversalContext> = [];
state: any = null;
opts: ExplodedTraverseOptions | null = null;
@bit.storage _traverseFlags: number;
@bit(REMOVED) accessor removed = false;
@bit(SHOULD_STOP) accessor shouldStop = false;
@bit(SHOULD_SKIP) accessor shouldSkip = false;
skipKeys: Record<string, boolean> | null = null;
parentPath: NodePath_Final | null = null;
container: t.Node | Array<t.Node> | null = null;
listKey: string | null = null;
key: string | number | null = null;
node: t.Node | null = null;
type: t.Node["type"] | null = null;
static get({
hub,
parentPath,
parent,
container,
listKey,
key,
}: {
hub?: HubInterface;
parentPath: NodePath_Final | null;
parent: t.Node;
container: t.Node | t.Node[];
listKey?: string;
key: string | number;
}): NodePath_Final {
if (!hub && parentPath) {
hub = parentPath.hub;
}
if (!parent) {
throw new Error("To get a node path the parent needs to exist");
}
const targetNode =
// @ts-expect-error key must present in container
container[key];
const paths = cache.getOrCreateCachedPaths(hub, parent);
let path = paths.get(targetNode);
if (!path) {
path = new NodePath(hub, parent) as NodePath_Final;
if (targetNode) paths.set(targetNode, path);
}
path.setup(parentPath, container, listKey, key);
return path;
}
getScope(this: NodePath_Final, scope: Scope): Scope {
return this.isScope() ? new Scope(this) : scope;
}
setData(key: string | symbol, val: any): any {
if (this.data == null) {
this.data = Object.create(null);
}
return (this.data[key] = val);
}
getData(key: string | symbol, def?: any): any {
if (this.data == null) {
this.data = Object.create(null);
}
let val = this.data[key];
if (val === undefined && def !== undefined) val = this.data[key] = def;
return val;
}
hasNode(): boolean {
return this.node != null;
}
buildCodeFrameError(
msg: string,
Error: new () => Error = SyntaxError,
): Error {
return this.hub.buildError(this.node, msg, Error);
}
traverse<T>(this: NodePath_Final, visitor: Visitor<T>, state: T): void;
traverse(this: NodePath_Final, visitor: Visitor): void;
traverse(this: NodePath_Final, visitor: any, state?: any) {
traverse(this.node, visitor, this.scope, state, this);
}
set(key: string, node: any) {
validate(this.node, key, node);
// @ts-expect-error key must present in this.node
this.node[key] = node;
}
getPathLocation(this: NodePath_Final): string {
const parts = [];
let path: NodePath_Final = this;
do {
let key = path.key;
if (path.inList) key = `${path.listKey}[${key}]`;
parts.unshift(key);
} while ((path = path.parentPath));
return parts.join(".");
}
debug(this: NodePath_Final, message: string) {
if (!debug.enabled) return;
debug(`${this.getPathLocation()} ${this.type}: ${message}`);
}
toString() {
return generator(this.node).code;
}
get inList() {
return !!this.listKey;
}
set inList(inList) {
if (!inList) {
this.listKey = null;
}
// ignore inList = true as it should depend on `listKey`
}
get parentKey(): string {
return (this.listKey || this.key) as string;
}
};
const methods = {
// NodePath_ancestry
findParent: NodePath_ancestry.findParent,
find: NodePath_ancestry.find,
getFunctionParent: NodePath_ancestry.getFunctionParent,
getStatementParent: NodePath_ancestry.getStatementParent,
getEarliestCommonAncestorFrom:
NodePath_ancestry.getEarliestCommonAncestorFrom,
getDeepestCommonAncestorFrom: NodePath_ancestry.getDeepestCommonAncestorFrom,
getAncestry: NodePath_ancestry.getAncestry,
isAncestor: NodePath_ancestry.isAncestor,
isDescendant: NodePath_ancestry.isDescendant,
inType: NodePath_ancestry.inType,
// NodePath_inference
getTypeAnnotation: NodePath_inference.getTypeAnnotation,
_getTypeAnnotation: NodePath_inference._getTypeAnnotation,
isBaseType: NodePath_inference.isBaseType,
couldBeBaseType: NodePath_inference.couldBeBaseType,
baseTypeStrictlyMatches: NodePath_inference.baseTypeStrictlyMatches,
isGenericType: NodePath_inference.isGenericType,
// NodePath_replacement
replaceWithMultiple: NodePath_replacement.replaceWithMultiple,
replaceWithSourceString: NodePath_replacement.replaceWithSourceString,
replaceWith: NodePath_replacement.replaceWith,
_replaceWith: NodePath_replacement._replaceWith,
replaceExpressionWithStatements:
NodePath_replacement.replaceExpressionWithStatements,
replaceInline: NodePath_replacement.replaceInline,
// NodePath_evaluation
evaluateTruthy: NodePath_evaluation.evaluateTruthy,
evaluate: NodePath_evaluation.evaluate,
// NodePath_conversion
toComputedKey: NodePath_conversion.toComputedKey,
ensureBlock: NodePath_conversion.ensureBlock,
unwrapFunctionEnvironment: NodePath_conversion.unwrapFunctionEnvironment,
arrowFunctionToExpression: NodePath_conversion.arrowFunctionToExpression,
// NodePath_introspection
matchesPattern: NodePath_introspection.matchesPattern,
has: NodePath_introspection.has,
isStatic: NodePath_introspection.isStatic,
is: NodePath_introspection.is,
isnt: NodePath_introspection.isnt,
equals: NodePath_introspection.equals,
isNodeType: NodePath_introspection.isNodeType,
canHaveVariableDeclarationOrExpression:
NodePath_introspection.canHaveVariableDeclarationOrExpression,
canSwapBetweenExpressionAndStatement:
NodePath_introspection.canSwapBetweenExpressionAndStatement,
isCompletionRecord: NodePath_introspection.isCompletionRecord,
isStatementOrBlock: NodePath_introspection.isStatementOrBlock,
referencesImport: NodePath_introspection.referencesImport,
getSource: NodePath_introspection.getSource,
willIMaybeExecuteBefore: NodePath_introspection.willIMaybeExecuteBefore,
_guessExecutionStatusRelativeTo:
NodePath_introspection._guessExecutionStatusRelativeTo,
resolve: NodePath_introspection.resolve,
_resolve: NodePath_introspection._resolve,
isConstantExpression: NodePath_introspection.isConstantExpression,
isInStrictMode: NodePath_introspection.isInStrictMode,
// NodePath_context
call: NodePath_context.call,
_call: NodePath_context._call,
isDenylisted: NodePath_context.isDenylisted,
isBlacklisted: NodePath_context.isBlacklisted,
visit: NodePath_context.visit,
skip: NodePath_context.skip,
skipKey: NodePath_context.skipKey,
stop: NodePath_context.stop,
setScope: NodePath_context.setScope,
setContext: NodePath_context.setContext,
resync: NodePath_context.resync,
_resyncParent: NodePath_context._resyncParent,
_resyncKey: NodePath_context._resyncKey,
_resyncList: NodePath_context._resyncList,
_resyncRemoved: NodePath_context._resyncRemoved,
popContext: NodePath_context.popContext,
pushContext: NodePath_context.pushContext,
setup: NodePath_context.setup,
setKey: NodePath_context.setKey,
requeue: NodePath_context.requeue,
_getQueueContexts: NodePath_context._getQueueContexts,
// NodePath_removal
remove: NodePath_removal.remove,
_removeFromScope: NodePath_removal._removeFromScope,
_callRemovalHooks: NodePath_removal._callRemovalHooks,
_remove: NodePath_removal._remove,
_markRemoved: NodePath_removal._markRemoved,
_assertUnremoved: NodePath_removal._assertUnremoved,
// NodePath_modification
insertBefore: NodePath_modification.insertBefore,
_containerInsert: NodePath_modification._containerInsert,
_containerInsertBefore: NodePath_modification._containerInsertBefore,
_containerInsertAfter: NodePath_modification._containerInsertAfter,
insertAfter: NodePath_modification.insertAfter,
updateSiblingKeys: NodePath_modification.updateSiblingKeys,
_verifyNodeList: NodePath_modification._verifyNodeList,
unshiftContainer: NodePath_modification.unshiftContainer,
pushContainer: NodePath_modification.pushContainer,
hoist: NodePath_modification.hoist,
// NodePath_family
getOpposite: NodePath_family.getOpposite,
getCompletionRecords: NodePath_family.getCompletionRecords,
getSibling: NodePath_family.getSibling,
getPrevSibling: NodePath_family.getPrevSibling,
getNextSibling: NodePath_family.getNextSibling,
getAllNextSiblings: NodePath_family.getAllNextSiblings,
getAllPrevSiblings: NodePath_family.getAllPrevSiblings,
get: NodePath_family.get,
_getKey: NodePath_family._getKey,
_getPattern: NodePath_family._getPattern,
getBindingIdentifiers: NodePath_family.getBindingIdentifiers,
getOuterBindingIdentifiers: NodePath_family.getOuterBindingIdentifiers,
getBindingIdentifierPaths: NodePath_family.getBindingIdentifierPaths,
getOuterBindingIdentifierPaths:
NodePath_family.getOuterBindingIdentifierPaths,
// NodePath_comments
shareCommentsWithSiblings: NodePath_comments.shareCommentsWithSiblings,
addComment: NodePath_comments.addComment,
addComments: NodePath_comments.addComments,
};
Object.assign(NodePath_Final.prototype, methods);
if (!process.env.BABEL_8_BREAKING && !USE_ESM) {
// @ts-expect-error babel 7 only
NodePath_Final.prototype.arrowFunctionToShadowed =
// workaround for rollup
// @ts-expect-error babel 7 only
NodePath_conversion[String("arrowFunctionToShadowed")];
}
if (!process.env.BABEL_8_BREAKING) {
// @ts-expect-error The original _guessExecutionStatusRelativeToDifferentFunctions only worked for paths in
// different functions, but _guessExecutionStatusRelativeTo works as a replacement in those cases.
NodePath_Final.prototype._guessExecutionStatusRelativeToDifferentFunctions =
NodePath_introspection._guessExecutionStatusRelativeTo;
}
// we can not use `import { TYPES } from "@babel/types"` here
// because the transformNamedBabelTypesImportToDestructuring plugin in babel.config.js
// does not offer live bindings for `TYPES`
// we can change to `import { TYPES }` when we are publishing ES modules only
for (const type of t.TYPES) {
const typeKey = `is${type}`;
// @ts-expect-error typeKey must present in t
const fn = t[typeKey];
// @ts-expect-error augmenting NodePath prototype
NodePath_Final.prototype[typeKey] = function (opts: any) {
return fn(this.node, opts);
};
// @ts-expect-error augmenting NodePath prototype
NodePath_Final.prototype[`assert${type}`] = function (opts: any) {
if (!fn(this.node, opts)) {
throw new TypeError(`Expected node path of type ${type}`);
}
};
}
// Register virtual types validators after base types validators
Object.assign(NodePath_Final.prototype, NodePath_virtual_types_validator);
for (const type of Object.keys(virtualTypes) as (keyof typeof virtualTypes)[]) {
if (type[0] === "_") continue;
if (!t.TYPES.includes(type)) t.TYPES.push(type);
}
interface NodePathOverwrites {
// We need to re-define these predicate and assertion
// methods here, because we cannot refine `this` in
// a function declaration.
// See https://github.com/microsoft/TypeScript/issues/38150
/**
* NOTE: This assertion doesn't narrow the type on unions of
* NodePaths, due to https://github.com/microsoft/TypeScript/issues/44212
*
* @see ./conversion.ts for implementation.
*/
ensureBlock(
this: NodePath_Final,
): asserts this is NodePath_Final<
(
| t.Loop
| t.WithStatement
| t.Function
| t.LabeledStatement
| t.CatchClause
) & { body: t.BlockStatement }
>;
/**
* @see ./introspection.ts for implementation.
*/
isStatementOrBlock(
this: NodePath_Final,
): this is NodePath_Final<t.Statement | t.Block>;
}
type NodePathMixins = Omit<typeof methods, keyof NodePathOverwrites>;
interface NodePath<T extends t.Node>
extends InstanceType<typeof NodePath_Final>,
NodePathAssertions,
NodePathValidators,
NodePathMixins,
NodePathOverwrites {
type: T["type"] | null;
node: T;
parent: t.ParentMaps[T["type"]];
parentPath: t.ParentMaps[T["type"]] extends null
? null
: NodePath_Final<t.ParentMaps[T["type"]]> | null;
}
// This trick is necessary so that
// NodePath_Final<A | B> is the same as NodePath_Final<A> | NodePath_Final<B>
type NodePath_Final<T extends t.Node = t.Node> = T extends any
? NodePath<T>
: never;
export { NodePath_Final as default, type NodePath as NodePath_Internal };