-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathParser.java
More file actions
3890 lines (3531 loc) · 143 KB
/
Parser.java
File metadata and controls
3890 lines (3531 loc) · 143 KB
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
package com.semmle.jcorn;
import static com.semmle.jcorn.Whitespace.isNewLine;
import static com.semmle.jcorn.Whitespace.lineBreak;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.Stack;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.semmle.jcorn.Identifiers.Dialect;
import com.semmle.jcorn.Options.AllowReserved;
import com.semmle.js.ast.ArrayExpression;
import com.semmle.js.ast.ArrayPattern;
import com.semmle.js.ast.ArrowFunctionExpression;
import com.semmle.js.ast.AssignmentExpression;
import com.semmle.js.ast.AssignmentPattern;
import com.semmle.js.ast.AwaitExpression;
import com.semmle.js.ast.BinaryExpression;
import com.semmle.js.ast.BlockStatement;
import com.semmle.js.ast.BreakStatement;
import com.semmle.js.ast.CallExpression;
import com.semmle.js.ast.CatchClause;
import com.semmle.js.ast.Chainable;
import com.semmle.js.ast.ClassBody;
import com.semmle.js.ast.ClassDeclaration;
import com.semmle.js.ast.ClassExpression;
import com.semmle.js.ast.ConditionalExpression;
import com.semmle.js.ast.ContinueStatement;
import com.semmle.js.ast.DebuggerStatement;
import com.semmle.js.ast.DeclarationFlags;
import com.semmle.js.ast.DoWhileStatement;
import com.semmle.js.ast.EmptyStatement;
import com.semmle.js.ast.EnhancedForStatement;
import com.semmle.js.ast.ExportAllDeclaration;
import com.semmle.js.ast.ExportDeclaration;
import com.semmle.js.ast.ExportDefaultDeclaration;
import com.semmle.js.ast.ExportNamedDeclaration;
import com.semmle.js.ast.ExportSpecifier;
import com.semmle.js.ast.Expression;
import com.semmle.js.ast.ExpressionStatement;
import com.semmle.js.ast.ForInStatement;
import com.semmle.js.ast.ForOfStatement;
import com.semmle.js.ast.ForStatement;
import com.semmle.js.ast.FunctionDeclaration;
import com.semmle.js.ast.FunctionExpression;
import com.semmle.js.ast.GeneratedCodeExpr;
import com.semmle.js.ast.IFunction;
import com.semmle.js.ast.INode;
import com.semmle.js.ast.IPattern;
import com.semmle.js.ast.Identifier;
import com.semmle.js.ast.IfStatement;
import com.semmle.js.ast.ImportDeclaration;
import com.semmle.js.ast.ImportDefaultSpecifier;
import com.semmle.js.ast.ImportNamespaceSpecifier;
import com.semmle.js.ast.ImportPhaseModifier;
import com.semmle.js.ast.ImportSpecifier;
import com.semmle.js.ast.LabeledStatement;
import com.semmle.js.ast.Literal;
import com.semmle.js.ast.LogicalExpression;
import com.semmle.js.ast.MemberDefinition;
import com.semmle.js.ast.MemberExpression;
import com.semmle.js.ast.MetaProperty;
import com.semmle.js.ast.MethodDefinition;
import com.semmle.js.ast.NewExpression;
import com.semmle.js.ast.Node;
import com.semmle.js.ast.ObjectExpression;
import com.semmle.js.ast.ObjectPattern;
import com.semmle.js.ast.ParenthesizedExpression;
import com.semmle.js.ast.Position;
import com.semmle.js.ast.Program;
import com.semmle.js.ast.Property;
import com.semmle.js.ast.RestElement;
import com.semmle.js.ast.ReturnStatement;
import com.semmle.js.ast.SequenceExpression;
import com.semmle.js.ast.SourceLocation;
import com.semmle.js.ast.SpreadElement;
import com.semmle.js.ast.Statement;
import com.semmle.js.ast.StaticInitializer;
import com.semmle.js.ast.Super;
import com.semmle.js.ast.SwitchCase;
import com.semmle.js.ast.SwitchStatement;
import com.semmle.js.ast.TaggedTemplateExpression;
import com.semmle.js.ast.TemplateElement;
import com.semmle.js.ast.TemplateLiteral;
import com.semmle.js.ast.ThisExpression;
import com.semmle.js.ast.ThrowStatement;
import com.semmle.js.ast.Token;
import com.semmle.js.ast.TryStatement;
import com.semmle.js.ast.UnaryExpression;
import com.semmle.js.ast.UpdateExpression;
import com.semmle.js.ast.VariableDeclaration;
import com.semmle.js.ast.VariableDeclarator;
import com.semmle.js.ast.WhileStatement;
import com.semmle.js.ast.WithStatement;
import com.semmle.js.ast.YieldExpression;
import com.semmle.ts.ast.ITypeExpression;
import com.semmle.util.collections.CollectionUtil;
import com.semmle.util.data.Pair;
import com.semmle.util.data.StringUtil;
import com.semmle.util.exception.CatastrophicError;
import com.semmle.util.exception.Exceptions;
import com.semmle.util.io.WholeIO;
/**
* Java port of Acorn.
*
* <p>This version corresponds to <a
* href="https://github.com/ternjs/acorn/commit/bb54adcdbceef01997a9549732139ca8f53a4e28">Acorn
* 4.0.3</a>, but does not support plugins, and always tracks full source locations.
*/
public class Parser {
protected final Options options;
protected final Set<String> keywords;
private final Set<String> reservedWords, reservedWordsStrict, reservedWordsStrictBind;
protected final String input;
private boolean containsEsc;
protected boolean exprAllowed;
protected boolean strict;
private boolean inModule;
protected boolean inFunction;
protected boolean inGenerator;
protected boolean inClass;
protected boolean inAsync;
protected boolean inTemplateElement;
protected int pos;
protected int lineStart;
protected int curLine;
protected int start;
protected int end;
protected TokenType type;
protected Object value;
protected Position startLoc;
protected Position endLoc;
protected Position lastTokEndLoc, lastTokStartLoc;
protected int lastTokStart, lastTokEnd;
protected Stack<TokContext> context;
protected int potentialArrowAt;
private Stack<LabelInfo> labels;
protected int yieldPos, awaitPos;
/**
* Set to true by {@link ESNextParser#readInt} if the parsed integer contains an underscore.
*/
protected boolean seenUnderscoreNumericSeparator = false;
/**
* For readability purposes, we pass this instead of false as the argument to the
* hasDeclareKeyword parameter (which only exists in TypeScript).
*/
private static final boolean noDeclareKeyword = false;
/**
* For readability purposes, we pass this instead of false as the argument to the isAbstract
* parameter (which only exists in TypeScript).
*/
protected static final boolean notAbstract = false;
/**
* For readability purposes, we pass this instead of null as the argument to the type annotation
* parameters (which only exists in TypeScript).
*/
private static final ITypeExpression noTypeAnnotation = null;
protected static class LabelInfo {
String name, kind;
int statementStart;
public LabelInfo(String name, String kind, int statementStart) {
this.name = name;
this.kind = kind;
this.statementStart = statementStart;
}
}
public static void main(String[] args) {
new Parser(new Options(), new WholeIO().strictread(new File(args[0])), 0).parse();
}
/// begin state.js
public Parser(Options options, String input, int startPos) {
this.options = options;
this.keywords =
new LinkedHashSet<String>(
Identifiers.keywords.get(
options.ecmaVersion() >= 6
? Identifiers.Dialect.ECMA_6
: Identifiers.Dialect.ECMA_5));
this.reservedWords = new LinkedHashSet<String>();
if (!options.allowReserved().isTrue()) {
this.reservedWords.addAll(Identifiers.reservedWords.get(options.getDialect()));
if (options.sourceType().equals("module")) this.reservedWords.add("await");
}
this.reservedWordsStrict = new LinkedHashSet<String>(this.reservedWords);
this.reservedWordsStrict.addAll(Identifiers.reservedWords.get(Dialect.STRICT));
this.reservedWordsStrictBind = new LinkedHashSet<String>(this.reservedWordsStrict);
this.reservedWordsStrictBind.addAll(Identifiers.reservedWords.get(Dialect.STRICT_BIND));
this.input = input;
// Used to signal to callers of `readWord1` whether the word
// contained any escape sequences. This is needed because words with
// escape sequences must not be interpreted as keywords.
this.containsEsc = false;
// Set up token state
// The current position of the tokenizer in the input.
if (startPos != 0) {
this.pos = startPos;
this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
this.curLine = inputSubstring(0, this.lineStart).split(Whitespace.lineBreak).length;
} else {
this.pos = this.lineStart = 0;
this.curLine = 1;
}
// Properties of the current token:
// Its type
this.type = TokenType.eof;
// For tokens that include more information than their type, the value
this.value = null;
// Its start and end offset
this.start = this.end = this.pos;
// And, if locations are used, the {line, column} object
// corresponding to those offsets
this.startLoc = this.endLoc = this.curPosition();
// Position information for the previous token
this.lastTokEndLoc = this.lastTokStartLoc = null;
this.lastTokStart = this.lastTokEnd = this.pos;
// The context stack is used to superficially track syntactic
// context to predict whether a regular expression is allowed in a
// given position.
this.context = this.initialContext();
this.exprAllowed = true;
// Figure out if it's a module code.
this.inModule = options.sourceType().equals("module");
// We don't care to report syntax errors in code that might be using strict mode. In
// the end, we don't know whether that code is put through additional build steps
// causing our alleged syntax errors to disappear. Therefore, we hardcode
// this.strict to false.
this.strict = false;
// Used to signify the start of a potential arrow function
this.potentialArrowAt = -1;
// Flags to track whether we are in a function, a generator, an async function, a class.
this.inFunction = this.inGenerator = this.inAsync = this.inClass = false;
// Positions to delayed-check that yield/await does not exist in default parameters.
this.yieldPos = this.awaitPos = 0;
// Labels in scope.
this.labels = new Stack<LabelInfo>();
// If enabled, skip leading hashbang line.
if (this.pos == 0 && options.allowHashBang() && this.input.startsWith("#!"))
this.skipLineComment(2);
}
public Program parse() {
Position startLoc = this.startLoc;
this.nextToken();
return this.parseTopLevel(startLoc, this.options.program());
}
/// end state.js
/// begin location.js
protected void raise(int pos, String msg, boolean recoverable) {
Position loc = Locutil.getLineInfo(input, pos);
raise(loc, msg, recoverable);
}
protected void raise(int pos, String msg) {
raise(pos, msg, false);
}
@SuppressWarnings("ReturnValueIgnored")
protected void raise(Position loc, String msg, boolean recoverable) {
msg += " (" + loc.getLine() + ":" + loc.getColumn() + ")";
SyntaxError err = new SyntaxError(msg, loc, this.pos);
if (recoverable && options.onRecoverableError() != null)
options.onRecoverableError().apply(err);
else throw err;
}
protected void raise(Position loc, String msg) {
raise(loc, msg, false);
}
protected void raise(INode nd, String msg) {
raise(nd.getLoc().getStart(), msg, false);
}
protected void raiseRecoverable(int pos, String msg) {
raise(pos, msg, true);
}
protected void raiseRecoverable(INode nd, String msg) {
raise(nd.getLoc().getStart(), msg, true);
}
protected Position curPosition() {
return new Position(curLine, pos - lineStart, pos);
}
/// end location.js
/// begin tokenize.js
// Move to the next token
protected void next() {
if (this.options.onToken() != null) this.options.onToken().apply(mkToken());
this.lastTokEnd = this.end;
this.lastTokStart = this.start;
this.lastTokEndLoc = this.endLoc;
this.lastTokStartLoc = this.startLoc;
this.nextToken();
}
// DEPRECATED. When we respected strict mode, this method was used to toggle strict
// mode (and would re-read the next number or string to please pedantic tests (`"use
// strict"; 010;` should fail)).
public void setStrict(boolean strict) {
// always false
return;
}
public TokContext curContext() {
return context.peek();
}
// Read a single token, updating the parser object's token-related
// properties.
public Token nextToken() {
TokContext curContext = this.curContext();
if (curContext == null || !curContext.preserveSpace) this.skipSpace();
this.start = this.pos;
this.startLoc = this.curPosition();
if (this.pos >= this.input.length()) return this.finishToken(TokenType.eof);
if (curContext != null && curContext.override != null) return curContext.override.apply(this);
else return this.readToken(this.fullCharCodeAtPos());
}
protected Token readToken(int code) {
// Identifier or keyword. '\\uXXXX' sequences are allowed in
// identifiers, so '\' also dispatches to that.
if (Identifiers.isIdentifierStart(code, this.options.ecmaVersion() >= 6)
|| code == 92 /* '\' */) return this.readWord();
return this.getTokenFromCode(code);
}
protected int fullCharCodeAtPos() {
int code = charAt(this.pos);
if (code <= 0xd7ff || code >= 0xe000) return code;
int next = charAt(this.pos + 1);
return (code << 10) + next - 0x35fdc00;
}
protected void skipBlockComment() {
Position startLoc = this.options.onComment() != null ? this.curPosition() : null;
int start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
if (end == -1) this.raise(this.pos - 2, "Unterminated comment");
this.pos = end + 2;
Matcher m = Whitespace.lineBreakG.matcher(this.input);
int next = start;
while (m.find(next) && m.start() < this.pos) {
++this.curLine;
lineStart = m.end();
next = lineStart;
}
if (this.options.onComment() != null)
this.options
.onComment()
.call(
true,
this.input,
inputSubstring(start + 2, end),
start,
this.pos,
startLoc,
this.curPosition());
}
protected void skipLineComment(int startSkip) {
int start = this.pos;
Position startLoc = this.options.onComment() != null ? this.curPosition() : null;
this.pos += startSkip;
int ch = charAt(this.pos);
while (this.pos < this.input.length() && ch != 10 && ch != 13 && ch != 8232 && ch != 8233) {
++this.pos;
ch = charAt(this.pos);
}
if (this.options.onComment() != null)
this.options
.onComment()
.call(
false,
this.input,
inputSubstring(start + startSkip, this.pos),
start,
this.pos,
startLoc,
this.curPosition());
}
// Called at the start of the parse and after every token. Skips
// whitespace and comments, and.
protected void skipSpace() {
loop:
while (this.pos < this.input.length()) {
int ch = this.input.charAt(this.pos);
switch (ch) {
case 32:
case 160: // ' '
++this.pos;
break;
case 13:
if (charAt(this.pos + 1) == 10) {
++this.pos;
}
case 10:
case 8232:
case 8233:
++this.pos;
++this.curLine;
this.lineStart = this.pos;
break;
case 47: // '/'
switch (charAt(this.pos + 1)) {
case 42: // '*'
this.skipBlockComment();
break;
case 47:
this.skipLineComment(2);
break;
default:
break loop;
}
break;
default:
if (ch > 8 && ch < 14 || ch >= 5760 && Whitespace.nonASCIIwhitespace.indexOf(ch) > -1) {
++this.pos;
} else {
break loop;
}
}
}
}
// Called at the end of every token. Sets `end`, `val`, and
// maintains `context` and `exprAllowed`, and skips the space after
// the token, so that the next one's `start` will point at the
// right position.
protected Token finishToken(TokenType type, Object val) {
this.end = this.pos;
this.endLoc = this.curPosition();
TokenType prevType = this.type;
this.type = type;
this.value = val;
this.updateContext(prevType);
return mkToken();
}
private Token mkToken() {
String src = inputSubstring(start, end);
SourceLocation loc = new SourceLocation(src, startLoc, endLoc);
String label, keyword;
if (isKeyword(src)) {
label = keyword = src;
} else {
label = type.label;
keyword = type.keyword;
}
return new Token(loc, label, keyword);
}
protected boolean isKeyword(String src) {
if (type.keyword != null) return true;
if (type == TokenType.name) {
if (keywords.contains(src)) return true;
if (options.ecmaVersion() >= 6 && ("let".equals(src) || "yield".equals(src))) return true;
}
return false;
}
protected Token finishToken(TokenType type) {
return finishToken(type, null);
}
// ### Token reading
// This is the function that is called to fetch the next token. It
// is somewhat obscure, because it works in character codes rather
// than characters, and because operator parsing has been inlined
// into it.
//
// All in the name of speed.
//
private Token readToken_dot() {
int next = charAt(this.pos + 1);
if (next >= 48 && next <= 57) return this.readNumber(true);
int next2 = charAt(this.pos + 2);
if (this.options.ecmaVersion() >= 6 && next == 46 && next2 == 46) { // 46 = dot '.'
this.pos += 3;
return this.finishToken(TokenType.ellipsis);
} else {
++this.pos;
return this.finishToken(TokenType.dot);
}
}
private Token readToken_question() { // '?'
int next = charAt(this.pos + 1);
int next2 = charAt(this.pos + 2);
if (this.options.esnext()) {
if (next == '.' && !('0' <= next2 && next2 <= '9')) // '?.', but not '?.X' where X is a digit
return this.finishOp(TokenType.questiondot, 2);
if (next == '?') { // '??'
if (next2 == '=') { // ??=
return this.finishOp(TokenType.assign, 3);
}
return this.finishOp(TokenType.questionquestion, 2);
}
}
return this.finishOp(TokenType.question, 1);
}
private Token readToken_slash() { // '/'
int next = charAt(this.pos + 1);
if (this.exprAllowed) {
++this.pos;
return this.readRegexp();
}
if (next == 61) return this.finishOp(TokenType.assign, 2);
return this.finishOp(TokenType.slash, 1);
}
private Token readToken_mult_modulo_exp(int code) { // '%*'
int next = charAt(this.pos + 1);
int size = 1;
TokenType tokentype = code == 42 ? TokenType.star : TokenType.modulo;
// exponentiation operator ** and **=
if (this.options.ecmaVersion() >= 7 && code == 42 && next == 42) {
++size;
tokentype = TokenType.starstar;
next = charAt(this.pos + 2);
}
if (next == 61) return this.finishOp(TokenType.assign, size + 1);
return this.finishOp(tokentype, size);
}
private Token readToken_pipe_amp(int code) { // '|&'
int next = charAt(this.pos + 1);
int next2 = charAt(this.pos + 2);
if (next == code) { // && ||
if (next2 == 61) return this.finishOp(TokenType.assign, 3); // &&= ||=
return this.finishOp(code == 124 ? TokenType.logicalOR : TokenType.logicalAND, 2);
}
if (next == 61) return this.finishOp(TokenType.assign, 2);
return this.finishOp(code == 124 ? TokenType.bitwiseOR : TokenType.bitwiseAND, 1);
}
private Token readToken_caret() { // '^'
int next = charAt(this.pos + 1);
if (next == 61) return this.finishOp(TokenType.assign, 2);
return this.finishOp(TokenType.bitwiseXOR, 1);
}
private Token readToken_plus_min(int code) { // '+-'
int next = charAt(this.pos + 1);
if (next == code) {
if (next == 45
&& charAt(this.pos + 2) == 62
&& inputSubstring(this.lastTokEnd, this.pos).matches("(?s).*(?:" + lineBreak + ").*")) {
// A `-->` line comment
this.skipLineComment(3);
this.skipSpace();
return this.nextToken();
}
return this.finishOp(TokenType.incDec, 2);
}
if (next == 61) return this.finishOp(TokenType.assign, 2);
return this.finishOp(TokenType.plusMin, 1);
}
private Token readToken_lt_gt(int code) { // '<>'
int next = charAt(this.pos + 1);
int size = 1;
if (next == code) {
size = code == 62 && charAt(this.pos + 2) == 62 ? 3 : 2;
if (charAt(this.pos + size) == 61) return this.finishOp(TokenType.assign, size + 1);
return this.finishOp(TokenType.bitShift, size);
}
if (next == 33 && code == 60 && charAt(this.pos + 2) == 45 && charAt(this.pos + 3) == 45) {
if (this.inModule) this.unexpected();
// `<!--`, an XML-style comment that should be interpreted as a line comment
this.skipLineComment(4);
this.skipSpace();
return this.nextToken();
}
if (next == '%' && code == '<' && this.options.allowGeneratedCodeExprs()) {
// `<%`, the beginning of an EJS-style template tag
size = 2;
int nextNext = charAt(this.pos + 2);
if (nextNext == '=' || nextNext == '-') {
++size;
}
return this.finishOp(TokenType.generatedCodeDelimiterEJS, size);
}
if (next == 61) size = 2;
return this.finishOp(TokenType.relational, size);
}
private Token readToken_eq_excl(int code) { // '=!'
int next = charAt(this.pos + 1);
if (next == 61) return this.finishOp(TokenType.equality, charAt(this.pos + 2) == 61 ? 3 : 2);
if (code == 61 && next == 62 && this.options.ecmaVersion() >= 6) { // '=>'
this.pos += 2;
return this.finishToken(TokenType.arrow);
}
return this.finishOp(code == 61 ? TokenType.eq : TokenType.prefix, 1);
}
protected Token getTokenFromCode(int code) {
switch (code) {
// The interpretation of a dot depends on whether it is followed
// by a digit or another two dots.
case 46: // '.'
return this.readToken_dot();
// Punctuation tokens.
case 40:
++this.pos;
return this.finishToken(TokenType.parenL);
case 41:
++this.pos;
return this.finishToken(TokenType.parenR);
case 59:
++this.pos;
return this.finishToken(TokenType.semi);
case 44:
++this.pos;
return this.finishToken(TokenType.comma);
case 91:
++this.pos;
return this.finishToken(TokenType.bracketL);
case 93:
++this.pos;
return this.finishToken(TokenType.bracketR);
case 123:
++this.pos;
return this.finishToken(TokenType.braceL);
case 125:
++this.pos;
return this.finishToken(TokenType.braceR);
case 58:
++this.pos;
return this.finishToken(TokenType.colon);
case 35:
++this.pos;
return this.finishToken(TokenType.pound);
case 63:
return this.readToken_question();
case 96: // '`'
if (this.options.ecmaVersion() < 6) break;
++this.pos;
return this.finishToken(TokenType.backQuote);
case 48: // '0'
int next = charAt(this.pos + 1);
if (next == 120 || next == 88) return this.readRadixNumber(16); // '0x', '0X' - hex number
if (this.options.ecmaVersion() >= 6) {
if (next == 111 || next == 79)
return this.readRadixNumber(8); // '0o', '0O' - octal number
if (next == 98 || next == 66)
return this.readRadixNumber(2); // '0b', '0B' - binary number
}
// Anything else beginning with a digit is an integer, octal
// number, or float.
case 49:
case 50:
case 51:
case 52:
case 53:
case 54:
case 55:
case 56:
case 57: // 1-9
return this.readNumber(false);
// Quotes produce strings.
case 34:
case 39: // '"', "'"
return this.readString((char) code);
// Operators are parsed inline in tiny state machines. '=' (61) is
// often referred to. `finishOp` simply skips the amount of
// characters it is given as second argument, and returns a token
// of the type given by its first argument.
case 47: // '/'
return this.readToken_slash();
case 37:
case 42: // '%*'
return this.readToken_mult_modulo_exp(code);
case 124: // '|'
case 38: // '&'
return this.readToken_pipe_amp(code);
case 94: // '^'
return this.readToken_caret();
case 43:
case 45: // '+-'
return this.readToken_plus_min(code);
case 60:
case 62: // '<>'
return this.readToken_lt_gt(code);
case 61:
case 33: // '=!'
return this.readToken_eq_excl(code);
case 126: // '~'
return this.finishOp(TokenType.prefix, 1);
}
String msg = String.format("Unexpected character '%s' (U+%04X)", codePointToString(code), code);
this.raise(this.pos, msg);
return null;
}
protected Token finishOp(TokenType type, int size) {
String str = inputSubstring(this.pos, this.pos + size);
this.pos += size;
return this.finishToken(type, str);
}
private Token readRegexp() {
boolean escaped = false, inClass = false;
int start = this.pos;
for (; ; ) {
if (this.pos >= this.input.length()) this.raise(start, "Unterminated regular expression");
int ch = this.input.charAt(this.pos);
if (isNewLine(ch)) this.raise(start, "Unterminated regular expression");
if (!escaped) {
if (ch == '[') inClass = true;
else if (ch == ']' && inClass) inClass = false;
else if (ch == '/' && !inClass) break;
escaped = ch == '\\';
} else {
escaped = false;
}
++this.pos;
}
String content = inputSubstring(start, this.pos);
++this.pos;
// Need to use `readWord1` because '\\uXXXX' sequences are allowed
// here (don't ask).
String mods = this.readWord1();
if (mods != null) {
String validFlags = "gim";
if (this.options.ecmaVersion() >= 6) validFlags = "gimuy";
if (this.options.ecmaVersion() >= 9) validFlags = "gimsuy";
if (this.options.ecmaVersion() >= 15) validFlags = "gimsuyv";
if (!mods.matches("^[" + validFlags + "]*$"))
this.raise(start, "Invalid regular expression flag");
if (mods.indexOf('u') >= 0) {
Matcher m = Pattern.compile("\\\\u\\{([0-9a-fA-F]+)\\}").matcher(content);
while (m.find()) {
try {
int code = Integer.parseInt(m.group(1), 16);
if (code > 0x10FFFF)
this.raiseRecoverable(start + m.start() + 3, "Code point out of bounds");
} catch (NumberFormatException nfe) {
Exceptions.ignore(nfe, "Don't complain about code points we don't understand.");
}
}
}
}
return this.finishToken(TokenType.regexp, content);
}
// Read an integer in the given radix. Return null if zero digits
// were read, the integer value otherwise. When `len` is given, this
// will return `null` unless the integer has exactly `len` digits.
protected Number readInt(int radix, Integer len) {
int start = this.pos;
double total = 0;
for (int i = 0, e = len == null ? Integer.MAX_VALUE : len; i < e; ++i) {
if (this.pos >= this.input.length()) break;
int code = this.input.charAt(this.pos), val;
if (code >= 97) val = code - 97 + 10; // a
else if (code >= 65) val = code - 65 + 10; // A
else if (code >= 48 && code <= 57) val = code - 48; // 0-9
else val = Integer.MAX_VALUE;
if (val >= radix) break;
++this.pos;
total = total * radix + val;
}
if (this.pos == start || len != null && this.pos - start != len) return null;
return total;
}
protected Token readRadixNumber(int radix) {
this.pos += 2; // 0x
Number val = this.readInt(radix, null);
if (val == null) this.raise(this.start + 2, "Expected number in radix " + radix);
// check for bigint literal
if (options.esnext() && this.fullCharCodeAtPos() == 'n') {
++this.pos;
return this.finishToken(TokenType.bigint, val);
}
if (Identifiers.isIdentifierStart(this.fullCharCodeAtPos(), false))
this.raise(this.pos, "Identifier directly after number");
return this.finishToken(TokenType.num, val);
}
// Read an integer, octal integer, or floating-point number.
protected Token readNumber(boolean startsWithDot) {
int start = this.pos;
boolean isFloat = false, octal = charAt(this.pos) == 48, isBigInt = false;
if (!startsWithDot && this.readInt(10, null) == null) this.raise(start, "Invalid number");
if (octal && this.pos == start + 1) octal = false;
if (this.pos < this.input.length()) {
int next = this.input.charAt(this.pos);
if (next == 46 && !octal) { // '.'
++this.pos;
this.readInt(10, null);
isFloat = true;
next = charAt(this.pos);
}
if ((next == 69 || next == 101) && !octal) { // 'eE'
next = charAt(++this.pos);
if (next == 43 || next == 45) ++this.pos; // '+-'
if (this.readInt(10, null) == null) this.raise(start, "Invalid number");
isFloat = true;
}
if (!isFloat && options.esnext() && this.fullCharCodeAtPos() == 'n') isBigInt = true;
else if (Identifiers.isIdentifierStart(this.fullCharCodeAtPos(), false))
this.raise(this.pos, "Identifier directly after number");
}
String str = inputSubstring(start, this.pos);
if (seenUnderscoreNumericSeparator) {
str = str.replace("_", "");
seenUnderscoreNumericSeparator = false;
}
Number val = null;
if (isFloat) val = parseFloat(str);
else if (!octal || str.length() == 1) val = parseInt(str, 10);
else if (str.matches(".*[89].*") || this.strict) this.raise(start, "Invalid number");
else val = parseInt(str, 8);
// handle bigints
if (isBigInt) {
++this.pos;
return this.finishToken(TokenType.bigint, val);
}
return this.finishToken(TokenType.num, val);
}
// Read a string value, interpreting backslash-escapes.
protected int readCodePoint() {
int ch = charAt(this.pos), code;
if (ch == 123) {
if (this.options.ecmaVersion() < 6) this.unexpected();
int codePos = ++this.pos;
code = this.readHexChar(this.input.indexOf('}', this.pos) - this.pos);
++this.pos;
if (code > 0x10FFFF) this.invalidStringToken(codePos, "Code point out of bounds");
} else {
code = this.readHexChar(4);
}
return code;
}
protected String codePointToString(int code) {
// UTF-16 Decoding
if (code <= 0xFFFF) return String.valueOf((char) code);
code -= 0x10000;
return new String(new char[] {(char) ((code >> 10) + 0xD800), (char) ((code & 1023) + 0xDC00)});
}
protected Token readString(char quote) {
StringBuilder out = new StringBuilder();
int chunkStart = ++this.pos;
for (; ; ) {
if (this.pos >= this.input.length()) this.raise(this.start, "Unterminated string constant");
int ch = this.input.charAt(this.pos);
if (ch == quote) break;
if (ch == 92) { // '\'
out.append(inputSubstring(chunkStart, this.pos));
out.append(this.readEscapedChar(false));
chunkStart = this.pos;
} else if (options.ecmaVersion() >= 10 && (ch == 0x2028 || ch == 0x2029)) {
// ECMAScript 2019 allows Unicode newlines in string literals
++this.pos;
} else {
if (Whitespace.isNewLine(ch)) this.raise(this.start, "Unterminated string constant");
++this.pos;
}
}
out.append(inputSubstring(chunkStart, this.pos++));
return this.finishToken(TokenType.string, out.toString());
}
// Reads template string tokens.
private static final RuntimeException INVALID_TEMPLATE_ESCAPE_ERROR = new RuntimeException();
private Token tryReadTemplateToken() {
this.inTemplateElement = true;
try {
return this.readTmplToken();
} catch (RuntimeException err) {
if (err == INVALID_TEMPLATE_ESCAPE_ERROR) {
return this.readInvalidTemplateToken();
} else {
throw err;
}
} finally {
this.inTemplateElement = false;
}
}
private void invalidStringToken(int position, String message) {
if (this.inTemplateElement && this.options.ecmaVersion() >= 9) {
throw INVALID_TEMPLATE_ESCAPE_ERROR;
} else {
this.raise(position, message);
}
}
protected Token readTmplToken() {
StringBuilder out = new StringBuilder();
int chunkStart = this.pos;
for (; ; ) {
if (this.pos >= this.input.length()) this.raise(this.start, "Unterminated template");
int ch = this.input.charAt(this.pos);
if (ch == 96 || ch == 36 && charAt(this.pos + 1) == 123) { // '`', '${'
if (this.pos == this.start
&& (this.type == TokenType.template || this.type == TokenType.invalidTemplate)) {
if (ch == 36) {
this.pos += 2;
return this.finishToken(TokenType.dollarBraceL);
} else {
++this.pos;
return this.finishToken(TokenType.backQuote);
}
}
out.append(inputSubstring(chunkStart, this.pos));
return this.finishToken(TokenType.template, out.toString());
}
if (ch == 92) { // '\'
out.append(inputSubstring(chunkStart, this.pos));
out.append(this.readEscapedChar(true));
chunkStart = this.pos;
} else if (Whitespace.isNewLine(ch)) {
out.append(inputSubstring(chunkStart, this.pos));
++this.pos;
switch (ch) {
case 13:
if (charAt(this.pos) == 10) ++this.pos;
case 10:
out.append('\n');
break;