-
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
util.js
408 lines (354 loc) 路 11.5 KB
/
util.js
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
// @flow
import {
isTokenType,
tokenIsLiteralPropertyName,
tokenLabelName,
tt,
type TokenType,
} from "../tokenizer/types";
import Tokenizer from "../tokenizer";
import State from "../tokenizer/state";
import type { Node } from "../types";
import { lineBreak, skipWhiteSpaceToLineBreak } from "../util/whitespace";
import { isIdentifierChar } from "../util/identifier";
import ClassScopeHandler from "../util/class-scope";
import ExpressionScopeHandler from "../util/expression-scope";
import { SCOPE_PROGRAM } from "../util/scopeflags";
import ProductionParameterHandler, {
PARAM_AWAIT,
PARAM,
} from "../util/production-parameter";
import { Errors, type ErrorTemplate, ErrorCodes } from "./error";
import type { ParsingError } from "./error";
/*::
import type ScopeHandler from "../util/scope";
*/
type TryParse<Node, Error, Thrown, Aborted, FailState> = {
node: Node,
error: Error,
thrown: Thrown,
aborted: Aborted,
failState: FailState,
};
// ## Parser utilities
export default class UtilParser extends Tokenizer {
// Forward-declaration: defined in parser/index.js
/*::
+getScopeHandler: () => Class<ScopeHandler<*>>;
*/
// TODO
addExtra(node: Node, key: string, val: any): void {
if (!node) return;
const extra = (node.extra = node.extra || {});
extra[key] = val;
}
// Tests whether parsed token is a contextual keyword.
isContextual(token: TokenType): boolean {
return this.state.type === token && !this.state.containsEsc;
}
isUnparsedContextual(nameStart: number, name: string): boolean {
const nameEnd = nameStart + name.length;
if (this.input.slice(nameStart, nameEnd) === name) {
const nextCh = this.input.charCodeAt(nameEnd);
return !(
isIdentifierChar(nextCh) ||
// check if `nextCh is between 0xd800 - 0xdbff,
// if `nextCh` is NaN, `NaN & 0xfc00` is 0, the function
// returns true
(nextCh & 0xfc00) === 0xd800
);
}
return false;
}
isLookaheadContextual(name: string): boolean {
const next = this.nextTokenStart();
return this.isUnparsedContextual(next, name);
}
// Consumes contextual keyword if possible.
eatContextual(token: TokenType): boolean {
if (this.isContextual(token)) {
this.next();
return true;
}
return false;
}
// Asserts that following token is given contextual keyword.
expectContextual(token: TokenType, template?: ErrorTemplate): void {
if (!this.eatContextual(token)) this.unexpected(null, template);
}
// Test whether a semicolon can be inserted at the current position.
canInsertSemicolon(): boolean {
return (
this.match(tt.eof) ||
this.match(tt.braceR) ||
this.hasPrecedingLineBreak()
);
}
hasPrecedingLineBreak(): boolean {
return lineBreak.test(
this.input.slice(this.state.lastTokEnd, this.state.start),
);
}
hasFollowingLineBreak(): boolean {
skipWhiteSpaceToLineBreak.lastIndex = this.state.end;
return skipWhiteSpaceToLineBreak.test(this.input);
}
// TODO
isLineTerminator(): boolean {
return this.eat(tt.semi) || this.canInsertSemicolon();
}
// Consume a semicolon, or, failing that, see if we are allowed to
// pretend that there is a semicolon at this position.
semicolon(allowAsi: boolean = true): void {
if (allowAsi ? this.isLineTerminator() : this.eat(tt.semi)) return;
this.raise(this.state.lastTokEnd, Errors.MissingSemicolon);
}
// Expect a token of a given type. If found, consume it, otherwise,
// raise an unexpected token error at given pos.
expect(type: TokenType, pos?: ?number): void {
this.eat(type) || this.unexpected(pos, type);
}
// Throws if the current token and the prev one are separated by a space.
assertNoSpace(message: string = "Unexpected space."): void {
if (this.state.start > this.state.lastTokEnd) {
/* eslint-disable @babel/development-internal/dry-error-messages */
this.raise(this.state.lastTokEnd, {
code: ErrorCodes.SyntaxError,
reasonCode: "UnexpectedSpace",
template: message,
});
/* eslint-enable @babel/development-internal/dry-error-messages */
}
}
// Raise an unexpected token error. Can take the expected token type
// instead of a message string.
unexpected(
pos: ?number,
messageOrType: ErrorTemplate | TokenType = {
code: ErrorCodes.SyntaxError,
reasonCode: "UnexpectedToken",
template: "Unexpected token",
},
): empty {
if (isTokenType(messageOrType)) {
messageOrType = {
code: ErrorCodes.SyntaxError,
reasonCode: "UnexpectedToken",
template: `Unexpected token, expected "${tokenLabelName(
// $FlowIgnore: Flow does not support assertion signature and TokenType is opaque
messageOrType,
)}"`,
};
}
/* eslint-disable @babel/development-internal/dry-error-messages */
// $FlowIgnore: Flow does not support assertion signature and TokenType is opaque
throw this.raise(pos != null ? pos : this.state.start, messageOrType);
/* eslint-enable @babel/development-internal/dry-error-messages */
}
expectPlugin(name: string, pos?: ?number): true {
if (!this.hasPlugin(name)) {
throw this.raiseWithData(
pos != null ? pos : this.state.start,
{ missingPlugin: [name] },
`This experimental syntax requires enabling the parser plugin: '${name}'`,
);
}
return true;
}
expectOnePlugin(names: Array<string>, pos?: ?number): void {
if (!names.some(n => this.hasPlugin(n))) {
throw this.raiseWithData(
pos != null ? pos : this.state.start,
{ missingPlugin: names },
`This experimental syntax requires enabling one of the following parser plugin(s): '${names.join(
", ",
)}'`,
);
}
}
// tryParse will clone parser state.
// It is expensive and should be used with cautions
tryParse<T: Node | $ReadOnlyArray<Node>>(
fn: (abort: (node?: T) => empty) => T,
oldState: State = this.state.clone(),
):
| TryParse<T, null, false, false, null>
| TryParse<T | null, ParsingError, boolean, false, State>
| TryParse<T | null, null, false, true, State> {
const abortSignal: { node: T | null } = { node: null };
try {
const node = fn((node = null) => {
abortSignal.node = node;
throw abortSignal;
});
if (this.state.errors.length > oldState.errors.length) {
const failState = this.state;
this.state = oldState;
// tokensLength should be preserved during error recovery mode
// since the parser does not halt and will instead parse the
// remaining tokens
this.state.tokensLength = failState.tokensLength;
return {
node,
error: (failState.errors[oldState.errors.length]: ParsingError),
thrown: false,
aborted: false,
failState,
};
}
return {
node,
error: null,
thrown: false,
aborted: false,
failState: null,
};
} catch (error) {
const failState = this.state;
this.state = oldState;
if (error instanceof SyntaxError) {
return { node: null, error, thrown: true, aborted: false, failState };
}
if (error === abortSignal) {
return {
node: abortSignal.node,
error: null,
thrown: false,
aborted: true,
failState,
};
}
throw error;
}
}
checkExpressionErrors(
refExpressionErrors: ?ExpressionErrors,
andThrow: boolean,
) {
if (!refExpressionErrors) return false;
const { shorthandAssign, doubleProto, optionalParameters } =
refExpressionErrors;
if (!andThrow) {
return (
shorthandAssign >= 0 || doubleProto >= 0 || optionalParameters >= 0
);
}
if (shorthandAssign >= 0) {
this.unexpected(shorthandAssign);
}
if (doubleProto >= 0) {
this.raise(doubleProto, Errors.DuplicateProto);
}
if (optionalParameters >= 0) {
this.unexpected(optionalParameters);
}
}
/**
* Test if current token is a literal property name
* https://tc39.es/ecma262/#prod-LiteralPropertyName
* LiteralPropertyName:
* IdentifierName
* StringLiteral
* NumericLiteral
* BigIntLiteral
*/
isLiteralPropertyName(): boolean {
return tokenIsLiteralPropertyName(this.state.type);
}
/*
* Test if given node is a PrivateName
* will be overridden in ESTree plugin
*/
isPrivateName(node: Node): boolean {
return node.type === "PrivateName";
}
/*
* Return the string value of a given private name
* WITHOUT `#`
* @see {@link https://tc39.es/proposal-class-fields/#sec-private-names-static-semantics-stringvalue}
*/
getPrivateNameSV(node: Node): string {
return node.id.name;
}
/*
* Return whether the given node is a member/optional chain that
* contains a private name as its property
* It is overridden in ESTree plugin
*/
hasPropertyAsPrivateName(node: Node): boolean {
return (
(node.type === "MemberExpression" ||
node.type === "OptionalMemberExpression") &&
this.isPrivateName(node.property)
);
}
isOptionalChain(node: Node): boolean {
return (
node.type === "OptionalMemberExpression" ||
node.type === "OptionalCallExpression"
);
}
isObjectProperty(node: Node): boolean {
return node.type === "ObjectProperty";
}
isObjectMethod(node: Node): boolean {
return node.type === "ObjectMethod";
}
initializeScopes(
inModule: boolean = this.options.sourceType === "module",
): () => void {
// Initialize state
const oldLabels = this.state.labels;
this.state.labels = [];
const oldExportedIdentifiers = this.exportedIdentifiers;
this.exportedIdentifiers = new Set();
// initialize scopes
const oldInModule = this.inModule;
this.inModule = inModule;
const oldScope = this.scope;
const ScopeHandler = this.getScopeHandler();
this.scope = new ScopeHandler(this.raise.bind(this), this.inModule);
const oldProdParam = this.prodParam;
this.prodParam = new ProductionParameterHandler();
const oldClassScope = this.classScope;
this.classScope = new ClassScopeHandler(this.raise.bind(this));
const oldExpressionScope = this.expressionScope;
this.expressionScope = new ExpressionScopeHandler(this.raise.bind(this));
return () => {
// Revert state
this.state.labels = oldLabels;
this.exportedIdentifiers = oldExportedIdentifiers;
// Revert scopes
this.inModule = oldInModule;
this.scope = oldScope;
this.prodParam = oldProdParam;
this.classScope = oldClassScope;
this.expressionScope = oldExpressionScope;
};
}
enterInitialScopes() {
let paramFlags = PARAM;
if (this.inModule) {
paramFlags |= PARAM_AWAIT;
}
this.scope.enter(SCOPE_PROGRAM);
this.prodParam.enter(paramFlags);
}
}
/**
* The ExpressionErrors is a context struct used to track ambiguous patterns
* When we are sure the parsed pattern is a RHS, which means it is not a pattern,
* we will throw on this position on invalid assign syntax, otherwise it will be reset to -1
*
* Types of ExpressionErrors:
*
* - **shorthandAssign**: track initializer `=` position
* - **doubleProto**: track the duplicate `__proto__` key position
* - **optionalParameters**: track the optional paramter (`?`).
* It's only used by typescript and flow plugins
*/
export class ExpressionErrors {
shorthandAssign = -1;
doubleProto = -1;
optionalParameters = -1;
}