-
-
Notifications
You must be signed in to change notification settings - Fork 667
/
parser.ts
4587 lines (4293 loc) · 131 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
/**
* @fileoverview A TypeScript parser for the AssemblyScript subset.
*
* Takes the tokens produced by the `Tokenizer` and builds an abstract
* syntax tree composed of `Node`s wrapped in a `Source` out of it.
*
* @license Apache-2.0
*/
import {
CommonFlags,
LIBRARY_PREFIX,
PATH_DELIMITER
} from "./common";
import {
Tokenizer,
Token,
CommentHandler,
IdentifierHandling,
isIllegalVariableIdentifier
} from "./tokenizer";
import {
Range,
DiagnosticCode,
DiagnosticEmitter,
DiagnosticMessage
} from "./diagnostics";
import {
CharCode,
normalizePath
} from "./util";
import {
Node,
NodeKind,
Source,
SourceKind,
TypeNode,
TypeName,
NamedTypeNode,
FunctionTypeNode,
ArrowKind,
Expression,
AssertionKind,
CallExpression,
ClassExpression,
FunctionExpression,
IdentifierExpression,
StringLiteralExpression,
Statement,
BlockStatement,
BreakStatement,
ClassDeclaration,
ContinueStatement,
DeclarationStatement,
DecoratorNode,
DoStatement,
EnumDeclaration,
EnumValueDeclaration,
ExportImportStatement,
ExportMember,
ExportStatement,
ExpressionStatement,
ForOfStatement,
FunctionDeclaration,
IfStatement,
ImportDeclaration,
ImportStatement,
IndexSignatureNode,
NamespaceDeclaration,
ParameterNode,
ParameterKind,
ReturnStatement,
SwitchCase,
SwitchStatement,
ThrowStatement,
TryStatement,
TypeDeclaration,
TypeParameterNode,
VariableStatement,
VariableDeclaration,
VoidStatement,
WhileStatement,
ModuleDeclaration,
mangleInternalPath
} from "./ast";
/** Represents a dependee. */
class Dependee {
constructor(
public source: Source,
public reportNode: Node
) {}
}
/** Parser interface. */
export class Parser extends DiagnosticEmitter {
/** Source file names to be requested next. */
backlog: string[] = new Array();
/** Source file names already seen, that is processed or backlogged. */
seenlog: Set<string> = new Set();
/** Source file names already completely processed. */
donelog: Set<string> = new Set();
/** Optional handler to intercept comments while tokenizing. */
onComment: CommentHandler | null = null;
/** Current file being parsed. */
currentSource: Source | null = null;
/** Map of dependees being depended upon by a source, by path. */
dependees: Map<string, Dependee> = new Map();
/** An array of parsed sources. */
sources: Source[];
/** Current overridden module name. */
currentModuleName: string | null = null;
/** Constructs a new parser. */
constructor(
diagnostics: DiagnosticMessage[] | null = null,
sources: Source[] = []
) {
super(diagnostics);
this.sources = sources;
}
/** Parses a file and adds its definitions to the program. */
parseFile(
/** Source text of the file, or `null` to indicate not found. */
text: string | null,
/** Normalized path of the file. */
path: string,
/** Whether this is an entry file. */
isEntry: bool
): void {
// the frontend gives us paths with file extensions
let normalizedPath = normalizePath(path);
let internalPath = mangleInternalPath(normalizedPath);
// check if already processed
if (this.donelog.has(internalPath)) return;
this.donelog.add(internalPath); // do not parse again
this.seenlog.add(internalPath); // do not request again
// check if this is an error
if (text == null) {
let dependees = this.dependees;
let dependee: Dependee | null = null;
if (dependees.has(internalPath)) dependee = assert(dependees.get(internalPath));
this.error(
DiagnosticCode.File_0_not_found,
dependee
? dependee.reportNode.range
: null,
path
);
return;
}
// create the source element
let source = new Source(
isEntry
? SourceKind.UserEntry
: path.startsWith(LIBRARY_PREFIX)
? path.indexOf(PATH_DELIMITER, LIBRARY_PREFIX.length) < 0
? SourceKind.LibraryEntry
: SourceKind.Library
: SourceKind.User,
normalizedPath,
text
);
this.sources.push(source);
this.currentSource = source;
this.currentModuleName = null;
// tokenize and parse
let tn = new Tokenizer(source, this.diagnostics);
tn.onComment = this.onComment;
let statements = source.statements;
while (!tn.skip(Token.EndOfFile)) {
let statement = this.parseTopLevelStatement(tn, null);
if (statement) {
statements.push(statement);
} else {
this.skipStatement(tn);
}
}
}
/** Parses a top-level statement. */
parseTopLevelStatement(
tn: Tokenizer,
namespace: NamespaceDeclaration | null = null
): Statement | null {
let flags = namespace ? namespace.flags & CommonFlags.Ambient : CommonFlags.None;
let startPos = -1;
// check decorators
let decorators: DecoratorNode[] | null = null;
while (tn.skip(Token.At)) {
if (startPos < 0) startPos = tn.tokenPos;
let decorator = this.parseDecorator(tn);
if (!decorator) {
this.skipStatement(tn);
continue;
}
if (!decorators) decorators = [decorator];
else decorators.push(decorator);
}
// check modifiers
let exportStart = 0;
let exportEnd = 0;
let defaultStart = 0;
let defaultEnd = 0;
if (tn.skip(Token.Export)) {
if (startPos < 0) startPos = tn.tokenPos;
flags |= CommonFlags.Export;
exportStart = tn.tokenPos;
exportEnd = tn.pos;
if (tn.skip(Token.Default)) {
defaultStart = tn.tokenPos;
defaultEnd = tn.pos;
}
}
let declareStart = 0;
let declareEnd = 0;
let contextIsAmbient = namespace != null && namespace.is(CommonFlags.Ambient);
if (tn.skip(Token.Declare)) {
if (contextIsAmbient) {
this.error(
DiagnosticCode.A_declare_modifier_cannot_be_used_in_an_already_ambient_context,
tn.range()
); // recoverable
} else {
if (startPos < 0) startPos = tn.tokenPos;
declareStart = startPos;
declareEnd = tn.pos;
flags |= CommonFlags.Declare | CommonFlags.Ambient;
}
} else if (contextIsAmbient) {
flags |= CommonFlags.Ambient;
}
// parse the statement
let statement: Statement | null = null;
// handle declarations
let first = tn.peek();
if (startPos < 0) startPos = tn.nextTokenPos;
switch (first) {
case Token.Const: {
tn.next();
flags |= CommonFlags.Const;
if (tn.skip(Token.Enum)) {
statement = this.parseEnum(tn, flags, decorators, startPos);
} else {
statement = this.parseVariable(tn, flags, decorators, startPos);
}
decorators = null;
break;
}
case Token.Let: flags |= CommonFlags.Let;
case Token.Var: {
tn.next();
statement = this.parseVariable(tn, flags, decorators, startPos);
decorators = null;
break;
}
case Token.Enum: {
tn.next();
statement = this.parseEnum(tn, flags, decorators, startPos);
decorators = null;
break;
}
case Token.Function: {
tn.next();
statement = this.parseFunction(tn, flags, decorators, startPos);
decorators = null;
break;
}
case Token.Abstract: {
let state = tn.mark();
tn.next();
let abstractStart = tn.tokenPos;
let abstractEnd = tn.pos;
if (tn.peekOnNewLine()) {
tn.reset(state);
statement = this.parseStatement(tn, true);
break;
}
let next = tn.peek();
if (next != Token.Class) {
if (next == Token.Interface) {
this.error(
DiagnosticCode._abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration,
tn.range(abstractStart, abstractEnd)
);
}
tn.reset(state);
statement = this.parseStatement(tn, true);
break;
} else {
tn.discard(state);
}
flags |= CommonFlags.Abstract;
// fall through
}
case Token.Class:
case Token.Interface: {
tn.next();
statement = this.parseClassOrInterface(tn, flags, decorators, startPos);
decorators = null;
break;
}
case Token.Namespace: {
let state = tn.mark();
tn.next();
if (tn.peek(IdentifierHandling.Prefer) == Token.Identifier) {
tn.discard(state);
statement = this.parseNamespace(tn, flags, decorators, startPos);
decorators = null;
} else {
tn.reset(state);
statement = this.parseStatement(tn, true);
}
break;
}
case Token.Import: {
tn.next();
flags |= CommonFlags.Import;
if (flags & CommonFlags.Export) {
statement = this.parseExportImport(tn, startPos);
} else {
statement = this.parseImport(tn);
}
break;
}
case Token.Type: { // also identifier
let state = tn.mark();
tn.next();
if (tn.peek(IdentifierHandling.Prefer) == Token.Identifier) {
tn.discard(state);
statement = this.parseTypeDeclaration(tn, flags, decorators, startPos);
decorators = null;
} else {
tn.reset(state);
statement = this.parseStatement(tn, true);
}
break;
}
case Token.Module: { // also identifier
let state = tn.mark();
tn.next();
if (tn.peek() == Token.StringLiteral && !tn.peekOnNewLine()) {
tn.discard(state);
statement = this.parseModuleDeclaration(tn, flags);
} else {
tn.reset(state);
statement = this.parseStatement(tn, true);
}
break;
}
default: {
// handle plain exports
if (flags & CommonFlags.Export) {
if (defaultEnd && tn.skipIdentifier(IdentifierHandling.Prefer)) {
if (declareEnd) {
this.error(
DiagnosticCode.An_export_assignment_cannot_have_modifiers,
tn.range(declareStart, declareEnd)
);
}
statement = this.parseExportDefaultAlias(tn, startPos, defaultStart, defaultEnd);
defaultStart = defaultEnd = 0; // consume
} else {
statement = this.parseExport(tn, startPos, (flags & CommonFlags.Declare) != 0);
}
// handle non-declaration statements
} else {
if (exportEnd) {
this.error(
DiagnosticCode._0_modifier_cannot_be_used_here,
tn.range(exportStart, exportEnd), "export"
); // recoverable
}
if (declareEnd) {
this.error(
DiagnosticCode._0_modifier_cannot_be_used_here,
tn.range(declareStart, declareEnd), "declare"
); // recoverable
}
if (namespace) {
this.error(
DiagnosticCode.Namespace_can_only_have_declarations,
tn.range(startPos)
);
} else {
statement = this.parseStatement(tn, true);
}
}
break;
}
}
// check for decorators that weren't consumed
if (decorators) {
for (let i = 0, k = decorators.length; i < k; ++i) {
this.error(
DiagnosticCode.Decorators_are_not_valid_here,
decorators[i].range
);
}
}
// check if this an `export default` declaration
if (defaultEnd && statement != null) {
switch (statement.kind) {
case NodeKind.EnumDeclaration:
case NodeKind.FunctionDeclaration:
case NodeKind.ClassDeclaration:
case NodeKind.InterfaceDeclaration:
case NodeKind.NamespaceDeclaration: {
return Node.createExportDefaultStatement(<DeclarationStatement>statement, tn.range(startPos, tn.pos));
}
default: {
this.error(
DiagnosticCode._0_modifier_cannot_be_used_here,
tn.range(defaultStart, defaultEnd), "default"
);
}
}
}
return statement;
}
/** Obtains the next file to parse. */
nextFile(): string | null {
let backlog = this.backlog;
return backlog.length ? assert(backlog.shift()) : null;
}
/** Obtains the path of the dependee of the given imported file. */
getDependee(dependent: string): string | null {
let dependees = this.dependees;
if (dependees.has(dependent)) {
let dependee = assert(dependees.get(dependent));
return dependee.source.internalPath;
}
return null;
}
/** Finishes parsing. */
finish(): void {
if (this.backlog.length) throw new Error("backlog is not empty");
this.backlog = [];
this.seenlog.clear();
this.donelog.clear();
this.dependees.clear();
}
// types
/** Parses a type name. */
parseTypeName(
tn: Tokenizer
): TypeName | null {
// at: Identifier ('.' Identifier)*
let first = Node.createSimpleTypeName(tn.readIdentifier(), tn.range());
let current = first;
while (tn.skip(Token.Dot)) {
if (tn.skip(Token.Identifier)) {
let next = Node.createSimpleTypeName(tn.readIdentifier(), tn.range());
current.next = next;
current = next;
} else {
this.error(
DiagnosticCode.Identifier_expected,
tn.range(tn.pos)
);
return null;
}
}
return first;
}
/** Parses a type. */
parseType(
tn: Tokenizer,
acceptParenthesized: bool = true,
suppressErrors: bool = false
): TypeNode | null {
// before: Type
// NOTE: this parses our limited subset
let token = tn.next();
let startPos = tn.tokenPos;
let type: TypeNode;
// '(' ...
if (token == Token.OpenParen) {
// '(' FunctionSignature ')'
let isInnerParenthesized = tn.skip(Token.OpenParen);
// FunctionSignature?
let signature = this.tryParseFunctionType(tn);
if (signature) {
if (isInnerParenthesized) {
if (!tn.skip(Token.CloseParen)) {
if (!suppressErrors) {
this.error(
DiagnosticCode._0_expected,
tn.range(), ")"
);
}
return null;
}
}
type = signature;
} else if (isInnerParenthesized || this.tryParseSignatureIsSignature) {
if (!suppressErrors) {
this.error(
DiagnosticCode.Unexpected_token,
tn.range()
);
}
return null;
// Type (',' Type)* ')'
} else if (acceptParenthesized) {
let innerType = this.parseType(tn, false, suppressErrors);
if (!innerType) return null;
if (!tn.skip(Token.CloseParen)) {
if (!suppressErrors) {
this.error(
DiagnosticCode._0_expected,
tn.range(tn.pos), ")"
);
}
return null;
}
type = innerType;
type.range.start = startPos;
type.range.end = tn.pos;
} else {
if (!suppressErrors) {
this.error(
DiagnosticCode.Unexpected_token,
tn.range()
);
}
return null;
}
// 'void'
} else if (token == Token.Void) {
type = Node.createNamedType(
Node.createSimpleTypeName("void", tn.range()), [], false, tn.range(startPos, tn.pos)
);
// 'this'
} else if (token == Token.This) {
type = Node.createNamedType(
Node.createSimpleTypeName("this", tn.range()), [], false, tn.range(startPos, tn.pos)
);
// 'true'
} else if (token == Token.True || token == Token.False) {
type = Node.createNamedType(
Node.createSimpleTypeName("bool", tn.range()), [], false, tn.range(startPos, tn.pos)
);
// 'null'
} else if (token == Token.Null) {
type = Node.createNamedType(
Node.createSimpleTypeName("null", tn.range()), [], false, tn.range(startPos, tn.pos)
);
// StringLiteral
} else if (token == Token.StringLiteral) {
tn.readString();
type = Node.createNamedType(
Node.createSimpleTypeName("string", tn.range()), [], false, tn.range(startPos, tn.pos)
);
// Identifier
} else if (token == Token.Identifier) {
let name = this.parseTypeName(tn);
if (!name) return null;
let parameters: TypeNode[] | null = null;
// Name<T>
if (tn.skip(Token.LessThan)) {
do {
let parameter = this.parseType(tn, true, suppressErrors);
if (!parameter) return null;
if (!parameters) parameters = [ parameter ];
else parameters.push(parameter);
} while (tn.skip(Token.Comma));
if (!tn.skip(Token.GreaterThan)) {
if (!suppressErrors) {
this.error(
DiagnosticCode._0_expected,
tn.range(tn.pos), ">"
);
}
return null;
}
}
if (!parameters) parameters = [];
type = Node.createNamedType(name, parameters, false, tn.range(startPos, tn.pos));
} else {
if (!suppressErrors) {
this.error(
DiagnosticCode.Type_expected,
tn.range()
);
}
return null;
}
// ... | type
while (tn.skip(Token.Bar)) {
let nextType = this.parseType(tn, true, false);
if (!nextType) return null;
let typeIsNull = type.kind == NodeKind.NamedType && (<NamedTypeNode>type).isNull;
let nextTypeIsNull = nextType.kind == NodeKind.NamedType && (<NamedTypeNode>nextType).isNull;
if (!typeIsNull && !nextTypeIsNull) {
if (!suppressErrors) {
this.error(
DiagnosticCode.Not_implemented_0, nextType.range, "union types"
);
}
return null;
} else if (nextTypeIsNull) {
type.isNullable = true;
type.range.end = nextType.range.end;
} else if (typeIsNull) {
nextType.range.start = type.range.start;
nextType.isNullable = true;
type = nextType;
} else {
// `null | null` still `null`
type.range.end = nextType.range.end;
}
}
// ... [][]
while (tn.skip(Token.OpenBracket)) {
let bracketStart = tn.tokenPos;
if (!tn.skip(Token.CloseBracket)) {
if (!suppressErrors) {
this.error(
DiagnosticCode._0_expected,
tn.range(), "]"
);
}
return null;
}
let bracketRange = tn.range(bracketStart, tn.pos);
// ...[] | null
let nullable = false;
if (tn.skip(Token.Bar)) {
if (tn.skip(Token.Null)) {
nullable = true;
} else {
if (!suppressErrors) {
this.error(
DiagnosticCode.Not_implemented_0,
tn.range(), "union types"
);
}
return null;
}
}
type = Node.createNamedType(
Node.createSimpleTypeName("Array", bracketRange),
[ type ],
nullable,
tn.range(startPos, tn.pos)
);
if (nullable) break;
}
return type;
}
// Indicates whether tryParseSignature determined that it is handling a Signature
private tryParseSignatureIsSignature: bool = false;
/** Parses a function type, as used in type declarations. */
tryParseFunctionType(
tn: Tokenizer
): FunctionTypeNode | null {
// at '(': ('...'? Identifier '?'? ':' Type (',' '...'? Identifier '?'? ':' Type)* )? ')' '=>' Type
let state = tn.mark();
let startPos = tn.tokenPos;
let parameters: ParameterNode[] | null = null;
let thisType: NamedTypeNode | null = null;
let isSignature: bool = false;
let firstParamNameNoType: IdentifierExpression | null = null;
let firstParamKind: ParameterKind = ParameterKind.Default;
if (tn.skip(Token.CloseParen)) {
isSignature = true;
tn.discard(state);
parameters = [];
} else {
isSignature = false; // not yet known
do {
let paramStart = -1;
let kind = ParameterKind.Default;
if (tn.skip(Token.Dot_Dot_Dot)) {
paramStart = tn.tokenPos;
isSignature = true;
tn.discard(state);
kind = ParameterKind.Rest;
}
if (tn.skip(Token.This)) {
if (paramStart < 0) paramStart = tn.tokenPos;
if (tn.skip(Token.Colon)) {
isSignature = true;
tn.discard(state);
let type = this.parseType(tn, false);
if (!type) return null;
if (type.kind != NodeKind.NamedType) {
this.error(
DiagnosticCode.Identifier_expected,
type.range
);
this.tryParseSignatureIsSignature = true;
return null;
}
thisType = <NamedTypeNode>type;
} else {
tn.reset(state);
this.tryParseSignatureIsSignature = false;
return null;
}
} else if (tn.skipIdentifier()) {
if (paramStart < 0) paramStart = tn.tokenPos;
let name = Node.createIdentifierExpression(tn.readIdentifier(), tn.range(tn.tokenPos, tn.pos));
if (tn.skip(Token.Question)) {
isSignature = true;
tn.discard(state);
if (kind == ParameterKind.Rest) {
this.error(
DiagnosticCode.A_rest_parameter_cannot_be_optional,
tn.range()
); // recoverable
} else {
kind = ParameterKind.Optional;
}
}
if (tn.skip(Token.Colon)) {
isSignature = true;
tn.discard(state);
let type = this.parseType(tn); // not suppressing errors because known
if (!type) {
this.tryParseSignatureIsSignature = isSignature;
return null;
}
let param = Node.createParameter(kind, name, type, null, tn.range(paramStart, tn.pos));
if (!parameters) parameters = [ param ];
else parameters.push(param);
} else {
if (!isSignature) {
if (tn.peek() == Token.Comma) {
isSignature = true;
tn.discard(state);
}
}
if (isSignature) {
let param = Node.createParameter(kind, name, Node.createOmittedType(tn.range(tn.pos)), null, tn.range(paramStart, tn.pos));
if (!parameters) parameters = [ param ];
else parameters.push(param);
this.error(
DiagnosticCode.Type_expected,
param.type.range
); // recoverable
} else if (!parameters) {
// on '(' Identifier ^',' we don't yet know whether this is a
// parenthesized or a function type, hence we have to delay the
// respective diagnostic until we know for sure.
firstParamNameNoType = name;
firstParamKind = kind;
}
}
} else {
if (isSignature) {
if (tn.peek() == Token.CloseParen) break; // allow trailing comma
this.error(
DiagnosticCode.Identifier_expected,
tn.range()
);
} else {
tn.reset(state);
}
this.tryParseSignatureIsSignature = isSignature;
return null;
}
} while (tn.skip(Token.Comma));
if (!tn.skip(Token.CloseParen)) {
if (isSignature) {
this.error(
DiagnosticCode._0_expected,
tn.range(), ")"
);
} else {
tn.reset(state);
}
this.tryParseSignatureIsSignature = isSignature;
return null;
}
}
let returnType: TypeNode | null;
if (tn.skip(Token.Equals_GreaterThan)) {
if (!isSignature) {
isSignature = true;
tn.discard(state);
if (firstParamNameNoType) { // now we know
let param = Node.createParameter(
firstParamKind,
firstParamNameNoType,
Node.createOmittedType(firstParamNameNoType.range.atEnd),
null,
firstParamNameNoType.range
);
if (!parameters) parameters = [ param ];
else parameters.push(param);
this.error(
DiagnosticCode.Type_expected,
param.type.range
); // recoverable
}
}
returnType = this.parseType(tn);
if (!returnType) {
this.tryParseSignatureIsSignature = isSignature;
return null;
}
} else {
if (isSignature) {
this.error(
DiagnosticCode._0_expected,
tn.range(), "=>"
);
} else {
tn.reset(state);
}
this.tryParseSignatureIsSignature = isSignature;
return null;
}
this.tryParseSignatureIsSignature = true;
if (!parameters) parameters = [];
return Node.createFunctionType(
parameters,
returnType,
thisType,
false,
tn.range(startPos, tn.pos)
);
}
// statements
parseDecorator(
tn: Tokenizer
): DecoratorNode | null {
// at '@': Identifier ('.' Identifier)* '(' Arguments
let startPos = tn.tokenPos;
if (tn.skipIdentifier()) {
let name = tn.readIdentifier();
let expression: Expression = Node.createIdentifierExpression(name, tn.range(startPos, tn.pos));
while (tn.skip(Token.Dot)) {
if (tn.skipIdentifier(IdentifierHandling.Prefer)) {
name = tn.readIdentifier();
expression = Node.createPropertyAccessExpression(
expression,
Node.createIdentifierExpression(name, tn.range()),
tn.range(startPos, tn.pos)
);
} else {
this.error(
DiagnosticCode.Identifier_expected,
tn.range()
);
return null;
}
}
let args: Expression[] | null;
if (tn.skip(Token.OpenParen)) {
args = this.parseArguments(tn);
if (args) {
return Node.createDecorator(expression, args, tn.range(startPos, tn.pos));
}
} else {
return Node.createDecorator(expression, null, tn.range(startPos, tn.pos));
}
} else {
this.error(
DiagnosticCode.Identifier_expected,
tn.range()
);
}
return null;
}
parseVariable(
tn: Tokenizer,
flags: CommonFlags,
decorators: DecoratorNode[] | null,
startPos: i32,
isFor: bool = false
): VariableStatement | null {
// at ('const' | 'let' | 'var'): VariableDeclaration (',' VariableDeclaration)* ';'?
let declarations = new Array<VariableDeclaration>();
do {
let declaration = this.parseVariableDeclaration(tn, flags, decorators, isFor);
if (!declaration) return null;
declaration.overriddenModuleName = this.currentModuleName;
declarations.push(declaration);
} while (tn.skip(Token.Comma));
let ret = Node.createVariableStatement(decorators, declarations, tn.range(startPos, tn.pos));
if (!tn.skip(Token.Semicolon) && !isFor) this.checkASI(tn);
return ret;
}
parseVariableDeclaration(
tn: Tokenizer,
parentFlags: CommonFlags,
parentDecorators: DecoratorNode[] | null,
isFor: bool = false
): VariableDeclaration | null {
// before: Identifier (':' Type)? ('=' Expression)?
if (!tn.skipIdentifier()) {
this.error(
DiagnosticCode.Identifier_expected,
tn.range()
);
return null;
}
let identifier = Node.createIdentifierExpression(tn.readIdentifier(), tn.range());
if (isIllegalVariableIdentifier(identifier.text)) {
this.error(
DiagnosticCode.Identifier_expected,
identifier.range
);
}
let flags = parentFlags;
if (tn.skip(Token.Exclamation)) {
flags |= CommonFlags.DefinitelyAssigned;
}
let type: TypeNode | null = null;
if (tn.skip(Token.Colon)) {
type = this.parseType(tn, true);
}
let initializer: Expression | null = null;
if (tn.skip(Token.Equals)) {
if (flags & CommonFlags.Ambient) {
this.error(
DiagnosticCode.Initializers_are_not_allowed_in_ambient_contexts,
tn.range()
); // recoverable
}
initializer = this.parseExpression(tn, Precedence.Comma + 1);
if (!initializer) return null;
if (flags & CommonFlags.DefinitelyAssigned) {
this.error(
DiagnosticCode.Declarations_with_initializers_cannot_also_have_definite_assignment_assertions,
initializer.range
);
}
} else if (!isFor) {
if (flags & CommonFlags.Const) {