-
Notifications
You must be signed in to change notification settings - Fork 784
/
parser.ts
3831 lines (3281 loc) · 142 KB
/
parser.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
992
993
994
995
996
997
998
999
1000
import { assert } from './assert';
import { ErrorHandler } from './error-handler';
import { Messages } from './messages';
import * as Node from './nodes';
import { Comment, RawToken, Scanner, SourceLocation } from './scanner';
import { Syntax } from './syntax';
import { Token, TokenName } from './token';
interface Config {
range: boolean;
loc: boolean;
source: string | null;
tokens: boolean;
comment: boolean;
tolerant: boolean;
}
interface Context {
isModule: boolean;
allowIn: boolean;
allowStrictDirective: boolean;
allowYield: boolean;
isAsync: boolean;
firstCoverInitializedNameError: RawToken | null;
isAssignmentTarget: boolean;
isBindingElement: boolean;
inFunctionBody: boolean;
inIteration: boolean;
inSwitch: boolean;
inClassConstructor: boolean;
labelSet: any;
strict: boolean;
}
export interface Marker {
index: number;
line: number;
column: number;
}
const ArrowParameterPlaceHolder = 'ArrowParameterPlaceHolder';
interface ArrowParameterPlaceHolderNode {
type: string;
params: Node.Expression[];
async: boolean;
}
interface DeclarationOptions {
inFor: boolean;
}
interface TokenEntry {
type: string;
value: string;
regex?: {
pattern: string;
flags: string;
};
range?: [number, number];
loc?: SourceLocation;
}
interface ParseTemplateLiteralOptions {
isTagged: boolean;
}
/* eslint-disable @typescript-eslint/unbound-method */
export class Parser {
readonly config: Config;
readonly delegate: any;
readonly errorHandler: ErrorHandler;
readonly scanner: Scanner;
readonly operatorPrecedence: any;
lookahead: RawToken;
hasLineTerminator: boolean;
context: Context;
tokens: any[];
startMarker: Marker;
lastMarker: Marker;
constructor(code: string, options: any = {}, delegate) {
this.config = {
range: (typeof options.range === 'boolean') && options.range,
loc: (typeof options.loc === 'boolean') && options.loc,
source: null,
tokens: (typeof options.tokens === 'boolean') && options.tokens,
comment: (typeof options.comment === 'boolean') && options.comment,
tolerant: (typeof options.tolerant === 'boolean') && options.tolerant
};
if (this.config.loc && options.source && options.source !== null) {
this.config.source = String(options.source);
}
this.delegate = delegate;
this.errorHandler = new ErrorHandler();
this.errorHandler.tolerant = this.config.tolerant;
this.scanner = new Scanner(code, this.errorHandler);
this.scanner.trackComment = this.config.comment;
this.operatorPrecedence = {
')': 0,
';': 0,
',': 0,
'=': 0,
']': 0,
'??': 5,
'||': 6,
'&&': 7,
'|': 8,
'^': 9,
'&': 10,
'==': 11,
'!=': 11,
'===': 11,
'!==': 11,
'<': 12,
'>': 12,
'<=': 12,
'>=': 12,
'<<': 13,
'>>': 13,
'>>>': 13,
'+': 14,
'-': 14,
'*': 15,
'/': 15,
'%': 15
};
this.lookahead = {
type: Token.EOF,
value: '',
lineNumber: this.scanner.lineNumber,
lineStart: 0,
start: 0,
end: 0
};
this.hasLineTerminator = false;
this.context = {
isModule: false,
isAsync: false,
allowIn: true,
allowStrictDirective: true,
allowYield: true,
firstCoverInitializedNameError: null,
isAssignmentTarget: false,
isBindingElement: false,
inFunctionBody: false,
inIteration: false,
inSwitch: false,
inClassConstructor: false,
labelSet: {},
strict: false
};
this.tokens = [];
this.startMarker = {
index: 0,
line: this.scanner.lineNumber,
column: 0
};
this.lastMarker = {
index: 0,
line: this.scanner.lineNumber,
column: 0
};
this.nextToken();
this.lastMarker = {
index: this.scanner.index,
line: this.scanner.lineNumber,
column: this.scanner.index - this.scanner.lineStart
};
}
throwError(messageFormat: string, ...values): void {
const args = values.slice();
const msg = messageFormat.replace(/%(\d)/g, (whole, idx) => {
assert(idx < args.length, 'Message reference must be in range');
return args[idx];
}
);
const index = this.lastMarker.index;
const line = this.lastMarker.line;
const column = this.lastMarker.column + 1;
throw this.errorHandler.createError(index, line, column, msg);
}
tolerateError(messageFormat, ...values) {
const args = values.slice();
const msg = messageFormat.replace(/%(\d)/g, (whole, idx) => {
assert(idx < args.length, 'Message reference must be in range');
return args[idx];
}
);
const index = this.lastMarker.index;
const line = this.scanner.lineNumber;
const column = this.lastMarker.column + 1;
this.errorHandler.tolerateError(index, line, column, msg);
}
// Throw an exception because of the token.
unexpectedTokenError(token?: any, message?: string): Error {
let msg = message || Messages.UnexpectedToken;
let value;
if (token) {
if (!message) {
msg = (token.type === Token.EOF) ? Messages.UnexpectedEOS :
(token.type === Token.Identifier) ? Messages.UnexpectedIdentifier :
(token.type === Token.NumericLiteral) ? Messages.UnexpectedNumber :
(token.type === Token.StringLiteral) ? Messages.UnexpectedString :
(token.type === Token.Template) ? Messages.UnexpectedTemplate :
Messages.UnexpectedToken;
if (token.type === Token.Keyword) {
if (this.scanner.isFutureReservedWord(token.value)) {
msg = Messages.UnexpectedReserved;
} else if (this.context.strict && this.scanner.isStrictModeReservedWord(token.value)) {
msg = Messages.StrictReservedWord;
}
}
}
value = token.value;
} else {
value = 'ILLEGAL';
}
msg = msg.replace('%0', value);
if (token && typeof token.lineNumber === 'number') {
const index = token.start;
const line = token.lineNumber;
const lastMarkerLineStart = this.lastMarker.index - this.lastMarker.column;
const column = token.start - lastMarkerLineStart + 1;
return this.errorHandler.createError(index, line, column, msg);
} else {
const index = this.lastMarker.index;
const line = this.lastMarker.line;
const column = this.lastMarker.column + 1;
return this.errorHandler.createError(index, line, column, msg);
}
}
throwUnexpectedToken(token?, message?): never {
throw this.unexpectedTokenError(token, message);
}
tolerateUnexpectedToken(token?, message?) {
this.errorHandler.tolerate(this.unexpectedTokenError(token, message));
}
tolerateInvalidLoopStatement() {
if (this.matchKeyword("class") || this.matchKeyword("function")) {
this.tolerateError(Messages.UnexpectedToken, this.lookahead);
}
}
collectComments() {
if (!this.config.comment) {
this.scanner.scanComments();
} else {
const comments: Comment[] = this.scanner.scanComments();
if (comments.length > 0 && this.delegate) {
for (let i = 0; i < comments.length; ++i) {
const e: Comment = comments[i];
const node: any = {
type: e.multiLine ? 'BlockComment' : 'LineComment',
value: this.scanner.source.slice(e.slice[0], e.slice[1])
};
if (this.config.range) {
node.range = e.range;
}
if (this.config.loc) {
node.loc = e.loc;
}
const metadata = {
start: {
line: e.loc.start.line,
column: e.loc.start.column,
offset: e.range[0]
},
end: {
line: e.loc.end.line,
column: e.loc.end.column,
offset: e.range[1]
}
};
this.delegate(node, metadata);
}
}
}
}
// From internal representation to an external structure
getTokenRaw(token): string {
return this.scanner.source.slice(token.start, token.end);
}
convertToken(token: RawToken): TokenEntry {
const t: TokenEntry = {
type: TokenName[token.type],
value: this.getTokenRaw(token)
};
if (this.config.range) {
t.range = [token.start, token.end];
}
if (this.config.loc) {
t.loc = {
start: {
line: this.startMarker.line,
column: this.startMarker.column
},
end: {
line: this.scanner.lineNumber,
column: this.scanner.index - this.scanner.lineStart
}
};
}
if (token.type === Token.RegularExpression) {
const pattern = token.pattern as string;
const flags = token.flags as string;
t.regex = { pattern, flags };
}
return t;
}
nextToken(): RawToken {
const token = this.lookahead;
this.lastMarker.index = this.scanner.index;
this.lastMarker.line = this.scanner.lineNumber;
this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
this.collectComments();
if (this.scanner.index !== this.startMarker.index) {
this.startMarker.index = this.scanner.index;
this.startMarker.line = this.scanner.lineNumber;
this.startMarker.column = this.scanner.index - this.scanner.lineStart;
}
const next = this.scanner.lex();
this.hasLineTerminator = (token.lineNumber !== next.lineNumber);
if (next && this.context.strict && next.type === Token.Identifier) {
if (this.scanner.isStrictModeReservedWord(next.value as string)) {
next.type = Token.Keyword;
}
}
this.lookahead = next;
if (this.config.tokens && next.type !== Token.EOF) {
this.tokens.push(this.convertToken(next));
}
return token;
}
nextRegexToken(): RawToken {
this.collectComments();
const token = this.scanner.scanRegExp();
if (this.config.tokens) {
// Pop the previous token, '/' or '/='
// This is added from the lookahead token.
this.tokens.pop();
this.tokens.push(this.convertToken(token));
}
// Prime the next lookahead.
this.lookahead = token;
this.nextToken();
return token;
}
createNode(): Marker {
return {
index: this.startMarker.index,
line: this.startMarker.line,
column: this.startMarker.column
};
}
startNode(token, lastLineStart = 0): Marker {
let column = token.start - token.lineStart;
let line = token.lineNumber;
if (column < 0) {
column += lastLineStart;
line--;
}
return {
index: token.start,
line: line,
column: column
};
}
finalize(marker: Marker, node) {
if (this.config.range) {
node.range = [marker.index, this.lastMarker.index];
}
if (this.config.loc) {
node.loc = {
start: {
line: marker.line,
column: marker.column,
},
end: {
line: this.lastMarker.line,
column: this.lastMarker.column
}
};
if (this.config.source) {
node.loc.source = this.config.source;
}
}
if (this.delegate) {
const metadata = {
start: {
line: marker.line,
column: marker.column,
offset: marker.index
},
end: {
line: this.lastMarker.line,
column: this.lastMarker.column,
offset: this.lastMarker.index
}
};
this.delegate(node, metadata);
}
return node;
}
// Expect the next token to match the specified punctuator.
// If not, an exception will be thrown.
expect(value) {
const token = this.nextToken();
if (token.type !== Token.Punctuator || token.value !== value) {
this.throwUnexpectedToken(token);
}
}
// Quietly expect a comma when in tolerant mode, otherwise delegates to expect().
expectCommaSeparator() {
if (this.config.tolerant) {
const token = this.lookahead;
if (token.type === Token.Punctuator && token.value === ',') {
this.nextToken();
} else if (token.type === Token.Punctuator && token.value === ';') {
this.nextToken();
this.tolerateUnexpectedToken(token);
} else {
this.tolerateUnexpectedToken(token, Messages.UnexpectedToken);
}
} else {
this.expect(',');
}
}
// Expect the next token to match the specified keyword.
// If not, an exception will be thrown.
expectKeyword(keyword) {
const token = this.nextToken();
if (token.type !== Token.Keyword || token.value !== keyword) {
this.throwUnexpectedToken(token);
}
}
// Return true if the next token matches the specified punctuator.
match(value) {
return this.lookahead.type === Token.Punctuator && this.lookahead.value === value;
}
// Return true if the next token matches the specified keyword
matchKeyword(keyword) {
return this.lookahead.type === Token.Keyword && this.lookahead.value === keyword;
}
// Return true if the next token matches the specified contextual keyword
// (where an identifier is sometimes a keyword depending on the context)
matchContextualKeyword(keyword) {
return this.lookahead.type === Token.Identifier && this.lookahead.value === keyword;
}
// Return true if the next token is an assignment operator
matchAssign() {
if (this.lookahead.type !== Token.Punctuator) {
return false;
}
const op = this.lookahead.value;
return op === '=' ||
op === '*=' ||
op === '**=' ||
op === '/=' ||
op === '%=' ||
op === '+=' ||
op === '-=' ||
op === '<<=' ||
op === '>>=' ||
op === '>>>=' ||
op === '&=' ||
op === '^=' ||
op === '|=';
}
// Cover grammar support.
//
// When an assignment expression position starts with an left parenthesis, the determination of the type
// of the syntax is to be deferred arbitrarily long until the end of the parentheses pair (plus a lookahead)
// or the first comma. This situation also defers the determination of all the expressions nested in the pair.
//
// There are three productions that can be parsed in a parentheses pair that needs to be determined
// after the outermost pair is closed. They are:
//
// 1. AssignmentExpression
// 2. BindingElements
// 3. AssignmentTargets
//
// In order to avoid exponential backtracking, we use two flags to denote if the production can be
// binding element or assignment target.
//
// The three productions have the relationship:
//
// BindingElements ⊆ AssignmentTargets ⊆ AssignmentExpression
//
// with a single exception that CoverInitializedName when used directly in an Expression, generates
// an early error. Therefore, we need the third state, firstCoverInitializedNameError, to track the
// first usage of CoverInitializedName and report it when we reached the end of the parentheses pair.
//
// isolateCoverGrammar function runs the given parser function with a new cover grammar context, and it does not
// effect the current flags. This means the production the parser parses is only used as an expression. Therefore
// the CoverInitializedName check is conducted.
//
// inheritCoverGrammar function runs the given parse function with a new cover grammar context, and it propagates
// the flags outside of the parser. This means the production the parser parses is used as a part of a potential
// pattern. The CoverInitializedName check is deferred.
isolateCoverGrammar(parseFunction) {
const previousIsBindingElement = this.context.isBindingElement;
const previousIsAssignmentTarget = this.context.isAssignmentTarget;
const previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError;
this.context.isBindingElement = true;
this.context.isAssignmentTarget = true;
this.context.firstCoverInitializedNameError = null;
const result = parseFunction.call(this);
if (this.context.firstCoverInitializedNameError !== null) {
this.throwUnexpectedToken(this.context.firstCoverInitializedNameError);
}
this.context.isBindingElement = previousIsBindingElement;
this.context.isAssignmentTarget = previousIsAssignmentTarget;
this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError;
return result;
}
inheritCoverGrammar(parseFunction) {
const previousIsBindingElement = this.context.isBindingElement;
const previousIsAssignmentTarget = this.context.isAssignmentTarget;
const previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError;
this.context.isBindingElement = true;
this.context.isAssignmentTarget = true;
this.context.firstCoverInitializedNameError = null;
const result = parseFunction.call(this);
this.context.isBindingElement = this.context.isBindingElement && previousIsBindingElement;
this.context.isAssignmentTarget = this.context.isAssignmentTarget && previousIsAssignmentTarget;
this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError || this.context.firstCoverInitializedNameError;
return result;
}
consumeSemicolon() {
if (this.match(';')) {
this.nextToken();
} else if (!this.hasLineTerminator) {
if (this.lookahead.type !== Token.EOF && !this.match('}')) {
this.throwUnexpectedToken(this.lookahead);
}
this.lastMarker.index = this.startMarker.index;
this.lastMarker.line = this.startMarker.line;
this.lastMarker.column = this.startMarker.column;
}
}
// https://tc39.github.io/ecma262/#sec-primary-expression
parsePrimaryExpression(): Node.Expression {
const node = this.createNode();
let expr: Node.Expression;
let token, raw;
switch (this.lookahead.type) {
case Token.Identifier:
if ((this.context.isModule || this.context.isAsync) && this.lookahead.value === 'await') {
this.tolerateUnexpectedToken(this.lookahead);
}
expr = this.matchAsyncFunction() ? this.parseFunctionExpression() : this.finalize(node, new Node.Identifier(this.nextToken().value));
break;
case Token.NumericLiteral:
case Token.StringLiteral:
if (this.context.strict && this.lookahead.octal) {
this.tolerateUnexpectedToken(this.lookahead, Messages.StrictOctalLiteral);
}
this.context.isAssignmentTarget = false;
this.context.isBindingElement = false;
token = this.nextToken();
raw = this.getTokenRaw(token);
expr = this.finalize(node, new Node.Literal(token.value, raw));
break;
case Token.BooleanLiteral:
this.context.isAssignmentTarget = false;
this.context.isBindingElement = false;
token = this.nextToken();
raw = this.getTokenRaw(token);
expr = this.finalize(node, new Node.Literal(token.value === 'true', raw));
break;
case Token.NullLiteral:
this.context.isAssignmentTarget = false;
this.context.isBindingElement = false;
token = this.nextToken();
raw = this.getTokenRaw(token);
expr = this.finalize(node, new Node.Literal(null, raw));
break;
case Token.Template:
expr = this.parseTemplateLiteral({ isTagged: false });
break;
case Token.Punctuator:
switch (this.lookahead.value) {
case '(':
this.context.isBindingElement = false;
expr = this.inheritCoverGrammar(this.parseGroupExpression);
break;
case '[':
expr = this.inheritCoverGrammar(this.parseArrayInitializer);
break;
case '{':
expr = this.inheritCoverGrammar(this.parseObjectInitializer);
break;
case '/':
case '/=':
this.context.isAssignmentTarget = false;
this.context.isBindingElement = false;
this.scanner.index = this.startMarker.index;
token = this.nextRegexToken();
raw = this.getTokenRaw(token);
expr = this.finalize(node, new Node.RegexLiteral(token.regex as RegExp, raw, token.pattern, token.flags));
break;
default:
expr = this.throwUnexpectedToken(this.nextToken());
}
break;
case Token.Keyword:
if (!this.context.strict && this.context.allowYield && this.matchKeyword('yield')) {
expr = this.parseIdentifierName();
} else if (!this.context.strict && this.matchKeyword('let')) {
expr = this.finalize(node, new Node.Identifier(this.nextToken().value));
} else {
this.context.isAssignmentTarget = false;
this.context.isBindingElement = false;
if (this.matchKeyword('function')) {
expr = this.parseFunctionExpression();
} else if (this.matchKeyword('this')) {
this.nextToken();
expr = this.finalize(node, new Node.ThisExpression());
} else if (this.matchKeyword('class')) {
expr = this.parseClassExpression();
} else if (this.matchImportCall()) {
expr = this.parseImportCall();
} else if (this.matchImportMeta()) {
if (!this.context.isModule) {
this.tolerateUnexpectedToken(this.lookahead, Messages.CannotUseImportMetaOutsideAModule);
}
expr = this.parseImportMeta();
} else {
expr = this.throwUnexpectedToken(this.nextToken());
}
}
break;
default:
expr = this.throwUnexpectedToken(this.nextToken());
}
return expr;
}
// https://tc39.github.io/ecma262/#sec-array-initializer
parseSpreadElement(): Node.SpreadElement {
const node = this.createNode();
this.expect('...');
const arg = this.inheritCoverGrammar(this.parseAssignmentExpression);
return this.finalize(node, new Node.SpreadElement(arg));
}
parseArrayInitializer(): Node.ArrayExpression {
const node = this.createNode();
const elements: Node.ArrayExpressionElement[] = [];
this.expect('[');
while (!this.match(']')) {
if (this.match(',')) {
this.nextToken();
elements.push(null);
} else if (this.match('...')) {
const element = this.parseSpreadElement();
if (!this.match(']')) {
this.context.isAssignmentTarget = false;
this.context.isBindingElement = false;
this.expect(',');
}
elements.push(element);
} else {
elements.push(this.inheritCoverGrammar(this.parseAssignmentExpression));
if (!this.match(']')) {
this.expect(',');
}
}
}
this.expect(']');
return this.finalize(node, new Node.ArrayExpression(elements));
}
// https://tc39.github.io/ecma262/#sec-object-initializer
parsePropertyMethod(params): Node.BlockStatement {
this.context.isAssignmentTarget = false;
this.context.isBindingElement = false;
const previousStrict = this.context.strict;
const previousAllowStrictDirective = this.context.allowStrictDirective;
this.context.allowStrictDirective = params.simple;
const body = this.isolateCoverGrammar(this.parseFunctionSourceElements);
if (this.context.strict && params.firstRestricted) {
this.tolerateUnexpectedToken(params.firstRestricted, params.message);
}
if (this.context.strict && params.stricted) {
this.tolerateUnexpectedToken(params.stricted, params.message);
}
this.context.strict = previousStrict;
this.context.allowStrictDirective = previousAllowStrictDirective;
return body;
}
parsePropertyMethodFunction(isGenerator: boolean): Node.FunctionExpression {
const node = this.createNode();
const previousAllowYield = this.context.allowYield;
this.context.allowYield = true;
const params = this.parseFormalParameters();
const method = this.parsePropertyMethod(params);
this.context.allowYield = previousAllowYield;
return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator));
}
parsePropertyMethodAsyncFunction(isGenerator: boolean): Node.FunctionExpression {
const node = this.createNode();
const previousAllowYield = this.context.allowYield;
const previousIsAsync = this.context.isAsync;
this.context.allowYield = false;
this.context.isAsync = true;
const params = this.parseFormalParameters();
const method = this.parsePropertyMethod(params);
this.context.allowYield = previousAllowYield;
this.context.isAsync = previousIsAsync;
return this.finalize(node, new Node.AsyncFunctionExpression(null, params.params, method, isGenerator));
}
parseObjectPropertyKey(): Node.PropertyKey {
const node = this.createNode();
const token = this.nextToken();
let key: Node.PropertyKey;
switch (token.type) {
case Token.StringLiteral:
case Token.NumericLiteral:
if (this.context.strict && token.octal) {
this.tolerateUnexpectedToken(token, Messages.StrictOctalLiteral);
}
const raw = this.getTokenRaw(token);
key = this.finalize(node, new Node.Literal(token.value as string, raw));
break;
case Token.Identifier:
case Token.BooleanLiteral:
case Token.NullLiteral:
case Token.Keyword:
key = this.finalize(node, new Node.Identifier(token.value));
break;
case Token.Punctuator:
if (token.value === '[') {
key = this.isolateCoverGrammar(this.parseAssignmentExpression);
this.expect(']');
} else {
key = this.throwUnexpectedToken(token);
}
break;
default:
key = this.throwUnexpectedToken(token);
}
return key;
}
isPropertyKey(key, value) {
return (key.type === Syntax.Identifier && key.name === value) ||
(key.type === Syntax.Literal && key.value === value);
}
parseObjectProperty(hasProto): Node.Property {
const node = this.createNode();
const token = this.lookahead;
let kind: string;
let key: Node.PropertyKey | null = null;
let value: Node.PropertyValue | null = null;
let computed = false;
let method = false;
let shorthand = false;
let isAsync = false;
let isGenerator = false;
if (token.type === Token.Identifier) {
const id = token.value;
this.nextToken();
computed = this.match('[');
isAsync = !this.hasLineTerminator && (id === 'async') &&
!this.match(':') && !this.match('(') && !this.match(',');
isGenerator = this.match('*');
if (isGenerator) {
this.nextToken();
}
key = isAsync ? this.parseObjectPropertyKey() : this.finalize(node, new Node.Identifier(id));
} else if (this.match('*')) {
this.nextToken();
} else {
computed = this.match('[');
key = this.parseObjectPropertyKey();
}
const lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead);
if (token.type === Token.Identifier && !isAsync && token.value === 'get' && lookaheadPropertyKey) {
kind = 'get';
computed = this.match('[');
key = this.parseObjectPropertyKey();
this.context.allowYield = false;
value = this.parseGetterMethod();
} else if (token.type === Token.Identifier && !isAsync && token.value === 'set' && lookaheadPropertyKey) {
kind = 'set';
computed = this.match('[');
key = this.parseObjectPropertyKey();
value = this.parseSetterMethod();
} else if (token.type === Token.Punctuator && token.value === '*' && lookaheadPropertyKey) {
kind = 'init';
computed = this.match('[');
key = this.parseObjectPropertyKey();
value = this.parseGeneratorMethod();
method = true;
} else {
if (!key) {
this.throwUnexpectedToken(this.lookahead);
}
kind = 'init';
if (this.match(':') && !isAsync) {
if (!computed && this.isPropertyKey(key, '__proto__')) {
if (hasProto.value) {
this.tolerateError(Messages.DuplicateProtoProperty);
}
hasProto.value = true;
}
this.nextToken();
value = this.inheritCoverGrammar(this.parseAssignmentExpression);
} else if (this.match('(')) {
value = isAsync ? this.parsePropertyMethodAsyncFunction(isGenerator) : this.parsePropertyMethodFunction(isGenerator);
method = true;
} else if (token.type === Token.Identifier) {
const id = this.finalize(node, new Node.Identifier(token.value));
if (this.match('=')) {
this.context.firstCoverInitializedNameError = this.lookahead;
this.nextToken();
shorthand = true;
const init = this.isolateCoverGrammar(this.parseAssignmentExpression);
value = this.finalize(node, new Node.AssignmentPattern(id, init));
} else {
shorthand = true;
value = id;
}
} else {
this.throwUnexpectedToken(this.nextToken());
}
}
return this.finalize(node, new Node.Property(kind, key as Node.PropertyKey, computed, value, method, shorthand));
}
parseObjectInitializer(): Node.ObjectExpression {
const node = this.createNode();
this.expect('{');
const properties: Node.ObjectExpressionProperty[] = [];
const hasProto = { value: false };
while (!this.match('}')) {
properties.push(this.match('...') ? this.parseSpreadElement() : this.parseObjectProperty(hasProto));
if (!this.match('}')) {
this.expectCommaSeparator();
}
}
this.expect('}');
return this.finalize(node, new Node.ObjectExpression(properties));
}
// https://tc39.es/proposal-template-literal-revision/#sec-static-semantics-template-early-errors
throwTemplateLiteralEarlyErrors(token: RawToken): never {
switch (token.notEscapeSequenceHead) {
case 'u':
return this.throwUnexpectedToken(token, Messages.InvalidUnicodeEscapeSequence);
case 'x':
return this.throwUnexpectedToken(token, Messages.InvalidHexEscapeSequence);
case '8':
case '9':
return this.throwUnexpectedToken(token, Messages.TemplateEscape89);
default: // For 0-7
return this.throwUnexpectedToken(token, Messages.TemplateOctalLiteral);
}
}
// https://tc39.github.io/ecma262/#sec-template-literals
parseTemplateHead(options: ParseTemplateLiteralOptions): Node.TemplateElement {
assert(this.lookahead.head as boolean, 'Template literal must start with a template head');
const node = this.createNode();
const token = this.nextToken();
if (!options.isTagged && token.notEscapeSequenceHead !== null) {
this.throwTemplateLiteralEarlyErrors(token);
}
const raw = token.value as string;
const cooked = token.cooked as string;
return this.finalize(node, new Node.TemplateElement({ raw, cooked }, token.tail as boolean));
}
parseTemplateElement(options: ParseTemplateLiteralOptions): Node.TemplateElement {
if (this.lookahead.type !== Token.Template) {
this.throwUnexpectedToken();
}
const node = this.createNode();
const token = this.nextToken();