-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Parser.java
4106 lines (3682 loc) · 136 KB
/
Parser.java
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
/*
* Copyright 2011 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp.parsing.parser;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.annotations.FormatMethod;
import com.google.errorprone.annotations.FormatString;
import com.google.javascript.jscomp.parsing.parser.FeatureSet.Feature;
import com.google.javascript.jscomp.parsing.parser.trees.AmbientDeclarationTree;
import com.google.javascript.jscomp.parsing.parser.trees.ArgumentListTree;
import com.google.javascript.jscomp.parsing.parser.trees.ArrayLiteralExpressionTree;
import com.google.javascript.jscomp.parsing.parser.trees.ArrayPatternTree;
import com.google.javascript.jscomp.parsing.parser.trees.ArrayTypeTree;
import com.google.javascript.jscomp.parsing.parser.trees.AssignmentRestElementTree;
import com.google.javascript.jscomp.parsing.parser.trees.AwaitExpressionTree;
import com.google.javascript.jscomp.parsing.parser.trees.BinaryOperatorTree;
import com.google.javascript.jscomp.parsing.parser.trees.BlockTree;
import com.google.javascript.jscomp.parsing.parser.trees.BreakStatementTree;
import com.google.javascript.jscomp.parsing.parser.trees.CallExpressionTree;
import com.google.javascript.jscomp.parsing.parser.trees.CallSignatureTree;
import com.google.javascript.jscomp.parsing.parser.trees.CaseClauseTree;
import com.google.javascript.jscomp.parsing.parser.trees.CatchTree;
import com.google.javascript.jscomp.parsing.parser.trees.ClassDeclarationTree;
import com.google.javascript.jscomp.parsing.parser.trees.CommaExpressionTree;
import com.google.javascript.jscomp.parsing.parser.trees.Comment;
import com.google.javascript.jscomp.parsing.parser.trees.ComprehensionForTree;
import com.google.javascript.jscomp.parsing.parser.trees.ComprehensionIfTree;
import com.google.javascript.jscomp.parsing.parser.trees.ComprehensionTree;
import com.google.javascript.jscomp.parsing.parser.trees.ComputedPropertyDefinitionTree;
import com.google.javascript.jscomp.parsing.parser.trees.ComputedPropertyGetterTree;
import com.google.javascript.jscomp.parsing.parser.trees.ComputedPropertyMemberVariableTree;
import com.google.javascript.jscomp.parsing.parser.trees.ComputedPropertyMethodTree;
import com.google.javascript.jscomp.parsing.parser.trees.ComputedPropertySetterTree;
import com.google.javascript.jscomp.parsing.parser.trees.ConditionalExpressionTree;
import com.google.javascript.jscomp.parsing.parser.trees.ContinueStatementTree;
import com.google.javascript.jscomp.parsing.parser.trees.DebuggerStatementTree;
import com.google.javascript.jscomp.parsing.parser.trees.DefaultClauseTree;
import com.google.javascript.jscomp.parsing.parser.trees.DefaultParameterTree;
import com.google.javascript.jscomp.parsing.parser.trees.DoWhileStatementTree;
import com.google.javascript.jscomp.parsing.parser.trees.EmptyStatementTree;
import com.google.javascript.jscomp.parsing.parser.trees.EnumDeclarationTree;
import com.google.javascript.jscomp.parsing.parser.trees.ExportDeclarationTree;
import com.google.javascript.jscomp.parsing.parser.trees.ExportSpecifierTree;
import com.google.javascript.jscomp.parsing.parser.trees.ExpressionStatementTree;
import com.google.javascript.jscomp.parsing.parser.trees.FinallyTree;
import com.google.javascript.jscomp.parsing.parser.trees.ForInStatementTree;
import com.google.javascript.jscomp.parsing.parser.trees.ForOfStatementTree;
import com.google.javascript.jscomp.parsing.parser.trees.ForStatementTree;
import com.google.javascript.jscomp.parsing.parser.trees.FormalParameterListTree;
import com.google.javascript.jscomp.parsing.parser.trees.FunctionDeclarationTree;
import com.google.javascript.jscomp.parsing.parser.trees.FunctionTypeTree;
import com.google.javascript.jscomp.parsing.parser.trees.GenericTypeListTree;
import com.google.javascript.jscomp.parsing.parser.trees.GetAccessorTree;
import com.google.javascript.jscomp.parsing.parser.trees.IdentifierExpressionTree;
import com.google.javascript.jscomp.parsing.parser.trees.IfStatementTree;
import com.google.javascript.jscomp.parsing.parser.trees.ImportDeclarationTree;
import com.google.javascript.jscomp.parsing.parser.trees.ImportSpecifierTree;
import com.google.javascript.jscomp.parsing.parser.trees.IndexSignatureTree;
import com.google.javascript.jscomp.parsing.parser.trees.InterfaceDeclarationTree;
import com.google.javascript.jscomp.parsing.parser.trees.LabelledStatementTree;
import com.google.javascript.jscomp.parsing.parser.trees.LiteralExpressionTree;
import com.google.javascript.jscomp.parsing.parser.trees.MemberExpressionTree;
import com.google.javascript.jscomp.parsing.parser.trees.MemberLookupExpressionTree;
import com.google.javascript.jscomp.parsing.parser.trees.MemberVariableTree;
import com.google.javascript.jscomp.parsing.parser.trees.MissingPrimaryExpressionTree;
import com.google.javascript.jscomp.parsing.parser.trees.NamespaceDeclarationTree;
import com.google.javascript.jscomp.parsing.parser.trees.NamespaceNameTree;
import com.google.javascript.jscomp.parsing.parser.trees.NewExpressionTree;
import com.google.javascript.jscomp.parsing.parser.trees.NewTargetExpressionTree;
import com.google.javascript.jscomp.parsing.parser.trees.NullTree;
import com.google.javascript.jscomp.parsing.parser.trees.ObjectLiteralExpressionTree;
import com.google.javascript.jscomp.parsing.parser.trees.ObjectPatternTree;
import com.google.javascript.jscomp.parsing.parser.trees.OptionalParameterTree;
import com.google.javascript.jscomp.parsing.parser.trees.ParameterizedTypeTree;
import com.google.javascript.jscomp.parsing.parser.trees.ParenExpressionTree;
import com.google.javascript.jscomp.parsing.parser.trees.ParseTree;
import com.google.javascript.jscomp.parsing.parser.trees.ParseTreeType;
import com.google.javascript.jscomp.parsing.parser.trees.ProgramTree;
import com.google.javascript.jscomp.parsing.parser.trees.PropertyNameAssignmentTree;
import com.google.javascript.jscomp.parsing.parser.trees.RecordTypeTree;
import com.google.javascript.jscomp.parsing.parser.trees.RestParameterTree;
import com.google.javascript.jscomp.parsing.parser.trees.ReturnStatementTree;
import com.google.javascript.jscomp.parsing.parser.trees.SetAccessorTree;
import com.google.javascript.jscomp.parsing.parser.trees.SpreadExpressionTree;
import com.google.javascript.jscomp.parsing.parser.trees.SuperExpressionTree;
import com.google.javascript.jscomp.parsing.parser.trees.SwitchStatementTree;
import com.google.javascript.jscomp.parsing.parser.trees.TemplateLiteralExpressionTree;
import com.google.javascript.jscomp.parsing.parser.trees.TemplateLiteralPortionTree;
import com.google.javascript.jscomp.parsing.parser.trees.TemplateSubstitutionTree;
import com.google.javascript.jscomp.parsing.parser.trees.ThisExpressionTree;
import com.google.javascript.jscomp.parsing.parser.trees.ThrowStatementTree;
import com.google.javascript.jscomp.parsing.parser.trees.TryStatementTree;
import com.google.javascript.jscomp.parsing.parser.trees.TypeAliasTree;
import com.google.javascript.jscomp.parsing.parser.trees.TypeNameTree;
import com.google.javascript.jscomp.parsing.parser.trees.TypeQueryTree;
import com.google.javascript.jscomp.parsing.parser.trees.TypedParameterTree;
import com.google.javascript.jscomp.parsing.parser.trees.UnaryExpressionTree;
import com.google.javascript.jscomp.parsing.parser.trees.UnionTypeTree;
import com.google.javascript.jscomp.parsing.parser.trees.UpdateExpressionTree;
import com.google.javascript.jscomp.parsing.parser.trees.VariableDeclarationListTree;
import com.google.javascript.jscomp.parsing.parser.trees.VariableDeclarationTree;
import com.google.javascript.jscomp.parsing.parser.trees.VariableStatementTree;
import com.google.javascript.jscomp.parsing.parser.trees.WhileStatementTree;
import com.google.javascript.jscomp.parsing.parser.trees.WithStatementTree;
import com.google.javascript.jscomp.parsing.parser.trees.YieldExpressionTree;
import com.google.javascript.jscomp.parsing.parser.util.ErrorReporter;
import com.google.javascript.jscomp.parsing.parser.util.LookaheadErrorReporter;
import com.google.javascript.jscomp.parsing.parser.util.LookaheadErrorReporter.ParseException;
import com.google.javascript.jscomp.parsing.parser.util.SourcePosition;
import com.google.javascript.jscomp.parsing.parser.util.SourceRange;
import com.google.javascript.jscomp.parsing.parser.util.Timer;
import java.util.ArrayDeque;
import java.util.LinkedHashMap;
import java.util.List;
import javax.annotation.Nullable;
/**
* Parses a javascript file.
*
* <p>The various parseX() methods never return null - even when parse errors are encountered.
* Typically parseX() will return a XTree ParseTree. Each ParseTree that is created includes its
* source location. The typical pattern for a parseX() method is:
*
* <pre>
* XTree parseX() {
* SourcePosition start = getTreeStartLocation();
* parse X grammar element and its children
* return new XTree(getTreeLocation(start), children);
* }
* </pre>
*
* <p>parseX() methods must consume at least 1 token - even in error cases. This prevents infinite
* loops in the parser.
*
* <p>Many parseX() methods are matched by a 'boolean peekX()' method which will return true if
* the beginning of an X appears at the current location. There are also peek() methods which
* examine the next token. peek() methods must not consume any tokens.
*
* <p>The eat() method consumes a token and reports an error if the consumed token is not of the
* expected type. The eatOpt() methods consume the next token iff the next token is of the expected
* type and return the consumed token or null if no token was consumed.
*
* <p>When parse errors are encountered, an error should be reported and the parse should return a
* best guess at the current parse tree.
*
* <p>When parsing lists, the preferred pattern is:
* <pre>
* eat(LIST_START);
* ImmutableList.Builder<ParseTree> elements = ImmutableList.builder();
* while (peekListElement()) {
* elements.add(parseListElement());
* }
* eat(LIST_END);
* </pre>
*/
public class Parser {
/**
* Indicates the type of function currently being parsed.
*/
private enum FunctionFlavor {
NORMAL, GENERATOR, ASYNCHRONOUS;
}
private final Scanner scanner;
private final ErrorReporter errorReporter;
private final Config config;
private final CommentRecorder commentRecorder = new CommentRecorder();
private final ArrayDeque<FunctionFlavor> functionContextStack = new ArrayDeque<>();
private FeatureSet features = FeatureSet.BARE_MINIMUM;
private SourcePosition lastSourcePosition;
@Nullable private String sourceMapURL;
public Parser(
Config config,
ErrorReporter errorReporter,
SourceFile source,
int offset,
boolean initialGeneratorContext) {
this.config = config;
this.errorReporter = errorReporter;
this.scanner = new Scanner(errorReporter, commentRecorder, source, offset);
this.functionContextStack.addLast(
initialGeneratorContext ? FunctionFlavor.GENERATOR : FunctionFlavor.NORMAL);
lastSourcePosition = scanner.getPosition();
}
public Parser(Config config, ErrorReporter errorReporter, SourceFile source, int offset) {
this(config, errorReporter, source, offset, false);
}
public Parser(Config config, ErrorReporter errorReporter, SourceFile source) {
this(config, errorReporter, source, 0);
}
public static class Config {
public static enum Mode {
ES3,
ES5,
ES6,
ES7,
ES8_OR_GREATER,
TYPESCRIPT,
}
/**
* Indicates that the parser should look for TypeScript-like data type syntax.
*/
// TODO(bradfordcsmith): Make sure all of the type syntax handling code is avoided when
// this is false.
private final boolean parseTypeSyntax;
private final boolean atLeast6;
private final boolean atLeast8;
private final boolean isStrictMode;
private final boolean warnTrailingCommas;
public Config() {
this(Mode.ES8_OR_GREATER, /* isStrictMode */ false);
}
public Config(Mode mode, boolean isStrictMode) {
parseTypeSyntax = mode == Mode.TYPESCRIPT;
atLeast6 = !(mode == Mode.ES3 || mode == Mode.ES5);
atLeast8 = mode == Mode.ES8_OR_GREATER;
this.isStrictMode = isStrictMode;
// Generally, we allow everything that is valid in any mode
// we only warn about things that are not represented in the AST.
this.warnTrailingCommas = mode == Mode.ES3;
}
}
private static final String SOURCE_MAPPING_URL_PREFIX = "//# sourceMappingURL=";
private class CommentRecorder implements Scanner.CommentRecorder {
private final ImmutableList.Builder<Comment> comments = ImmutableList.builder();
@Override
public void recordComment(Comment.Type type, SourceRange range, String value) {
value = value.trim();
if (value.startsWith(SOURCE_MAPPING_URL_PREFIX)) {
sourceMapURL = value.substring(SOURCE_MAPPING_URL_PREFIX.length());
}
comments.add(new Comment(value, range, type));
}
private ImmutableList<Comment> getComments() {
return comments.build();
}
}
public List<Comment> getComments() {
return commentRecorder.getComments();
}
public FeatureSet getFeatures() {
return features;
}
/** Returns the url provided by the sourceMappingURL if any was found. */
@Nullable
public String getSourceMapURL() {
return sourceMapURL;
}
// 14 Program
public ProgramTree parseProgram() {
Timer t = new Timer("Parse Program");
try {
SourcePosition start = getTreeStartLocation();
ImmutableList<ParseTree> sourceElements = parseGlobalSourceElements();
eat(TokenType.END_OF_FILE);
t.end();
return new ProgramTree(
getTreeLocation(start), sourceElements, commentRecorder.getComments());
} catch (StackOverflowError e) {
reportError("Too deep recursion while parsing");
return null;
}
}
private ImmutableList<ParseTree> parseGlobalSourceElements() {
ImmutableList.Builder<ParseTree> result = ImmutableList.builder();
while (!peek(TokenType.END_OF_FILE)) {
result.add(parseScriptElement());
}
return result.build();
}
private ImmutableList<ParseTree> parseNamespaceElements() {
ImmutableList.Builder<ParseTree> result = ImmutableList.builder();
while (!peek(TokenType.CLOSE_CURLY) && !peek(TokenType.END_OF_FILE)) {
result.add(parseScriptElement());
}
return result.build();
}
private ImmutableList<ParseTree> parseAmbientNamespaceElements() {
ImmutableList.Builder<ParseTree> result = ImmutableList.builder();
while (peekAmbientNamespaceElement()) {
result.add(parseAmbientNamespaceElement());
}
return result.build();
}
// ImportDeclaration
// ExportDeclaration
// TypeScript InterfaceDeclaration
// TypeScript EnumDeclaration
// TypeScript TypeAlias
// TypeScript AmbientDeclaration
// SourceElement
private ParseTree parseScriptElement() {
if (peekImportDeclaration()) {
return parseImportDeclaration();
}
if (peekExportDeclaration()) {
return parseExportDeclaration(false);
}
if (peekInterfaceDeclaration()) {
return parseInterfaceDeclaration();
}
if (peekEnumDeclaration()) {
return parseEnumDeclaration();
}
if (peekTypeAlias()) {
return parseTypeAlias();
}
if (peekAmbientDeclaration()) {
return parseAmbientDeclaration();
}
if (peekNamespaceDeclaration()) {
return parseNamespaceDeclaration(false);
}
return parseSourceElement();
}
private ParseTree parseAmbientNamespaceElement() {
if (peekInterfaceDeclaration()) {
return parseInterfaceDeclaration();
}
if (peekExportDeclaration()) {
return parseExportDeclaration(true);
}
return parseAmbientDeclarationHelper();
}
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-imports
private boolean peekImportDeclaration() {
return peek(TokenType.IMPORT);
}
private ParseTree parseImportDeclaration() {
SourcePosition start = getTreeStartLocation();
eat(TokenType.IMPORT);
// import ModuleSpecifier ;
if (peek(TokenType.STRING)) {
LiteralToken moduleSpecifier = eat(TokenType.STRING).asLiteral();
eatPossibleImplicitSemiColon();
return new ImportDeclarationTree(
getTreeLocation(start), null, null, null, moduleSpecifier);
}
// import ImportedDefaultBinding from ModuleSpecifier
// import NameSpaceImport from ModuleSpecifier
// import NamedImports from ModuleSpecifier ;
// import ImportedDefaultBinding , NameSpaceImport from ModuleSpecifier ;
// import ImportedDefaultBinding , NamedImports from ModuleSpecifier ;
IdentifierToken defaultBindingIdentifier = null;
IdentifierToken nameSpaceImportIdentifier = null;
ImmutableList<ParseTree> identifierSet = null;
boolean parseExplicitNames = true;
if (peekId()) {
defaultBindingIdentifier = eatId();
if (peek(TokenType.COMMA)) {
eat(TokenType.COMMA);
} else {
parseExplicitNames = false;
}
} else if (Keywords.isKeyword(peekType())) {
Token keyword = nextToken();
reportError(keyword, "cannot use keyword '%s' here.", keyword);
}
if (parseExplicitNames) {
if (peek(TokenType.STAR)) {
eat(TokenType.STAR);
eatPredefinedString(PredefinedName.AS);
nameSpaceImportIdentifier = eatId();
} else {
identifierSet = parseImportSpecifierSet();
}
}
eatPredefinedString(PredefinedName.FROM);
Token moduleStr = eat(TokenType.STRING);
LiteralToken moduleSpecifier = (moduleStr == null)
? null : moduleStr.asLiteral();
eatPossibleImplicitSemiColon();
return new ImportDeclarationTree(
getTreeLocation(start),
defaultBindingIdentifier, identifierSet, nameSpaceImportIdentifier, moduleSpecifier);
}
// ImportSpecifierSet ::= '{' (ImportSpecifier (',' ImportSpecifier)* (,)? )? '}'
private ImmutableList<ParseTree> parseImportSpecifierSet() {
ImmutableList.Builder<ParseTree> elements;
elements = ImmutableList.builder();
eat(TokenType.OPEN_CURLY);
while (peekIdOrKeyword()) {
elements.add(parseImportSpecifier());
if (!peek(TokenType.CLOSE_CURLY)) {
eat(TokenType.COMMA);
}
}
eat(TokenType.CLOSE_CURLY);
return elements.build();
}
// ImportSpecifier ::= Identifier ('as' Identifier)?
private ParseTree parseImportSpecifier() {
SourcePosition start = getTreeStartLocation();
IdentifierToken importedName = eatIdOrKeywordAsId();
IdentifierToken destinationName = null;
if (peekPredefinedString(PredefinedName.AS)) {
eatPredefinedString(PredefinedName.AS);
destinationName = eatId();
} else if (Keywords.isKeyword(importedName.value)) {
reportExpectedError(null, PredefinedName.AS);
}
return new ImportSpecifierTree(
getTreeLocation(start), importedName, destinationName);
}
// export VariableStatement
// export FunctionDeclaration
// export ConstStatement
// export ClassDeclaration
// export default expression
// etc
private boolean peekExportDeclaration() {
return peek(TokenType.EXPORT);
}
/*
ExportDeclaration :
export * FromClause ;
export ExportClause [NoReference] FromClause ;
export ExportClause ;
export VariableStatement
export Declaration[Default]
export default AssignmentExpression ;
ExportClause [NoReference] :
{ }
{ ExportsList [?NoReference] }
{ ExportsList [?NoReference] , }
ExportsList [NoReference] :
ExportSpecifier [?NoReference]
ExportsList [?NoReference] , ExportSpecifier [?NoReference]
ExportSpecifier [NoReference] :
[~NoReference] IdentifierReference
[~NoReference] IdentifierReference as IdentifierName
[+NoReference] IdentifierName
[+NoReference] IdentifierName as IdentifierName
*/
private ParseTree parseExportDeclaration(boolean isAmbient) {
SourcePosition start = getTreeStartLocation();
boolean isDefault = false;
boolean isExportAll = false;
boolean isExportSpecifier = false;
boolean needsSemiColon = true;
eat(TokenType.EXPORT);
ParseTree export = null;
ImmutableList<ParseTree> exportSpecifierList = null;
switch (peekType()) {
case STAR:
isExportAll = true;
nextToken();
break;
case FUNCTION:
// TODO(bradfordcsmith): handle async functions here
export = isAmbient ? parseAmbientFunctionDeclaration() : parseFunctionDeclaration();
needsSemiColon = isAmbient;
break;
case CLASS:
export = parseClassDeclaration(isAmbient);
needsSemiColon = false;
break;
case INTERFACE:
export = parseInterfaceDeclaration();
needsSemiColon = false;
break;
case ENUM:
export = parseEnumDeclaration();
needsSemiColon = false;
break;
case MODULE:
case NAMESPACE:
export = parseNamespaceDeclaration(isAmbient);
needsSemiColon = false;
break;
case DECLARE:
export = parseAmbientDeclaration();
needsSemiColon = false;
break;
case DEFAULT:
isDefault = true;
nextToken();
export = parseExpression();
needsSemiColon = false;
break;
case OPEN_CURLY:
isExportSpecifier = true;
exportSpecifierList = parseExportSpecifierSet();
break;
case TYPE:
export = parseTypeAlias();
break;
default: // unreachable, parse as a var decl to get a parse error.
case VAR:
case LET:
case CONST:
export = isAmbient ? parseAmbientVariableDeclarationList() : parseVariableDeclarationList();
break;
}
LiteralToken moduleSpecifier = null;
if (isExportAll || (isExportSpecifier && peekPredefinedString(PredefinedName.FROM))) {
eatPredefinedString(PredefinedName.FROM);
moduleSpecifier = (LiteralToken) eat(TokenType.STRING);
} else if (isExportSpecifier) {
for (ParseTree tree : exportSpecifierList) {
IdentifierToken importedName = tree.asExportSpecifier().importedName;
if (Keywords.isKeyword(importedName.value)) {
reportError(importedName, "cannot use keyword '%s' here.", importedName.value);
}
}
}
if (needsSemiColon || peekImplicitSemiColon()) {
eatPossibleImplicitSemiColon();
}
return new ExportDeclarationTree(
getTreeLocation(start), isDefault, isExportAll,
export, exportSpecifierList, moduleSpecifier);
}
// ExportSpecifierSet ::= '{' (ExportSpecifier (',' ExportSpecifier)* (,)? )? '}'
private ImmutableList<ParseTree> parseExportSpecifierSet() {
ImmutableList.Builder<ParseTree> elements;
elements = ImmutableList.builder();
eat(TokenType.OPEN_CURLY);
while (peekIdOrKeyword()) {
elements.add(parseExportSpecifier());
if (!peek(TokenType.CLOSE_CURLY)) {
eat(TokenType.COMMA);
}
}
eat(TokenType.CLOSE_CURLY);
return elements.build();
}
// ExportSpecifier ::= Identifier ('as' Identifier)?
private ParseTree parseExportSpecifier() {
SourcePosition start = getTreeStartLocation();
IdentifierToken importedName = eatIdOrKeywordAsId();
IdentifierToken destinationName = null;
if (peekPredefinedString(PredefinedName.AS)) {
eatPredefinedString(PredefinedName.AS);
destinationName = eatIdOrKeywordAsId();
}
return new ExportSpecifierTree(
getTreeLocation(start), importedName, destinationName);
}
private boolean peekClassDeclaration() {
return peek(TokenType.CLASS);
}
private boolean peekInterfaceDeclaration() {
return peek(TokenType.INTERFACE);
}
private boolean peekEnumDeclaration() {
return peek(TokenType.ENUM);
}
private boolean peekNamespaceDeclaration() {
return (peek(TokenType.MODULE) || peek(TokenType.NAMESPACE))
&& !peekImplicitSemiColon(1) && peek(1, TokenType.IDENTIFIER);
}
private ParseTree parseClassDeclaration(boolean isAmbient) {
return parseClass(false, isAmbient);
}
private ParseTree parseClassExpression() {
return parseClass(true, false);
}
private ParseTree parseInterfaceDeclaration() {
SourcePosition start = getTreeStartLocation();
eat(TokenType.INTERFACE);
IdentifierToken name = eatId();
GenericTypeListTree generics = maybeParseGenericTypes();
ImmutableList.Builder<ParseTree> superTypes = ImmutableList.builder();
if (peek(TokenType.EXTENDS)) {
eat(TokenType.EXTENDS);
ParseTree type = parseType();
superTypes.add(type);
while (peek(TokenType.COMMA)) {
eat(TokenType.COMMA);
type = parseType();
if (type != null) {
superTypes.add(type);
}
}
}
eat(TokenType.OPEN_CURLY);
ImmutableList<ParseTree> elements = parseInterfaceElements();
eat(TokenType.CLOSE_CURLY);
return new InterfaceDeclarationTree(getTreeLocation(start), name, generics,
superTypes.build(), elements);
}
private ImmutableList<ParseTree> parseInterfaceElements() {
ImmutableList.Builder<ParseTree> result = ImmutableList.builder();
while (peekInterfaceElement()) {
result.add(parseInterfaceElement());
if (!peek(TokenType.CLOSE_CURLY)) {
// The standard delimiter is semicolon, but we also accept comma
if (peekImplicitSemiColon()) {
eatPossibleImplicitSemiColon();
} else {
eat(TokenType.COMMA);
}
}
}
return result.build();
}
private boolean peekInterfaceElement() {
Token token = peekToken();
switch (token.type) {
case NEW:
case IDENTIFIER:
case OPEN_SQUARE:
case STAR:
case OPEN_ANGLE:
case OPEN_PAREN:
return true;
default:
return Keywords.isKeyword(token.type);
}
}
private ParseTree parseInterfaceElement() {
SourcePosition start = getTreeStartLocation();
boolean isGenerator = eatOpt(TokenType.STAR) != null;
IdentifierToken name = null;
TokenType type = peekType();
if (type == TokenType.NEW) {
return parseCallSignature(true); // ConstructSignature
} else if (type == TokenType.IDENTIFIER || Keywords.isKeyword(type)) {
name = eatIdOrKeywordAsId();
} else if (type == TokenType.OPEN_SQUARE) { // IndexSignature
return parseIndexSignature();
} else if (type == TokenType.OPEN_ANGLE || type == TokenType.OPEN_PAREN) { // CallSignature
return parseCallSignature(false);
}
boolean isOptional = false;
if (peek(TokenType.QUESTION)) {
eat(TokenType.QUESTION);
isOptional = true;
}
if (peek(TokenType.OPEN_PAREN) || peek(TokenType.OPEN_ANGLE)) {
// Method signature.
ParseTree function = parseMethodSignature(
start, name, false, isGenerator, isOptional, null);
return function;
} else {
// Property signature.
ParseTree declaredType = maybeParseColonType();
return new MemberVariableTree(
getTreeLocation(start), name, false, isOptional, null, declaredType);
}
}
private ParseTree parseEnumDeclaration() {
SourcePosition start = getTreeStartLocation();
eat(TokenType.ENUM);
IdentifierToken name = eatId();
eat(TokenType.OPEN_CURLY);
ImmutableList<ParseTree> members = parseEnumMembers();
eat(TokenType.CLOSE_CURLY);
return new EnumDeclarationTree(getTreeLocation(start), name, members);
}
private ImmutableList<ParseTree> parseEnumMembers() {
SourceRange range = getTreeLocation(getTreeStartLocation());
IdentifierToken propertyName;
ParseTree member = null;
ImmutableList.Builder<ParseTree> result = ImmutableList.builder();
while (peekId()) {
propertyName = parseIdentifierExpression().identifierToken;
member = new PropertyNameAssignmentTree(range, propertyName, null);
result.add(member);
if (!peek(TokenType.CLOSE_CURLY)) {
eat(TokenType.COMMA);
}
}
return result.build();
}
private ParseTree parseClass(boolean isExpression, boolean isAmbient) {
SourcePosition start = getTreeStartLocation();
eat(TokenType.CLASS);
IdentifierToken name = null;
if (!isExpression || peekId()) {
name = eatId();
}
GenericTypeListTree generics = maybeParseGenericTypes();
ParseTree superClass = null;
if (peek(TokenType.EXTENDS)) {
eat(TokenType.EXTENDS);
superClass = parseExpression();
}
ImmutableList.Builder<ParseTree> interfaces = ImmutableList.builder();
if (config.parseTypeSyntax && peek(TokenType.IMPLEMENTS)) {
eat(TokenType.IMPLEMENTS);
ParseTree type = parseType();
interfaces.add(type);
while (peek(TokenType.COMMA)) {
eat(TokenType.COMMA);
type = parseType();
if (type != null) {
interfaces.add(type);
}
}
}
eat(TokenType.OPEN_CURLY);
ImmutableList<ParseTree> elements = parseClassElements(isAmbient);
eat(TokenType.CLOSE_CURLY);
return new ClassDeclarationTree(getTreeLocation(start), name, generics,
superClass, interfaces.build(), elements);
}
private ImmutableList<ParseTree> parseClassElements(boolean isAmbient) {
ImmutableList.Builder<ParseTree> result = ImmutableList.builder();
while (peekClassElement()) {
result.add(parseClassElement(isAmbient));
}
return result.build();
}
private boolean peekClassElement() {
Token token = peekToken();
switch (token.type) {
case IDENTIFIER:
case STAR:
case STATIC:
case OPEN_SQUARE:
case SEMI_COLON:
return true;
default:
return Keywords.isKeyword(token.type);
}
}
private static class PartialClassElement {
final SourcePosition start;
boolean isAmbient = false;
boolean isStatic = false;
TokenType accessModifier = null;
PartialClassElement(SourcePosition start) {
this.start = start;
}
}
private PartialClassElement getClassElementDefaults() {
return new PartialClassElement(getTreeStartLocation());
}
private ParseTree parseClassElement(boolean isAmbient) {
if (peek(TokenType.SEMI_COLON)) {
return parseEmptyStatement();
} else {
PartialClassElement partialElement = getClassElementDefaults();
partialElement.isAmbient = isAmbient;
partialElement.accessModifier = maybeParseAccessibilityModifier();
partialElement.isStatic = eatOpt(TokenType.STATIC) != null;
return parseClassElement(partialElement);
}
}
private ParseTree parseClassElement(PartialClassElement partialElement) {
if (peekGetAccessor()) {
return parseGetAccessor(partialElement);
} else if (peekSetAccessor()) {
return parseSetAccessor(partialElement);
} else if (peekAsyncMethod()) {
return parseAsyncMethod(partialElement);
} else {
return parseClassMemberDeclaration(partialElement);
}
}
private boolean peekAsyncMethod() {
return peekPredefinedString(ASYNC)
&& !peekImplicitSemiColon(1)
&& peekPropertyNameOrComputedProp(1);
}
private ParseTree parseClassMemberDeclaration() {
return parseClassMemberDeclaration(getClassElementDefaults());
}
private ParseTree parseClassMemberDeclaration(PartialClassElement partial) {
boolean isGenerator = eatOpt(TokenType.STAR) != null;
ParseTree nameExpr;
IdentifierToken name;
if (peekIdOrKeyword()) {
nameExpr = null;
name = eatIdOrKeywordAsId();
if (Keywords.isKeyword(name.value)) {
features = features.with(Feature.KEYWORDS_AS_PROPERTIES);
}
} else {
if (config.parseTypeSyntax && peekIndexSignature()) {
ParseTree indexSignature = parseIndexSignature();
eatPossibleImplicitSemiColon();
return indexSignature;
}
nameExpr = parseComputedPropertyName();
name = null;
}
// Member variables are supported only when parsing type syntax
if (!config.parseTypeSyntax || peek(TokenType.OPEN_PAREN) || peek(TokenType.OPEN_ANGLE)) {
// Member function.
FunctionDeclarationTree.Kind kind;
TokenType accessOnFunction;
if (nameExpr == null) {
kind = FunctionDeclarationTree.Kind.MEMBER;
accessOnFunction = partial.accessModifier;
} else {
kind = FunctionDeclarationTree.Kind.EXPRESSION;
accessOnFunction = null; // Accessibility modifier goes on the ComputedPropertyMethodTree
}
ParseTree function;
if (partial.isAmbient) {
function = parseMethodSignature(partial, name, isGenerator, /* isOptional */ false);
eatPossibleImplicitSemiColon();
} else {
FunctionDeclarationTree.Builder builder =
FunctionDeclarationTree.builder(kind)
.setName(name)
.setStatic(partial.isStatic)
.setAccess(accessOnFunction);
parseFunctionTail(builder, isGenerator ? FunctionFlavor.GENERATOR : FunctionFlavor.NORMAL);
function = builder.build(getTreeLocation(partial.start));
}
if (kind == FunctionDeclarationTree.Kind.MEMBER) {
return function;
} else {
return new ComputedPropertyMethodTree(
getTreeLocation(partial.start), partial.accessModifier, nameExpr, function);
}
} else {
// Member variable.
if (isGenerator) {
reportError("Member variable cannot be prefixed by '*' (generator function)");
}
ParseTree declaredType = maybeParseColonType();
if (peek(TokenType.EQUAL)) {
reportError("Member variable initializers ('=') are not supported");
}
eatPossibleImplicitSemiColon();
if (nameExpr == null) {
return new MemberVariableTree(
getTreeLocation(partial.start),
name,
partial.isStatic,
false,
partial.accessModifier,
declaredType);
} else {
return new ComputedPropertyMemberVariableTree(
getTreeLocation(partial.start),
nameExpr,
partial.isStatic,
partial.accessModifier,
declaredType);
}
}
}
private ParseTree parseAsyncMethod() {
return parseAsyncMethod(getClassElementDefaults());
}
private ParseTree parseAsyncMethod(PartialClassElement partial) {
eatPredefinedString(ASYNC);
if (peekIdOrKeyword()) {
IdentifierToken name = eatIdOrKeywordAsId();
FunctionDeclarationTree.Builder builder =
FunctionDeclarationTree.builder(FunctionDeclarationTree.Kind.MEMBER)
.setAsync(true)
.setStatic(partial.isStatic)
.setName(name)
.setAccess(partial.accessModifier);
if (partial.isAmbient) {
builder
.setGenerics(maybeParseGenericTypes())
.setFormalParameterList(parseFormalParameterList(ParamContext.SIGNATURE))
.setReturnType(maybeParseColonType())
.setFunctionBody(new EmptyStatementTree(getTreeLocation(partial.start)));
eatPossibleImplicitSemiColon();
} else {
parseFunctionTail(builder, FunctionFlavor.ASYNCHRONOUS);
}
return builder.build(getTreeLocation(name.getStart()));
} else if (config.parseTypeSyntax && peekIndexSignature()) {
ParseTree indexSignature = parseIndexSignature();
eatPossibleImplicitSemiColon();
return indexSignature;
} else { // expect '[' to start computed property name
ParseTree nameExpr = parseComputedPropertyName();
FunctionDeclarationTree.Builder builder =
FunctionDeclarationTree.builder(FunctionDeclarationTree.Kind.EXPRESSION)
.setAsync(true)
.setStatic(partial.isStatic);
parseFunctionTail(builder, FunctionFlavor.ASYNCHRONOUS);
ParseTree function = builder.build(getTreeLocation(nameExpr.getStart()));
return new ComputedPropertyMethodTree(
getTreeLocation(nameExpr.getStart()), partial.accessModifier, nameExpr, function);
}
}
private FunctionDeclarationTree parseMethodSignature(
PartialClassElement partial, IdentifierToken name, boolean isGenerator, boolean isOptional) {
return parseMethodSignature(