-
Notifications
You must be signed in to change notification settings - Fork 138
/
expression.ts
991 lines (886 loc) · 27.9 KB
/
expression.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
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
/* eslint max-len: 0 */
// A recursive descent parser operates by defining functions for all
// syntactic elements, and recursively calling those, each function
// advancing the input stream and returning an AST node. Precedence
// of constructs (for example, the fact that `!x[1]` means `!(x[1])`
// instead of `(!x)[1]` is handled by the fact that the parser
// function that parses unary prefix operators is called first, and
// in turn calls the function that parses `[]` subscripts — that
// way, it'll receive the node for `x[1]` already parsed, and wraps
// *that* in the unary operator node.
//
// Acorn uses an [operator precedence parser][opp] to handle binary
// operator precedence, because it is much more compact than using
// the technique outlined above, which uses different, nesting
// functions to specify precedence, for all of the ten binary
// precedence levels that JavaScript defines.
//
// [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser
import {
flowParseArrow,
flowParseFunctionBodyAndFinish,
flowParseMaybeAssign,
flowParseSubscript,
flowParseSubscripts,
flowParseVariance,
flowStartParseAsyncArrowFromCallExpression,
flowStartParseNewArguments,
flowStartParseObjPropValue,
} from "../plugins/flow";
import {jsxParseElement} from "../plugins/jsx/index";
import {typedParseConditional, typedParseParenItem} from "../plugins/types";
import {
tsParseArrow,
tsParseFunctionBodyAndFinish,
tsParseMaybeAssign,
tsParseSubscript,
tsParseType,
tsParseTypeAssertion,
tsStartParseAsyncArrowFromCallExpression,
tsStartParseNewArguments,
tsStartParseObjPropValue,
} from "../plugins/typescript";
import {
eat,
IdentifierRole,
lookaheadCharCode,
lookaheadType,
match,
next,
nextTemplateToken,
popTypeContext,
pushTypeContext,
retokenizeSlashAsRegex,
} from "../tokenizer/index";
import {ContextualKeyword} from "../tokenizer/keywords";
import {Scope} from "../tokenizer/state";
import {TokenType, TokenType as tt} from "../tokenizer/types";
import {charCodes} from "../util/charcodes";
import {IS_IDENTIFIER_START} from "../util/identifier";
import {getNextContextId, isFlowEnabled, isJSXEnabled, isTypeScriptEnabled, state} from "./base";
import {
markPriorBindingIdentifier,
parseBindingIdentifier,
parseMaybeDefault,
parseRest,
parseSpread,
} from "./lval";
import {
parseBlock,
parseClass,
parseDecorators,
parseFunction,
parseFunctionParams,
} from "./statement";
import {
canInsertSemicolon,
eatContextual,
expect,
hasPrecedingLineBreak,
isContextual,
unexpected,
} from "./util";
export class StopState {
stop: boolean;
constructor(stop: boolean) {
this.stop = stop;
}
}
// ### Expression parsing
// These nest, from the most general expression type at the top to
// 'atomic', nondivisible expression types at the bottom. Most of
// the functions will simply let the function (s) below them parse,
// and, *if* the syntactic construct they handle is present, wrap
// the AST node that the inner parser gave them in another node.
export function parseExpression(noIn: boolean = false): void {
parseMaybeAssign(noIn);
if (match(tt.comma)) {
while (eat(tt.comma)) {
parseMaybeAssign(noIn);
}
}
}
/**
* noIn is used when parsing a for loop so that we don't interpret a following "in" as the binary
* operatior.
* isWithinParens is used to indicate that we're parsing something that might be a comma expression
* or might be an arrow function or might be a Flow type assertion (which requires explicit parens).
* In these cases, we should allow : and ?: after the initial "left" part.
*/
export function parseMaybeAssign(noIn: boolean = false, isWithinParens: boolean = false): boolean {
if (isTypeScriptEnabled) {
return tsParseMaybeAssign(noIn, isWithinParens);
} else if (isFlowEnabled) {
return flowParseMaybeAssign(noIn, isWithinParens);
} else {
return baseParseMaybeAssign(noIn, isWithinParens);
}
}
// Parse an assignment expression. This includes applications of
// operators like `+=`.
// Returns true if the expression was an arrow function.
export function baseParseMaybeAssign(noIn: boolean, isWithinParens: boolean): boolean {
if (match(tt._yield)) {
parseYield();
return false;
}
if (match(tt.parenL) || match(tt.name) || match(tt._yield)) {
state.potentialArrowAt = state.start;
}
const wasArrow = parseMaybeConditional(noIn);
if (isWithinParens) {
parseParenItem();
}
if (state.type & TokenType.IS_ASSIGN) {
next();
parseMaybeAssign(noIn);
return false;
}
return wasArrow;
}
// Parse a ternary conditional (`?:`) operator.
// Returns true if the expression was an arrow function.
function parseMaybeConditional(noIn: boolean): boolean {
const wasArrow = parseExprOps(noIn);
if (wasArrow) {
return true;
}
parseConditional(noIn);
return false;
}
function parseConditional(noIn: boolean): void {
if (isTypeScriptEnabled || isFlowEnabled) {
typedParseConditional(noIn);
} else {
baseParseConditional(noIn);
}
}
export function baseParseConditional(noIn: boolean): void {
if (eat(tt.question)) {
parseMaybeAssign();
expect(tt.colon);
parseMaybeAssign(noIn);
}
}
// Start the precedence parser.
// Returns true if this was an arrow function
function parseExprOps(noIn: boolean): boolean {
const startTokenIndex = state.tokens.length;
const wasArrow = parseMaybeUnary();
if (wasArrow) {
return true;
}
parseExprOp(startTokenIndex, -1, noIn);
return false;
}
// Parse binary operators with the operator precedence parsing
// algorithm. `left` is the left-hand side of the operator.
// `minPrec` provides context that allows the function to stop and
// defer further parser to one of its callers when it encounters an
// operator that has a lower precedence than the set it is parsing.
function parseExprOp(startTokenIndex: number, minPrec: number, noIn: boolean): void {
if (
isTypeScriptEnabled &&
(tt._in & TokenType.PRECEDENCE_MASK) > minPrec &&
!hasPrecedingLineBreak() &&
eatContextual(ContextualKeyword._as)
) {
state.tokens[state.tokens.length - 1].type = tt._as;
const oldIsType = pushTypeContext(1);
tsParseType();
popTypeContext(oldIsType);
parseExprOp(startTokenIndex, minPrec, noIn);
return;
}
const prec = state.type & TokenType.PRECEDENCE_MASK;
if (prec > 0 && (!noIn || !match(tt._in))) {
if (prec > minPrec) {
const op = state.type;
next();
if (op === tt.nullishCoalescing) {
state.tokens[state.tokens.length - 1].nullishStartIndex = startTokenIndex;
}
const rhsStartTokenIndex = state.tokens.length;
parseMaybeUnary();
// Extend the right operand of this operator if possible.
parseExprOp(rhsStartTokenIndex, op & TokenType.IS_RIGHT_ASSOCIATIVE ? prec - 1 : prec, noIn);
if (op === tt.nullishCoalescing) {
state.tokens[startTokenIndex].numNullishCoalesceStarts++;
state.tokens[state.tokens.length - 1].numNullishCoalesceEnds++;
}
// Continue with any future operator holding this expression as the left operand.
parseExprOp(startTokenIndex, minPrec, noIn);
}
}
}
// Parse unary operators, both prefix and postfix.
// Returns true if this was an arrow function.
export function parseMaybeUnary(): boolean {
if (isTypeScriptEnabled && !isJSXEnabled && eat(tt.lessThan)) {
tsParseTypeAssertion();
return false;
}
if (state.type & TokenType.IS_PREFIX) {
next();
parseMaybeUnary();
return false;
}
const wasArrow = parseExprSubscripts();
if (wasArrow) {
return true;
}
while (state.type & TokenType.IS_POSTFIX && !canInsertSemicolon()) {
// The tokenizer calls everything a preincrement, so make it a postincrement when
// we see it in that context.
if (state.type === tt.preIncDec) {
state.type = tt.postIncDec;
}
next();
}
return false;
}
// Parse call, dot, and `[]`-subscript expressions.
// Returns true if this was an arrow function.
export function parseExprSubscripts(): boolean {
const startTokenIndex = state.tokens.length;
const wasArrow = parseExprAtom();
if (wasArrow) {
return true;
}
parseSubscripts(startTokenIndex);
// If there was any optional chain operation, the start token would be marked
// as such, so also mark the end now.
if (state.tokens.length > startTokenIndex && state.tokens[startTokenIndex].isOptionalChainStart) {
state.tokens[state.tokens.length - 1].isOptionalChainEnd = true;
}
return false;
}
function parseSubscripts(startTokenIndex: number, noCalls: boolean = false): void {
if (isFlowEnabled) {
flowParseSubscripts(startTokenIndex, noCalls);
} else {
baseParseSubscripts(startTokenIndex, noCalls);
}
}
export function baseParseSubscripts(startTokenIndex: number, noCalls: boolean = false): void {
const stopState = new StopState(false);
do {
parseSubscript(startTokenIndex, noCalls, stopState);
} while (!stopState.stop && !state.error);
}
function parseSubscript(startTokenIndex: number, noCalls: boolean, stopState: StopState): void {
if (isTypeScriptEnabled) {
tsParseSubscript(startTokenIndex, noCalls, stopState);
} else if (isFlowEnabled) {
flowParseSubscript(startTokenIndex, noCalls, stopState);
} else {
baseParseSubscript(startTokenIndex, noCalls, stopState);
}
}
/** Set 'state.stop = true' to indicate that we should stop parsing subscripts. */
export function baseParseSubscript(
startTokenIndex: number,
noCalls: boolean,
stopState: StopState,
): void {
if (!noCalls && eat(tt.doubleColon)) {
parseNoCallExpr();
stopState.stop = true;
// Propagate startTokenIndex so that `a::b?.()` will keep `a` as the first token. We may want
// to revisit this in the future when fully supporting bind syntax.
parseSubscripts(startTokenIndex, noCalls);
} else if (match(tt.questionDot)) {
state.tokens[startTokenIndex].isOptionalChainStart = true;
if (noCalls && lookaheadType() === tt.parenL) {
stopState.stop = true;
return;
}
next();
state.tokens[state.tokens.length - 1].subscriptStartIndex = startTokenIndex;
if (eat(tt.bracketL)) {
parseExpression();
expect(tt.bracketR);
} else if (eat(tt.parenL)) {
parseCallExpressionArguments();
} else {
parseMaybePrivateName();
}
} else if (eat(tt.dot)) {
state.tokens[state.tokens.length - 1].subscriptStartIndex = startTokenIndex;
parseMaybePrivateName();
} else if (eat(tt.bracketL)) {
state.tokens[state.tokens.length - 1].subscriptStartIndex = startTokenIndex;
parseExpression();
expect(tt.bracketR);
} else if (!noCalls && match(tt.parenL)) {
if (atPossibleAsync()) {
// We see "async", but it's possible it's a usage of the name "async". Parse as if it's a
// function call, and if we see an arrow later, backtrack and re-parse as a parameter list.
const snapshot = state.snapshot();
const asyncStartTokenIndex = state.tokens.length;
next();
state.tokens[state.tokens.length - 1].subscriptStartIndex = startTokenIndex;
const callContextId = getNextContextId();
state.tokens[state.tokens.length - 1].contextId = callContextId;
parseCallExpressionArguments();
state.tokens[state.tokens.length - 1].contextId = callContextId;
if (shouldParseAsyncArrow()) {
// We hit an arrow, so backtrack and start again parsing function parameters.
state.restoreFromSnapshot(snapshot);
stopState.stop = true;
state.scopeDepth++;
parseFunctionParams();
parseAsyncArrowFromCallExpression(asyncStartTokenIndex);
}
} else {
next();
state.tokens[state.tokens.length - 1].subscriptStartIndex = startTokenIndex;
const callContextId = getNextContextId();
state.tokens[state.tokens.length - 1].contextId = callContextId;
parseCallExpressionArguments();
state.tokens[state.tokens.length - 1].contextId = callContextId;
}
} else if (match(tt.backQuote)) {
// Tagged template expression.
parseTemplate();
} else {
stopState.stop = true;
}
}
export function atPossibleAsync(): boolean {
// This was made less strict than the original version to avoid passing around nodes, but it
// should be safe to have rare false positives here.
return (
state.tokens[state.tokens.length - 1].contextualKeyword === ContextualKeyword._async &&
!canInsertSemicolon()
);
}
export function parseCallExpressionArguments(): void {
let first = true;
while (!eat(tt.parenR) && !state.error) {
if (first) {
first = false;
} else {
expect(tt.comma);
if (eat(tt.parenR)) {
break;
}
}
parseExprListItem(false);
}
}
function shouldParseAsyncArrow(): boolean {
return match(tt.colon) || match(tt.arrow);
}
function parseAsyncArrowFromCallExpression(startTokenIndex: number): void {
if (isTypeScriptEnabled) {
tsStartParseAsyncArrowFromCallExpression();
} else if (isFlowEnabled) {
flowStartParseAsyncArrowFromCallExpression();
}
expect(tt.arrow);
parseArrowExpression(startTokenIndex);
}
// Parse a no-call expression (like argument of `new` or `::` operators).
function parseNoCallExpr(): void {
const startTokenIndex = state.tokens.length;
parseExprAtom();
parseSubscripts(startTokenIndex, true);
}
// Parse an atomic expression — either a single token that is an
// expression, an expression started by a keyword like `function` or
// `new`, or an expression wrapped in punctuation like `()`, `[]`,
// or `{}`.
// Returns true if the parsed expression was an arrow function.
export function parseExprAtom(): boolean {
if (eat(tt.modulo)) {
// V8 intrinsic expression. Just parse the identifier, and the function invocation is parsed
// naturally.
parseIdentifier();
return false;
}
if (match(tt.jsxText)) {
parseLiteral();
return false;
} else if (match(tt.lessThan) && isJSXEnabled) {
state.type = tt.jsxTagStart;
jsxParseElement();
next();
return false;
}
const canBeArrow = state.potentialArrowAt === state.start;
switch (state.type) {
case tt.slash:
case tt.assign:
retokenizeSlashAsRegex();
// Fall through.
case tt._super:
case tt._this:
case tt.regexp:
case tt.num:
case tt.bigint:
case tt.decimal:
case tt.string:
case tt._null:
case tt._true:
case tt._false:
next();
return false;
case tt._import:
next();
if (match(tt.dot)) {
// import.meta
state.tokens[state.tokens.length - 1].type = tt.name;
next();
parseIdentifier();
}
return false;
case tt.name: {
const startTokenIndex = state.tokens.length;
const functionStart = state.start;
const contextualKeyword = state.contextualKeyword;
parseIdentifier();
if (contextualKeyword === ContextualKeyword._await) {
parseAwait();
return false;
} else if (
contextualKeyword === ContextualKeyword._async &&
match(tt._function) &&
!canInsertSemicolon()
) {
next();
parseFunction(functionStart, false);
return false;
} else if (
canBeArrow &&
!canInsertSemicolon() &&
contextualKeyword === ContextualKeyword._async &&
match(tt.name)
) {
state.scopeDepth++;
parseBindingIdentifier(false);
expect(tt.arrow);
// let foo = async bar => {};
parseArrowExpression(startTokenIndex);
return true;
}
if (canBeArrow && !canInsertSemicolon() && match(tt.arrow)) {
state.scopeDepth++;
markPriorBindingIdentifier(false);
expect(tt.arrow);
parseArrowExpression(startTokenIndex);
return true;
}
state.tokens[state.tokens.length - 1].identifierRole = IdentifierRole.Access;
return false;
}
case tt._do: {
next();
parseBlock();
return false;
}
case tt.parenL: {
const wasArrow = parseParenAndDistinguishExpression(canBeArrow);
return wasArrow;
}
case tt.bracketL:
next();
parseExprList(tt.bracketR, true);
return false;
case tt.braceL:
parseObj(false, false);
return false;
case tt._function:
parseFunctionExpression();
return false;
case tt.at:
parseDecorators();
// Fall through.
case tt._class:
parseClass(false);
return false;
case tt._new:
parseNew();
return false;
case tt.backQuote:
parseTemplate();
return false;
case tt.doubleColon: {
next();
parseNoCallExpr();
return false;
}
case tt.hash: {
const code = lookaheadCharCode();
if (IS_IDENTIFIER_START[code] || code === charCodes.backslash) {
parseMaybePrivateName();
} else {
next();
}
// Smart pipeline topic reference.
return false;
}
default:
unexpected();
return false;
}
}
function parseMaybePrivateName(): void {
eat(tt.hash);
parseIdentifier();
}
function parseFunctionExpression(): void {
const functionStart = state.start;
parseIdentifier();
if (eat(tt.dot)) {
// function.sent
parseIdentifier();
}
parseFunction(functionStart, false);
}
export function parseLiteral(): void {
next();
}
export function parseParenExpression(): void {
expect(tt.parenL);
parseExpression();
expect(tt.parenR);
}
// Returns true if this was an arrow expression.
function parseParenAndDistinguishExpression(canBeArrow: boolean): boolean {
// Assume this is a normal parenthesized expression, but if we see an arrow, we'll bail and
// start over as a parameter list.
const snapshot = state.snapshot();
const startTokenIndex = state.tokens.length;
expect(tt.parenL);
let first = true;
while (!match(tt.parenR) && !state.error) {
if (first) {
first = false;
} else {
expect(tt.comma);
if (match(tt.parenR)) {
break;
}
}
if (match(tt.ellipsis)) {
parseRest(false /* isBlockScope */);
parseParenItem();
break;
} else {
parseMaybeAssign(false, true);
}
}
expect(tt.parenR);
if (canBeArrow && shouldParseArrow()) {
const wasArrow = parseArrow();
if (wasArrow) {
// It was an arrow function this whole time, so start over and parse it as params so that we
// get proper token annotations.
state.restoreFromSnapshot(snapshot);
state.scopeDepth++;
// Don't specify a context ID because arrow functions don't need a context ID.
parseFunctionParams();
parseArrow();
parseArrowExpression(startTokenIndex);
return true;
}
}
return false;
}
function shouldParseArrow(): boolean {
return match(tt.colon) || !canInsertSemicolon();
}
// Returns whether there was an arrow token.
export function parseArrow(): boolean {
if (isTypeScriptEnabled) {
return tsParseArrow();
} else if (isFlowEnabled) {
return flowParseArrow();
} else {
return eat(tt.arrow);
}
}
function parseParenItem(): void {
if (isTypeScriptEnabled || isFlowEnabled) {
typedParseParenItem();
}
}
// New's precedence is slightly tricky. It must allow its argument to
// be a `[]` or dot subscript expression, but not a call — at least,
// not without wrapping it in parentheses. Thus, it uses the noCalls
// argument to parseSubscripts to prevent it from consuming the
// argument list.
function parseNew(): void {
expect(tt._new);
if (eat(tt.dot)) {
// new.target
parseIdentifier();
return;
}
parseNoCallExpr();
eat(tt.questionDot);
parseNewArguments();
}
function parseNewArguments(): void {
if (isTypeScriptEnabled) {
tsStartParseNewArguments();
} else if (isFlowEnabled) {
flowStartParseNewArguments();
}
if (eat(tt.parenL)) {
parseExprList(tt.parenR);
}
}
export function parseTemplate(): void {
// Finish `, read quasi
nextTemplateToken();
// Finish quasi, read ${
nextTemplateToken();
while (!match(tt.backQuote) && !state.error) {
expect(tt.dollarBraceL);
parseExpression();
// Finish }, read quasi
nextTemplateToken();
// Finish quasi, read either ${ or `
nextTemplateToken();
}
next();
}
// Parse an object literal or binding pattern.
export function parseObj(isPattern: boolean, isBlockScope: boolean): void {
// Attach a context ID to the object open and close brace and each object key.
const contextId = getNextContextId();
let first = true;
next();
state.tokens[state.tokens.length - 1].contextId = contextId;
while (!eat(tt.braceR) && !state.error) {
if (first) {
first = false;
} else {
expect(tt.comma);
if (eat(tt.braceR)) {
break;
}
}
let isGenerator = false;
if (match(tt.ellipsis)) {
const previousIndex = state.tokens.length;
parseSpread();
if (isPattern) {
// Mark role when the only thing being spread over is an identifier.
if (state.tokens.length === previousIndex + 2) {
markPriorBindingIdentifier(isBlockScope);
}
if (eat(tt.braceR)) {
break;
}
}
continue;
}
if (!isPattern) {
isGenerator = eat(tt.star);
}
if (!isPattern && isContextual(ContextualKeyword._async)) {
if (isGenerator) unexpected();
parseIdentifier();
if (
match(tt.colon) ||
match(tt.parenL) ||
match(tt.braceR) ||
match(tt.eq) ||
match(tt.comma)
) {
// This is a key called "async" rather than an async function.
} else {
if (match(tt.star)) {
next();
isGenerator = true;
}
parsePropertyName(contextId);
}
} else {
parsePropertyName(contextId);
}
parseObjPropValue(isPattern, isBlockScope, contextId);
}
state.tokens[state.tokens.length - 1].contextId = contextId;
}
function isGetterOrSetterMethod(isPattern: boolean): boolean {
// We go off of the next and don't bother checking if the node key is actually "get" or "set".
// This lets us avoid generating a node, and should only make the validation worse.
return (
!isPattern &&
(match(tt.string) || // get "string"() {}
match(tt.num) || // get 1() {}
match(tt.bracketL) || // get ["string"]() {}
match(tt.name) || // get foo() {}
!!(state.type & TokenType.IS_KEYWORD)) // get debugger() {}
);
}
// Returns true if this was a method.
function parseObjectMethod(isPattern: boolean, objectContextId: number): boolean {
// We don't need to worry about modifiers because object methods can't have optional bodies, so
// the start will never be used.
const functionStart = state.start;
if (match(tt.parenL)) {
if (isPattern) unexpected();
parseMethod(functionStart, /* isConstructor */ false);
return true;
}
if (isGetterOrSetterMethod(isPattern)) {
parsePropertyName(objectContextId);
parseMethod(functionStart, /* isConstructor */ false);
return true;
}
return false;
}
function parseObjectProperty(isPattern: boolean, isBlockScope: boolean): void {
if (eat(tt.colon)) {
if (isPattern) {
parseMaybeDefault(isBlockScope);
} else {
parseMaybeAssign(false);
}
return;
}
// Since there's no colon, we assume this is an object shorthand.
// If we're in a destructuring, we've now discovered that the key was actually an assignee, so
// we need to tag it as a declaration with the appropriate scope. Otherwise, we might need to
// transform it on access, so mark it as a normal object shorthand.
let identifierRole;
if (isPattern) {
if (state.scopeDepth === 0) {
identifierRole = IdentifierRole.ObjectShorthandTopLevelDeclaration;
} else if (isBlockScope) {
identifierRole = IdentifierRole.ObjectShorthandBlockScopedDeclaration;
} else {
identifierRole = IdentifierRole.ObjectShorthandFunctionScopedDeclaration;
}
} else {
identifierRole = IdentifierRole.ObjectShorthand;
}
state.tokens[state.tokens.length - 1].identifierRole = identifierRole;
// Regardless of whether we know this to be a pattern or if we're in an ambiguous context, allow
// parsing as if there's a default value.
parseMaybeDefault(isBlockScope, true);
}
function parseObjPropValue(
isPattern: boolean,
isBlockScope: boolean,
objectContextId: number,
): void {
if (isTypeScriptEnabled) {
tsStartParseObjPropValue();
} else if (isFlowEnabled) {
flowStartParseObjPropValue();
}
const wasMethod = parseObjectMethod(isPattern, objectContextId);
if (!wasMethod) {
parseObjectProperty(isPattern, isBlockScope);
}
}
export function parsePropertyName(objectContextId: number): void {
if (isFlowEnabled) {
flowParseVariance();
}
if (eat(tt.bracketL)) {
state.tokens[state.tokens.length - 1].contextId = objectContextId;
parseMaybeAssign();
expect(tt.bracketR);
state.tokens[state.tokens.length - 1].contextId = objectContextId;
} else {
if (match(tt.num) || match(tt.string) || match(tt.bigint) || match(tt.decimal)) {
parseExprAtom();
} else {
parseMaybePrivateName();
}
state.tokens[state.tokens.length - 1].identifierRole = IdentifierRole.ObjectKey;
state.tokens[state.tokens.length - 1].contextId = objectContextId;
}
}
// Parse object or class method.
export function parseMethod(functionStart: number, isConstructor: boolean): void {
const funcContextId = getNextContextId();
state.scopeDepth++;
const startTokenIndex = state.tokens.length;
const allowModifiers = isConstructor; // For TypeScript parameter properties
parseFunctionParams(allowModifiers, funcContextId);
parseFunctionBodyAndFinish(functionStart, funcContextId);
const endTokenIndex = state.tokens.length;
state.scopes.push(new Scope(startTokenIndex, endTokenIndex, true));
state.scopeDepth--;
}
// Parse arrow function expression.
// If the parameters are provided, they will be converted to an
// assignable list.
export function parseArrowExpression(startTokenIndex: number): void {
parseFunctionBody(true);
const endTokenIndex = state.tokens.length;
state.scopes.push(new Scope(startTokenIndex, endTokenIndex, true));
state.scopeDepth--;
}
export function parseFunctionBodyAndFinish(functionStart: number, funcContextId: number = 0): void {
if (isTypeScriptEnabled) {
tsParseFunctionBodyAndFinish(functionStart, funcContextId);
} else if (isFlowEnabled) {
flowParseFunctionBodyAndFinish(funcContextId);
} else {
parseFunctionBody(false, funcContextId);
}
}
export function parseFunctionBody(allowExpression: boolean, funcContextId: number = 0): void {
const isExpression = allowExpression && !match(tt.braceL);
if (isExpression) {
parseMaybeAssign();
} else {
parseBlock(true /* isFunctionScope */, funcContextId);
}
}
// Parses a comma-separated list of expressions, and returns them as
// an array. `close` is the token type that ends the list, and
// `allowEmpty` can be turned on to allow subsequent commas with
// nothing in between them to be parsed as `null` (which is needed
// for array literals).
function parseExprList(close: TokenType, allowEmpty: boolean = false): void {
let first = true;
while (!eat(close) && !state.error) {
if (first) {
first = false;
} else {
expect(tt.comma);
if (eat(close)) break;
}
parseExprListItem(allowEmpty);
}
}
function parseExprListItem(allowEmpty: boolean): void {
if (allowEmpty && match(tt.comma)) {
// Empty item; nothing more to parse for this item.
} else if (match(tt.ellipsis)) {
parseSpread();
parseParenItem();
} else if (match(tt.question)) {
// Partial function application proposal.
next();
} else {
parseMaybeAssign(false, true);
}
}
// Parse the next token as an identifier.
export function parseIdentifier(): void {
next();
state.tokens[state.tokens.length - 1].type = tt.name;
}
// Parses await expression inside async function.
function parseAwait(): void {
parseMaybeUnary();
}
// Parses yield expression inside generator.
function parseYield(): void {
next();
if (!match(tt.semi) && !canInsertSemicolon()) {
eat(tt.star);
parseMaybeAssign();
}
}