-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathast-utils.ts
667 lines (570 loc) · 16.4 KB
/
ast-utils.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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
import * as t from "@babel/types";
import { NodePath } from "@babel/traverse";
import { ok } from "assert";
import { deepClone } from "./node";
export function getPatternIdentifierNames(
path: NodePath | NodePath[]
): Set<string> {
if (Array.isArray(path)) {
var allNames = new Set<string>();
for (var p of path) {
var names = getPatternIdentifierNames(p);
for (var name of names) {
allNames.add(name);
}
}
return allNames;
}
var names = new Set<string>();
var functionParent = path.find((parent) => parent.isFunction());
path.traverse({
BindingIdentifier: (bindingPath) => {
var bindingFunctionParent = bindingPath.find((parent) =>
parent.isFunction()
);
if (functionParent === bindingFunctionParent) {
names.add(bindingPath.node.name);
}
},
});
// Check if the path itself is a binding identifier
if (path.isBindingIdentifier()) {
names.add(path.node.name);
}
return names;
}
/**
* Ensures a `String Literal` is 'computed' before replacing it with a more complex expression.
*
* ```js
* // Input
* {
* "myToBeEncodedString": "value"
* }
*
* // Output
* {
* ["myToBeEncodedString"]: "value"
* }
* ```
* @param path
*/
export function ensureComputedExpression(path: NodePath<t.Node>) {
if (
(t.isObjectMember(path.parent) ||
t.isClassMethod(path.parent) ||
t.isClassProperty(path.parent)) &&
path.parent.key === path.node &&
!path.parent.computed
) {
path.parent.computed = true;
}
}
/**
* Retrieves a function name from debugging purposes.
* - Function Declaration / Expression
* - Variable Declaration
* - Object property / method
* - Class property / method
* - Program returns "[Program]"
* - Default returns "anonymous"
* @param path
* @returns
*/
export function getFunctionName(path: NodePath<t.Function>): string {
if (!path) return "null";
if (path.isProgram()) return "[Program]";
// Check function declaration/expression ID
if (
(t.isFunctionDeclaration(path.node) || t.isFunctionExpression(path.node)) &&
path.node.id
) {
return path.node.id.name;
}
// Check for containing variable declaration
if (
path.parentPath?.isVariableDeclarator() &&
t.isIdentifier(path.parentPath.node.id)
) {
return path.parentPath.node.id.name;
}
if (path.isObjectMethod() || path.isClassMethod()) {
var property = getObjectPropertyAsString(path.node);
if (property) return property;
}
// Check for containing property in an object
if (
path.parentPath?.isObjectProperty() ||
path.parentPath?.isClassProperty()
) {
var property = getObjectPropertyAsString(path.parentPath.node);
if (property) return property;
}
var output = "anonymous";
if (path.isFunction()) {
if (path.node.generator) {
output += "*";
} else if (path.node.async) {
output = "async " + output;
}
}
return output;
}
export function isModuleImport(path: NodePath<t.StringLiteral>) {
// Import Declaration
if (path.parentPath.isImportDeclaration()) {
return true;
}
// Dynamic Import / require() call
if (
t.isCallExpression(path.parent) &&
(t.isIdentifier(path.parent.callee, { name: "require" }) ||
t.isImport(path.parent.callee)) &&
path.node === path.parent.arguments[0]
) {
return true;
}
return false;
}
export function getBlock(path: NodePath) {
return path.find((p) => p.isBlock()) as NodePath<t.Block>;
}
export function getParentFunctionOrProgram(
path: NodePath
): NodePath<t.Function | t.Program> {
if (path.isProgram()) return path;
// Find the nearest function-like parent
const functionOrProgramPath = path.findParent(
(parentPath) => parentPath.isFunction() || parentPath.isProgram()
) as NodePath<t.Function | t.Program>;
ok(functionOrProgramPath);
return functionOrProgramPath;
}
export function getObjectPropertyAsString(
property: t.ObjectMember | t.ClassProperty | t.ClassMethod
): string {
ok(
t.isObjectMember(property) ||
t.isClassProperty(property) ||
t.isClassMethod(property)
);
if (!property.computed && t.isIdentifier(property.key)) {
return property.key.name;
}
if (t.isStringLiteral(property.key)) {
return property.key.value;
}
if (t.isNumericLiteral(property.key)) {
return property.key.value.toString();
}
return null;
}
/**
* Gets the property of a MemberExpression as a string.
*
* @param memberPath - The path of the MemberExpression node.
* @returns The property as a string or null if it cannot be determined.
*/
export function getMemberExpressionPropertyAsString(
member: t.MemberExpression
): string | null {
t.assertMemberExpression(member);
const property = member.property;
if (!member.computed && t.isIdentifier(property)) {
return property.name;
}
if (t.isStringLiteral(property)) {
return property.value;
}
if (t.isNumericLiteral(property)) {
return property.value.toString();
}
return null; // If the property cannot be determined
}
function registerPaths(paths: NodePath[]) {
for (var path of paths) {
if (path.isVariableDeclaration() && path.node.kind === "var") {
getParentFunctionOrProgram(path).scope.registerDeclaration(path);
}
path.scope.registerDeclaration(path);
}
return paths;
}
function nodeListToNodes(nodesIn: (t.Statement | t.Statement[])[]) {
var nodes: t.Statement[] = [];
if (Array.isArray(nodesIn[0])) {
ok(nodesIn.length === 1);
nodes = nodesIn[0];
} else {
nodes = nodesIn as t.Statement[];
}
return nodes;
}
/**
* Appends to the bottom of a block. Preserving last expression for the top level.
*/
export function append(
path: NodePath,
...nodesIn: (t.Statement | t.Statement[])[]
) {
var nodes = nodeListToNodes(nodesIn);
var listParent = path.find(
(p) => p.isFunction() || p.isBlock() || p.isSwitchCase()
);
if (!listParent) {
throw new Error("Could not find a suitable parent to prepend to");
}
if (listParent.isProgram()) {
var lastExpression = listParent.get("body").at(-1);
if (lastExpression.isExpressionStatement()) {
return registerPaths(lastExpression.insertBefore(nodes));
}
}
if (listParent.isSwitchCase()) {
return registerPaths(listParent.pushContainer("consequent", nodes));
}
if (listParent.isFunction()) {
var body = listParent.get("body");
if (listParent.isArrowFunctionExpression() && listParent.node.expression) {
if (!body.isBlockStatement()) {
body.replaceWith(
t.blockStatement([t.returnStatement(body.node as t.Expression)])
);
}
}
ok(body.isBlockStatement());
return registerPaths(body.pushContainer("body", nodes));
}
ok(listParent.isBlock());
return registerPaths(listParent.pushContainer("body", nodes));
}
/**
* Prepends and registers a list of nodes to the beginning of a block.
*
* - Preserves import declarations by inserting after the last import declaration.
* - Handles arrow functions
* - Handles switch cases
* @param path
* @param nodes
* @returns
*/
export function prepend(
path: NodePath,
...nodesIn: (t.Statement | t.Statement[])[]
): NodePath[] {
var nodes = nodeListToNodes(nodesIn);
var listParent = path.find(
(p) => p.isFunction() || p.isBlock() || p.isSwitchCase()
);
if (!listParent) {
throw new Error("Could not find a suitable parent to prepend to");
}
if (listParent.isProgram()) {
// Preserve import declarations
// Filter out import declarations
const body = listParent.get("body");
const lastImportIndex = body.findIndex(
(path) => !path.isImportDeclaration()
);
if (lastImportIndex === 0 || lastImportIndex === -1) {
// No non-import declarations, so we can safely unshift everything
return registerPaths(listParent.unshiftContainer("body", nodes));
} else {
// Insert the nodes after the last import declaration
return registerPaths(body[lastImportIndex - 1].insertAfter(nodes));
}
}
if (listParent.isFunction()) {
var body = listParent.get("body");
if (listParent.isArrowFunctionExpression() && listParent.node.expression) {
if (!body.isBlockStatement()) {
body = body.replaceWith(
t.blockStatement([t.returnStatement(body.node as t.Expression)])
)[0];
}
}
ok(body.isBlockStatement());
return registerPaths(body.unshiftContainer("body", nodes));
}
if (listParent.isBlock()) {
return registerPaths(listParent.unshiftContainer("body", nodes));
} else if (listParent.isSwitchCase()) {
return registerPaths(listParent.unshiftContainer("consequent", nodes));
}
ok(false);
}
export function prependProgram(
path: NodePath,
...nodes: (t.Statement | t.Statement[])[]
) {
var program = path.find((p) => p.isProgram());
ok(program);
return prepend(program, ...nodes);
}
/**
* A referenced or binding identifier, only names that reflect variables.
*
* - Excludes labels
*
* @param path
* @returns
*/
export function isVariableIdentifier(path: NodePath<t.Identifier>) {
if (
!path.isReferencedIdentifier() &&
!(path as NodePath).isBindingIdentifier()
)
return false;
// abc: {} // not a variable identifier
if (path.key === "label" && path.parentPath?.isLabeledStatement())
return false;
return true;
}
/**
* Subset of BindingIdentifier, excluding non-defined assignment expressions.
*
* @example
* var a = 1; // true
* var {c} = {} // true
* function b() {} // true
* function d([e] = [], ...f) {} // true
*
* f = 0; // false
* f(); // false
* @param path
* @returns
*/
export function isDefiningIdentifier(path: NodePath<t.Identifier>) {
if (path.key === "id" && path.parentPath.isFunction()) return true;
if (path.key === "id" && path.parentPath.isClassDeclaration) return true;
if (
path.key === "local" &&
(path.parentPath.isImportSpecifier() ||
path.parentPath.isImportDefaultSpecifier() ||
path.parentPath.isImportNamespaceSpecifier())
)
return true;
var maxTraversalPath = path.find(
(p) =>
(p.key === "id" && p.parentPath?.isVariableDeclarator()) ||
(p.listKey === "params" && p.parentPath?.isFunction()) ||
(p.key === "param" && p.parentPath?.isCatchClause())
);
if (!maxTraversalPath) return false;
var cursor: NodePath = path;
while (cursor && cursor !== maxTraversalPath) {
if (
cursor.parentPath.isObjectProperty() &&
cursor.parentPath.parentPath?.isObjectPattern()
) {
if (cursor.key !== "value") {
return false;
}
} else if (cursor.parentPath.isArrayPattern()) {
if (cursor.listKey !== "elements") {
return false;
}
} else if (cursor.parentPath.isRestElement()) {
if (cursor.key !== "argument") {
return false;
}
} else if (cursor.parentPath.isAssignmentPattern()) {
if (cursor.key !== "left") {
return false;
}
} else if (cursor.parentPath.isObjectPattern()) {
} else return false;
cursor = cursor.parentPath;
}
return true;
}
/**
* @example
* function id() {} // true
* class id {} // true
* var id; // false
* @param path
* @returns
*/
export function isStrictIdentifier(path: NodePath): boolean {
if (
path.key === "id" &&
(path.parentPath.isFunction() || path.parentPath.isClass())
)
return true;
return false;
}
export function isExportedIdentifier(path: NodePath<t.Identifier>) {
// Check if the identifier is directly inside an ExportNamedDeclaration
if (path.parentPath.isExportNamedDeclaration()) {
return true;
}
// Check if the identifier is in an ExportDefaultDeclaration
if (path.parentPath.isExportDefaultDeclaration()) {
return true;
}
// Check if the identifier is within an ExportSpecifier
if (
path.parentPath.isExportSpecifier() &&
path.parentPath.parentPath.isExportNamedDeclaration()
) {
return true;
}
// Check if it's part of an exported variable declaration (e.g., export const a = 1;)
if (
path.parentPath.isVariableDeclarator() &&
path.parentPath.parentPath.parentPath.isExportNamedDeclaration()
) {
return true;
}
// Check if it's part of an exported function declaration (e.g., export function abc() {})
if (
(path.parentPath.isFunctionDeclaration() ||
path.parentPath.isClassDeclaration()) &&
path.parentPath.parentPath.isExportNamedDeclaration()
) {
return true;
}
return false;
}
/**
* @example
* function abc() {
* "use strict";
* } // true
* @param path
* @returns
*/
export function isStrictMode(path: NodePath) {
// Classes are always in strict mode
if (path.isClass()) return true;
if (path.isBlock()) {
if (path.isTSModuleBlock()) return false;
return (path.node as t.BlockStatement | t.Program).directives.some(
(directive) => directive.value.value === "use strict"
);
}
if (path.isFunction()) {
const fnBody = path.get("body");
if (fnBody.isBlock()) {
return isStrictMode(fnBody);
}
}
return false;
}
/**
* A modified identifier is an identifier that is assigned to or updated.
*
* - Assignment Expression
* - Update Expression
*
* @param identifierPath
*/
export function isModifiedIdentifier(identifierPath: NodePath<t.Identifier>) {
var isModification = false;
if (identifierPath.parentPath.isUpdateExpression()) {
isModification = true;
}
if (
identifierPath.find(
(p) => p.key === "left" && p.parentPath?.isAssignmentExpression()
)
) {
isModification = true;
}
return isModification;
}
export function replaceDefiningIdentifierToMemberExpression(
path: NodePath<t.Identifier>,
memberExpression: t.MemberExpression
) {
// function id(){} -> var id = function() {}
if (path.key === "id" && path.parentPath.isFunctionDeclaration()) {
var asFunctionExpression = deepClone(
path.parentPath.node
) as t.Node as t.FunctionExpression;
asFunctionExpression.type = "FunctionExpression";
path.parentPath.replaceWith(
t.expressionStatement(
t.assignmentExpression("=", memberExpression, asFunctionExpression)
)
);
return;
}
// class id{} -> var id = class {}
if (path.key === "id" && path.parentPath.isClassDeclaration()) {
var asClassExpression = deepClone(
path.parentPath.node
) as t.Node as t.ClassExpression;
asClassExpression.type = "ClassExpression";
path.parentPath.replaceWith(
t.expressionStatement(
t.assignmentExpression("=", memberExpression, asClassExpression)
)
);
return;
}
// var id = 1 -> id = 1
var variableDeclaratorChild = path.find(
(p) =>
p.key === "id" &&
p.parentPath?.isVariableDeclarator() &&
p.parentPath?.parentPath?.isVariableDeclaration()
) as NodePath<t.VariableDeclarator["id"]>;
if (variableDeclaratorChild) {
var variableDeclarator =
variableDeclaratorChild.parentPath as NodePath<t.VariableDeclarator>;
var variableDeclaration =
variableDeclarator.parentPath as NodePath<t.VariableDeclaration>;
if (variableDeclaration.type === "VariableDeclaration") {
ok(
variableDeclaration.node.declarations.length === 1,
"Multiple declarations not supported"
);
}
const id = variableDeclarator.get("id");
const init = variableDeclarator.get("init");
var newExpression: t.Node = id.node;
var isForInitializer =
(variableDeclaration.key === "init" ||
variableDeclaration.key === "left") &&
variableDeclaration.parentPath.isFor();
if (init.node || !isForInitializer) {
newExpression = t.assignmentExpression(
"=",
id.node,
init.node || t.identifier("undefined")
);
}
if (!isForInitializer) {
newExpression = t.expressionStatement(newExpression as t.Expression);
}
path.replaceWith(memberExpression);
if (variableDeclaration.isVariableDeclaration()) {
variableDeclaration.replaceWith(newExpression);
}
return;
}
// Safely replace the identifier with the member expression
// ensureComputedExpression(path);
// path.replaceWith(memberExpression);
}
/**
* @example
* undefined // true
* void 0 // true
*/
export function isUndefined(path: NodePath) {
if (path.isIdentifier() && path.node.name === "undefined") {
return true;
}
if (
path.isUnaryExpression() &&
path.node.operator === "void" &&
path.node.argument.type === "NumericLiteral" &&
path.node.argument.value === 0
) {
return true;
}
return false;
}