-
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
estree.ts
577 lines (507 loc) 路 17.2 KB
/
estree.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
import type { TokenType } from "../tokenizer/types";
import type Parser from "../parser";
import type { ExpressionErrors } from "../parser/util";
import type * as N from "../types";
import type { Node as NodeType, NodeBase, File } from "../types";
import type { Position } from "../util/location";
import { Errors } from "../parse-error";
import type { Undone } from "../parser/node";
import type { BindingTypes } from "../util/scopeflags";
const { defineProperty } = Object;
const toUnenumerable = (object: any, key: string) =>
defineProperty(object, key, { enumerable: false, value: object[key] });
function toESTreeLocation(node: any) {
node.loc.start && toUnenumerable(node.loc.start, "index");
node.loc.end && toUnenumerable(node.loc.end, "index");
return node;
}
export default (superClass: typeof Parser) =>
class ESTreeParserMixin extends superClass implements Parser {
parse(): File {
const file = toESTreeLocation(super.parse());
if (this.options.tokens) {
file.tokens = file.tokens.map(toESTreeLocation);
}
return file;
}
// @ts-expect-error ESTree plugin changes node types
parseRegExpLiteral({ pattern, flags }): N.EstreeRegExpLiteral {
let regex: RegExp | null = null;
try {
regex = new RegExp(pattern, flags);
} catch (e) {
// In environments that don't support these flags value will
// be null as the regex can't be represented natively.
}
const node = this.estreeParseLiteral<N.EstreeRegExpLiteral>(regex);
node.regex = { pattern, flags };
return node;
}
// @ts-expect-error ESTree plugin changes node types
parseBigIntLiteral(value: any): N.Node {
// https://github.com/estree/estree/blob/master/es2020.md#bigintliteral
let bigInt: BigInt | null;
try {
bigInt = BigInt(value);
} catch {
bigInt = null;
}
const node = this.estreeParseLiteral<N.EstreeBigIntLiteral>(bigInt);
node.bigint = String(node.value || value);
return node;
}
// @ts-expect-error ESTree plugin changes node types
parseDecimalLiteral(value: any): N.Node {
// https://github.com/estree/estree/blob/master/experimental/decimal.md
// todo: use BigDecimal when node supports it.
const decimal: null = null;
const node = this.estreeParseLiteral(decimal);
node.decimal = String(node.value || value);
return node;
}
estreeParseLiteral<T extends N.Node>(value: any) {
// @ts-expect-error ESTree plugin changes node types
return this.parseLiteral<T>(value, "Literal");
}
// @ts-expect-error ESTree plugin changes node types
parseStringLiteral(value: any): N.Node {
return this.estreeParseLiteral(value);
}
parseNumericLiteral(value: any): any {
return this.estreeParseLiteral(value);
}
// @ts-expect-error ESTree plugin changes node types
parseNullLiteral(): N.Node {
return this.estreeParseLiteral(null);
}
parseBooleanLiteral(value: boolean): N.BooleanLiteral {
return this.estreeParseLiteral(value);
}
// Cast a Directive to an ExpressionStatement. Mutates the input Directive.
directiveToStmt(directive: N.Directive): N.ExpressionStatement {
const expression = directive.value as any as N.EstreeLiteral;
delete directive.value;
expression.type = "Literal";
// @ts-expect-error N.EstreeLiteral.raw is not defined.
expression.raw = expression.extra.raw;
expression.value = expression.extra.expressionValue;
const stmt = directive as any as N.ExpressionStatement;
stmt.type = "ExpressionStatement";
stmt.expression = expression;
// @ts-expect-error N.ExpressionStatement.directive is not defined
stmt.directive = expression.extra.rawValue;
delete expression.extra;
return stmt;
}
// ==================================
// Overrides
// ==================================
initFunction(node: N.BodilessFunctionOrMethodBase, isAsync: boolean): void {
super.initFunction(node, isAsync);
node.expression = false;
}
checkDeclaration(node: N.Pattern | N.ObjectProperty): void {
if (node != null && this.isObjectProperty(node)) {
// @ts-expect-error plugin typings
this.checkDeclaration((node as unknown as N.EstreeProperty).value);
} else {
super.checkDeclaration(node);
}
}
getObjectOrClassMethodParams(method: N.ObjectMethod | N.ClassMethod) {
return (method as any as N.EstreeProperty | N.EstreeMethodDefinition)
.value.params;
}
isValidDirective(stmt: N.Statement): boolean {
return (
stmt.type === "ExpressionStatement" &&
stmt.expression.type === "Literal" &&
typeof stmt.expression.value === "string" &&
!stmt.expression.extra?.parenthesized
);
}
parseBlockBody(
node: N.BlockStatementLike,
allowDirectives: boolean | undefined | null,
topLevel: boolean,
end: TokenType,
afterBlockParse?: (hasStrictModeDirective: boolean) => void,
): void {
super.parseBlockBody(
node,
allowDirectives,
topLevel,
end,
afterBlockParse,
);
const directiveStatements = node.directives.map(d =>
this.directiveToStmt(d),
);
// @ts-expect-error estree plugin typings
node.body = directiveStatements.concat(node.body);
delete node.directives;
}
pushClassMethod(
classBody: N.ClassBody,
method: N.ClassMethod,
isGenerator: boolean,
isAsync: boolean,
isConstructor: boolean,
allowsDirectSuper: boolean,
): void {
this.parseMethod(
method,
isGenerator,
isAsync,
isConstructor,
allowsDirectSuper,
"ClassMethod",
true,
);
if (method.typeParameters) {
// @ts-expect-error mutate AST types
method.value.typeParameters = method.typeParameters;
delete method.typeParameters;
}
classBody.body.push(method);
}
parsePrivateName(): any {
const node = super.parsePrivateName();
if (!process.env.BABEL_8_BREAKING) {
if (!this.getPluginOption("estree", "classFeatures")) {
return node;
}
}
return this.convertPrivateNameToPrivateIdentifier(node);
}
convertPrivateNameToPrivateIdentifier(
node: N.PrivateName,
): N.EstreePrivateIdentifier {
const name = super.getPrivateNameSV(node);
node = node as any;
delete node.id;
// @ts-expect-error mutate AST types
node.name = name;
// @ts-expect-error mutate AST types
node.type = "PrivateIdentifier";
return node as unknown as N.EstreePrivateIdentifier;
}
isPrivateName(node: N.Node): boolean {
if (!process.env.BABEL_8_BREAKING) {
if (!this.getPluginOption("estree", "classFeatures")) {
return super.isPrivateName(node);
}
}
return node.type === "PrivateIdentifier";
}
getPrivateNameSV(node: N.Node): string {
if (!process.env.BABEL_8_BREAKING) {
if (!this.getPluginOption("estree", "classFeatures")) {
return super.getPrivateNameSV(node);
}
}
return node.name;
}
// @ts-expect-error plugin may override interfaces
parseLiteral<T extends N.Literal>(value: any, type: T["type"]): T {
const node = super.parseLiteral<T>(value, type);
// @ts-expect-error mutating AST types
node.raw = node.extra.raw;
delete node.extra;
return node;
}
parseFunctionBody(
node: N.Function,
allowExpression?: boolean | null,
isMethod: boolean = false,
): void {
super.parseFunctionBody(node, allowExpression, isMethod);
node.expression = node.body.type !== "BlockStatement";
}
// @ts-expect-error plugin may override interfaces
parseMethod<
T extends N.ClassPrivateMethod | N.ObjectMethod | N.ClassMethod,
>(
node: Undone<T>,
isGenerator: boolean,
isAsync: boolean,
isConstructor: boolean,
allowDirectSuper: boolean,
type: T["type"],
inClassScope: boolean = false,
): N.EstreeMethodDefinition {
let funcNode = this.startNode<N.MethodLike>();
funcNode.kind = node.kind; // provide kind, so super method correctly sets state
funcNode = super.parseMethod(
// @ts-expect-error todo(flow->ts)
funcNode,
isGenerator,
isAsync,
isConstructor,
allowDirectSuper,
type,
inClassScope,
);
// @ts-expect-error mutate AST types
funcNode.type = "FunctionExpression";
delete funcNode.kind;
// @ts-expect-error mutate AST types
node.value = funcNode;
if (type === "ClassPrivateMethod") {
node.computed = false;
}
return this.finishNode(
// @ts-expect-error cast methods to estree types
node as Undone<N.EstreeMethodDefinition>,
"MethodDefinition",
);
}
parseClassProperty(...args: [N.ClassProperty]): any {
const propertyNode = super.parseClassProperty(...args) as any;
if (!process.env.BABEL_8_BREAKING) {
if (!this.getPluginOption("estree", "classFeatures")) {
return propertyNode as N.EstreePropertyDefinition;
}
}
propertyNode.type = "PropertyDefinition";
return propertyNode as N.EstreePropertyDefinition;
}
parseClassPrivateProperty(...args: [N.ClassPrivateProperty]): any {
const propertyNode = super.parseClassPrivateProperty(...args) as any;
if (!process.env.BABEL_8_BREAKING) {
if (!this.getPluginOption("estree", "classFeatures")) {
return propertyNode as N.EstreePropertyDefinition;
}
}
propertyNode.type = "PropertyDefinition";
propertyNode.computed = false;
return propertyNode as N.EstreePropertyDefinition;
}
parseObjectMethod(
prop: N.ObjectMethod,
isGenerator: boolean,
isAsync: boolean,
isPattern: boolean,
isAccessor: boolean,
): N.ObjectMethod | undefined | null {
const node: N.EstreeProperty = super.parseObjectMethod(
prop,
isGenerator,
isAsync,
isPattern,
isAccessor,
) as any;
if (node) {
node.type = "Property";
if ((node as any as N.ClassMethod).kind === "method") {
node.kind = "init";
}
node.shorthand = false;
}
return node as any;
}
parseObjectProperty(
prop: N.ObjectProperty,
startLoc: Position | undefined | null,
isPattern: boolean,
refExpressionErrors?: ExpressionErrors | null,
): N.ObjectProperty | undefined | null {
const node: N.EstreeProperty = super.parseObjectProperty(
prop,
startLoc,
isPattern,
refExpressionErrors,
) as any;
if (node) {
node.kind = "init";
node.type = "Property";
}
return node as any;
}
isValidLVal(
type: string,
isUnparenthesizedInAssign: boolean,
binding: BindingTypes,
) {
return type === "Property"
? "value"
: super.isValidLVal(type, isUnparenthesizedInAssign, binding);
}
isAssignable(node: N.Node, isBinding?: boolean): boolean {
if (node != null && this.isObjectProperty(node)) {
return this.isAssignable(node.value, isBinding);
}
return super.isAssignable(node, isBinding);
}
toAssignable(node: N.Node, isLHS: boolean = false): void {
if (node != null && this.isObjectProperty(node)) {
const { key, value } = node;
if (this.isPrivateName(key)) {
this.classScope.usePrivateName(
this.getPrivateNameSV(key),
key.loc.start,
);
}
this.toAssignable(value, isLHS);
} else {
super.toAssignable(node, isLHS);
}
}
toAssignableObjectExpressionProp(
prop: N.Node,
isLast: boolean,
isLHS: boolean,
) {
if (prop.kind === "get" || prop.kind === "set") {
this.raise(Errors.PatternHasAccessor, { at: prop.key });
} else if (prop.method) {
this.raise(Errors.PatternHasMethod, { at: prop.key });
} else {
super.toAssignableObjectExpressionProp(prop, isLast, isLHS);
}
}
finishCallExpression<T extends N.CallExpression | N.OptionalCallExpression>(
unfinished: Undone<T>,
optional: boolean,
): T {
const node = super.finishCallExpression(unfinished, optional);
if (node.callee.type === "Import") {
(node as N.Node as N.EstreeImportExpression).type = "ImportExpression";
(node as N.Node as N.EstreeImportExpression).source = node.arguments[0];
if (
this.hasPlugin("importAttributes") ||
this.hasPlugin("importAssertions")
) {
(node as N.Node as N.EstreeImportExpression).options =
node.arguments[1] ?? null;
// compatibility with previous ESTree AST
(node as N.Node as N.EstreeImportExpression).attributes =
node.arguments[1] ?? null;
}
// arguments isn't optional in the type definition
delete node.arguments;
// callee isn't optional in the type definition
delete node.callee;
}
return node;
}
toReferencedArguments(
node:
| N.CallExpression
| N.OptionalCallExpression
| N.EstreeImportExpression,
/* isParenthesizedExpr?: boolean, */
) {
// ImportExpressions do not have an arguments array.
if (node.type === "ImportExpression") {
return;
}
super.toReferencedArguments(node);
}
parseExport(
unfinished: Undone<N.AnyExport>,
decorators: N.Decorator[] | null,
) {
const exportStartLoc = this.state.lastTokStartLoc;
const node = super.parseExport(unfinished, decorators);
switch (node.type) {
case "ExportAllDeclaration":
// @ts-expect-error mutating AST types
node.exported = null;
break;
case "ExportNamedDeclaration":
if (
node.specifiers.length === 1 &&
// @ts-expect-error mutating AST types
node.specifiers[0].type === "ExportNamespaceSpecifier"
) {
// @ts-expect-error mutating AST types
node.type = "ExportAllDeclaration";
// @ts-expect-error mutating AST types
node.exported = node.specifiers[0].exported;
delete node.specifiers;
}
// fallthrough
case "ExportDefaultDeclaration":
{
const { declaration } = node;
if (
declaration?.type === "ClassDeclaration" &&
declaration.decorators?.length > 0 &&
// decorator comes before export
declaration.start === node.start
) {
this.resetStartLocation(
node,
// For compatibility with ESLint's keyword-spacing rule, which assumes that an
// export declaration must start with export.
// https://github.com/babel/babel/issues/15085
// Here we reset export declaration's start to be the start of the export token
exportStartLoc,
);
}
}
break;
}
return node;
}
parseSubscript(
base: N.Expression,
startLoc: Position,
noCalls: boolean | undefined | null,
state: N.ParseSubscriptState,
) {
const node = super.parseSubscript(base, startLoc, noCalls, state);
if (state.optionalChainMember) {
// https://github.com/estree/estree/blob/master/es2020.md#chainexpression
if (
node.type === "OptionalMemberExpression" ||
node.type === "OptionalCallExpression"
) {
node.type = node.type.substring(8); // strip Optional prefix
}
if (state.stop) {
const chain = this.startNodeAtNode(node);
chain.expression = node;
return this.finishNode(chain, "ChainExpression");
}
} else if (
node.type === "MemberExpression" ||
node.type === "CallExpression"
) {
node.optional = false;
}
return node;
}
hasPropertyAsPrivateName(node: N.Node): boolean {
if (node.type === "ChainExpression") {
node = node.expression;
}
return super.hasPropertyAsPrivateName(node);
}
// @ts-expect-error override interfaces
isObjectProperty(node: N.Node): boolean {
return node.type === "Property" && node.kind === "init" && !node.method;
}
isObjectMethod(node: N.Node): boolean {
return node.method || node.kind === "get" || node.kind === "set";
}
finishNodeAt<T extends NodeType>(
node: Undone<T>,
type: T["type"],
endLoc: Position,
): T {
return toESTreeLocation(super.finishNodeAt(node, type, endLoc));
}
resetStartLocation(node: N.Node, startLoc: Position) {
super.resetStartLocation(node, startLoc);
toESTreeLocation(node);
}
resetEndLocation(
node: NodeBase,
endLoc: Position = this.state.lastTokEndLoc,
): void {
super.resetEndLocation(node, endLoc);
toESTreeLocation(node);
}
};