-
Notifications
You must be signed in to change notification settings - Fork 12.7k
/
Copy pathparser.ts
3980 lines (3589 loc) · 197 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
/// <reference path="types.ts"/>
/// <reference path="core.ts"/>
/// <reference path="scanner.ts"/>
module ts {
var nodeConstructors = new Array<new () => Node>(SyntaxKind.Count);
export function getNodeConstructor(kind: SyntaxKind): new () => Node {
return nodeConstructors[kind] || (nodeConstructors[kind] = objectAllocator.getNodeConstructor(kind));
}
function createRootNode(kind: SyntaxKind, pos: number, end: number, flags: NodeFlags): Node {
var node = new (getNodeConstructor(kind))();
node.pos = pos;
node.end = end;
node.flags = flags;
return node;
}
var moduleExtensions = [".d.ts", ".ts", ".js"];
interface ReferenceComments {
referencedFiles: FileReference[];
amdDependencies: string[];
}
export function getModuleNameFromFilename(filename: string) {
for (var i = 0; i < moduleExtensions.length; i++) {
var ext = moduleExtensions[i];
var len = filename.length - ext.length;
if (len > 0 && filename.substr(len) === ext) return filename.substr(0, len);
}
return filename;
}
export function getSourceFileOfNode(node: Node): SourceFile {
while (node && node.kind !== SyntaxKind.SourceFile) node = node.parent;
return <SourceFile>node;
}
// This is a useful function for debugging purposes.
export function nodePosToString(node: Node): string {
var file = getSourceFileOfNode(node);
var loc = file.getLineAndCharacterFromPosition(node.pos);
return file.filename + "(" + loc.line + "," + loc.character + ")";
}
export function getStartPosOfNode(node: Node): number {
return node.pos;
}
export function getTokenPosOfNode(node: Node): number {
return skipTrivia(getSourceFileOfNode(node).text, node.pos);
}
export function getSourceTextOfNodeFromSourceText(sourceText: string, node: Node): string {
return sourceText.substring(skipTrivia(sourceText, node.pos), node.end);
}
export function getSourceTextOfNode(node: Node): string {
var text = getSourceFileOfNode(node).text;
return text.substring(skipTrivia(text, node.pos), node.end);
}
// Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__'
export function escapeIdentifier(identifier: string): string {
return identifier.length >= 2 && identifier.charCodeAt(0) === CharacterCodes._ && identifier.charCodeAt(1) === CharacterCodes._ ? "_" + identifier : identifier;
}
// Remove extra underscore from escaped identifier
export function unescapeIdentifier(identifier: string): string {
return identifier.length >= 3 && identifier.charCodeAt(0) === CharacterCodes._ && identifier.charCodeAt(1) === CharacterCodes._ && identifier.charCodeAt(2) === CharacterCodes._ ? identifier.substr(1) : identifier;
}
// Return display name of an identifier
export function identifierToString(identifier: Identifier) {
return identifier.kind === SyntaxKind.Missing ? "(Missing)" : getSourceTextOfNode(identifier);
}
export function createDiagnosticForNode(node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): Diagnostic {
node = getErrorSpanForNode(node);
var file = getSourceFileOfNode(node);
var start = node.kind === SyntaxKind.Missing ? node.pos : skipTrivia(file.text, node.pos);
var length = node.end - start;
return createFileDiagnostic(file, start, length, message, arg0, arg1, arg2);
}
export function createDiagnosticForNodeFromMessageChain(node: Node, messageChain: DiagnosticMessageChain, newLine: string): Diagnostic {
node = getErrorSpanForNode(node);
var file = getSourceFileOfNode(node);
var start = skipTrivia(file.text, node.pos);
var length = node.end - start;
return flattenDiagnosticChain(file, start, length, messageChain, newLine);
}
export function getErrorSpanForNode(node: Node): Node {
var errorSpan: Node;
switch (node.kind) {
// This list is a work in progress. Add missing node kinds to improve their error
// spans.
case SyntaxKind.VariableDeclaration:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.ModuleDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.EnumMember:
errorSpan = (<Declaration>node).name;
break;
}
// We now have the ideal error span, but it may be a node that is optional and absent
// (e.g. the name of a function expression), in which case errorSpan will be undefined.
// Alternatively, it might be required and missing (e.g. the name of a module), in which
// case its pos will equal its end (length 0). In either of these cases, we should fall
// back to the original node that the error was issued on.
return errorSpan && errorSpan.pos < errorSpan.end ? errorSpan : node;
}
export function isExternalModule(file: SourceFile): boolean {
return file.externalModuleIndicator !== undefined;
}
export function isPrologueDirective(node: Node): boolean {
return node.kind === SyntaxKind.ExpressionStatement && (<ExpressionStatement>node).expression.kind === SyntaxKind.StringLiteral;
}
function isEvalOrArgumentsIdentifier(node: Node): boolean {
return node.kind === SyntaxKind.Identifier &&
(<Identifier>node).text &&
((<Identifier>node).text === "eval" || (<Identifier>node).text === "arguments");
}
/// Should be called only on prologue directives (isPrologueDirective(node) should be true)
function isUseStrictPrologueDirective(node: Node): boolean {
Debug.assert(isPrologueDirective(node));
return (<Identifier>(<ExpressionStatement>node).expression).text === "use strict";
}
export function getLeadingCommentsOfNode(node: Node, sourceFileOfNode: SourceFile) {
// If parameter/type parameter, the prev token trailing comments are part of this node too
if (node.kind === SyntaxKind.Parameter || node.kind === SyntaxKind.TypeParameter) {
// e.g. (/** blah */ a, /** blah */ b);
return concatenate(getTrailingComments(sourceFileOfNode.text, node.pos),
// e.g.: (
// /** blah */ a,
// /** blah */ b);
getLeadingComments(sourceFileOfNode.text, node.pos));
}
else {
return getLeadingComments(sourceFileOfNode.text, node.pos);
}
}
export function getJsDocComments(node: Declaration, sourceFileOfNode: SourceFile) {
return filter(getLeadingCommentsOfNode(node, sourceFileOfNode), comment => isJsDocComment(comment));
function isJsDocComment(comment: Comment) {
// True if the comment starts with '/**' but not if it is '/**/'
return sourceFileOfNode.text.charCodeAt(comment.pos + 1) === CharacterCodes.asterisk &&
sourceFileOfNode.text.charCodeAt(comment.pos + 2) === CharacterCodes.asterisk &&
sourceFileOfNode.text.charCodeAt(comment.pos + 3) !== CharacterCodes.slash;
}
}
export var fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*<reference\s+path\s*=\s*)('|")(.+?)\2.*?\/>/
// Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
// stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise,
// embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns
// a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
export function forEachChild<T>(node: Node, cbNode: (node: Node) => T, cbNodes?: (nodes: Node[]) => T): T {
function child(node: Node): T {
if (node) return cbNode(node);
}
function children(nodes: Node[]) {
if (nodes) {
if (cbNodes) return cbNodes(nodes);
var result: T;
for (var i = 0, len = nodes.length; i < len; i++) {
if (result = cbNode(nodes[i])) break;
}
return result;
}
}
if (!node) return;
switch (node.kind) {
case SyntaxKind.QualifiedName:
return child((<QualifiedName>node).left) ||
child((<QualifiedName>node).right);
case SyntaxKind.TypeParameter:
return child((<TypeParameterDeclaration>node).name) ||
child((<TypeParameterDeclaration>node).constraint);
case SyntaxKind.Parameter:
return child((<ParameterDeclaration>node).name) ||
child((<ParameterDeclaration>node).type) ||
child((<ParameterDeclaration>node).initializer);
case SyntaxKind.Property:
case SyntaxKind.PropertyAssignment:
return child((<PropertyDeclaration>node).name) ||
child((<PropertyDeclaration>node).type) ||
child((<PropertyDeclaration>node).initializer);
case SyntaxKind.CallSignature:
case SyntaxKind.ConstructSignature:
case SyntaxKind.IndexSignature:
return children((<SignatureDeclaration>node).typeParameters) ||
children((<SignatureDeclaration>node).parameters) ||
child((<SignatureDeclaration>node).type);
case SyntaxKind.Method:
case SyntaxKind.Constructor:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.FunctionExpression:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.ArrowFunction:
return child((<FunctionDeclaration>node).name) ||
children((<FunctionDeclaration>node).typeParameters) ||
children((<FunctionDeclaration>node).parameters) ||
child((<FunctionDeclaration>node).type) ||
child((<FunctionDeclaration>node).body);
case SyntaxKind.TypeReference:
return child((<TypeReferenceNode>node).typeName) ||
children((<TypeReferenceNode>node).typeArguments);
case SyntaxKind.TypeQuery:
return child((<TypeQueryNode>node).exprName);
case SyntaxKind.TypeLiteral:
return children((<TypeLiteralNode>node).members);
case SyntaxKind.ArrayType:
return child((<ArrayTypeNode>node).elementType);
case SyntaxKind.TupleType:
return children((<TupleTypeNode>node).elementTypes);
case SyntaxKind.ArrayLiteral:
return children((<ArrayLiteral>node).elements);
case SyntaxKind.ObjectLiteral:
return children((<ObjectLiteral>node).properties);
case SyntaxKind.PropertyAccess:
return child((<PropertyAccess>node).left) ||
child((<PropertyAccess>node).right);
case SyntaxKind.IndexedAccess:
return child((<IndexedAccess>node).object) ||
child((<IndexedAccess>node).index);
case SyntaxKind.CallExpression:
case SyntaxKind.NewExpression:
return child((<CallExpression>node).func) ||
children((<CallExpression>node).typeArguments) ||
children((<CallExpression>node).arguments);
case SyntaxKind.TypeAssertion:
return child((<TypeAssertion>node).type) ||
child((<TypeAssertion>node).operand);
case SyntaxKind.ParenExpression:
return child((<ParenExpression>node).expression);
case SyntaxKind.PrefixOperator:
case SyntaxKind.PostfixOperator:
return child((<UnaryExpression>node).operand);
case SyntaxKind.BinaryExpression:
return child((<BinaryExpression>node).left) ||
child((<BinaryExpression>node).right);
case SyntaxKind.ConditionalExpression:
return child((<ConditionalExpression>node).condition) ||
child((<ConditionalExpression>node).whenTrue) ||
child((<ConditionalExpression>node).whenFalse);
case SyntaxKind.Block:
case SyntaxKind.TryBlock:
case SyntaxKind.FinallyBlock:
case SyntaxKind.FunctionBlock:
case SyntaxKind.ModuleBlock:
case SyntaxKind.SourceFile:
return children((<Block>node).statements);
case SyntaxKind.VariableStatement:
return children((<VariableStatement>node).declarations);
case SyntaxKind.ExpressionStatement:
return child((<ExpressionStatement>node).expression);
case SyntaxKind.IfStatement:
return child((<IfStatement>node).expression) ||
child((<IfStatement>node).thenStatement) ||
child((<IfStatement>node).elseStatement);
case SyntaxKind.DoStatement:
return child((<DoStatement>node).statement) ||
child((<DoStatement>node).expression);
case SyntaxKind.WhileStatement:
return child((<WhileStatement>node).expression) ||
child((<WhileStatement>node).statement);
case SyntaxKind.ForStatement:
return children((<ForStatement>node).declarations) ||
child((<ForStatement>node).initializer) ||
child((<ForStatement>node).condition) ||
child((<ForStatement>node).iterator) ||
child((<ForStatement>node).statement);
case SyntaxKind.ForInStatement:
return child((<ForInStatement>node).declaration) ||
child((<ForInStatement>node).variable) ||
child((<ForInStatement>node).expression) ||
child((<ForInStatement>node).statement);
case SyntaxKind.ContinueStatement:
case SyntaxKind.BreakStatement:
return child((<BreakOrContinueStatement>node).label);
case SyntaxKind.ReturnStatement:
return child((<ReturnStatement>node).expression);
case SyntaxKind.WithStatement:
return child((<WithStatement>node).expression) ||
child((<WithStatement>node).statement);
case SyntaxKind.SwitchStatement:
return child((<SwitchStatement>node).expression) ||
children((<SwitchStatement>node).clauses);
case SyntaxKind.CaseClause:
case SyntaxKind.DefaultClause:
return child((<CaseOrDefaultClause>node).expression) ||
children((<CaseOrDefaultClause>node).statements);
case SyntaxKind.LabelledStatement:
return child((<LabelledStatement>node).label) ||
child((<LabelledStatement>node).statement);
case SyntaxKind.ThrowStatement:
return child((<ThrowStatement>node).expression);
case SyntaxKind.TryStatement:
return child((<TryStatement>node).tryBlock) ||
child((<TryStatement>node).catchBlock) ||
child((<TryStatement>node).finallyBlock);
case SyntaxKind.CatchBlock:
return child((<CatchBlock>node).variable) ||
children((<CatchBlock>node).statements);
case SyntaxKind.VariableDeclaration:
return child((<VariableDeclaration>node).name) ||
child((<VariableDeclaration>node).type) ||
child((<VariableDeclaration>node).initializer);
case SyntaxKind.ClassDeclaration:
return child((<ClassDeclaration>node).name) ||
children((<ClassDeclaration>node).typeParameters) ||
child((<ClassDeclaration>node).baseType) ||
children((<ClassDeclaration>node).implementedTypes) ||
children((<ClassDeclaration>node).members);
case SyntaxKind.InterfaceDeclaration:
return child((<InterfaceDeclaration>node).name) ||
children((<InterfaceDeclaration>node).typeParameters) ||
children((<InterfaceDeclaration>node).baseTypes) ||
children((<InterfaceDeclaration>node).members);
case SyntaxKind.EnumDeclaration:
return child((<EnumDeclaration>node).name) ||
children((<EnumDeclaration>node).members);
case SyntaxKind.EnumMember:
return child((<EnumMember>node).name) ||
child((<EnumMember>node).initializer);
case SyntaxKind.ModuleDeclaration:
return child((<ModuleDeclaration>node).name) ||
child((<ModuleDeclaration>node).body);
case SyntaxKind.ImportDeclaration:
return child((<ImportDeclaration>node).name) ||
child((<ImportDeclaration>node).entityName) ||
child((<ImportDeclaration>node).externalModuleName);
case SyntaxKind.ExportAssignment:
return child((<ExportAssignment>node).exportName);
}
}
// Warning: This has the same semantics as the forEach family of functions,
// in that traversal terminates in the event that 'visitor' supplies a truthy value.
export function forEachReturnStatement<T>(body: Block, visitor: (stmt: ReturnStatement) => T): T {
return traverse(body);
function traverse(node: Node): T {
switch (node.kind) {
case SyntaxKind.ReturnStatement:
return visitor(node);
case SyntaxKind.Block:
case SyntaxKind.FunctionBlock:
case SyntaxKind.IfStatement:
case SyntaxKind.DoStatement:
case SyntaxKind.WhileStatement:
case SyntaxKind.ForStatement:
case SyntaxKind.ForInStatement:
case SyntaxKind.WithStatement:
case SyntaxKind.SwitchStatement:
case SyntaxKind.CaseClause:
case SyntaxKind.DefaultClause:
case SyntaxKind.LabelledStatement:
case SyntaxKind.TryStatement:
case SyntaxKind.TryBlock:
case SyntaxKind.CatchBlock:
case SyntaxKind.FinallyBlock:
return forEachChild(node, traverse);
}
}
}
export function isAnyFunction(node: Node): boolean {
if (node) {
switch (node.kind) {
case SyntaxKind.FunctionExpression:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.ArrowFunction:
case SyntaxKind.Method:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.Constructor:
return true;
}
}
return false;
}
export function getContainingFunction(node: Node): SignatureDeclaration {
while (true) {
node = node.parent;
if (!node || isAnyFunction(node)) {
return <SignatureDeclaration>node;
}
}
}
export function getThisContainer(node: Node, includeArrowFunctions: boolean): Node {
while (true) {
node = node.parent;
if (!node) {
return undefined;
}
switch (node.kind) {
case SyntaxKind.ArrowFunction:
if (!includeArrowFunctions) {
continue;
}
// Fall through
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
case SyntaxKind.ModuleDeclaration:
case SyntaxKind.Property:
case SyntaxKind.Method:
case SyntaxKind.Constructor:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.SourceFile:
return node;
}
}
}
export function getSuperContainer(node: Node): Node {
while (true) {
node = node.parent;
if (!node) {
return undefined;
}
switch (node.kind) {
case SyntaxKind.Property:
case SyntaxKind.Method:
case SyntaxKind.Constructor:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
return node;
}
}
}
export function hasRestParameters(s: SignatureDeclaration): boolean {
return s.parameters.length > 0 && (s.parameters[s.parameters.length - 1].flags & NodeFlags.Rest) !== 0;
}
export function isInAmbientContext(node: Node): boolean {
while (node) {
if (node.flags & (NodeFlags.Ambient | NodeFlags.DeclarationFile)) return true;
node = node.parent;
}
return false;
}
export function isDeclaration(node: Node): boolean {
switch (node.kind) {
case SyntaxKind.TypeParameter:
case SyntaxKind.Parameter:
case SyntaxKind.VariableDeclaration:
case SyntaxKind.Property:
case SyntaxKind.PropertyAssignment:
case SyntaxKind.EnumMember:
case SyntaxKind.Method:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.ModuleDeclaration:
case SyntaxKind.ImportDeclaration:
return true;
}
return false;
}
// True if the given identifier, string literal, or number literal is the name of a declaration node
export function isDeclarationOrFunctionExpressionOrCatchVariableName(name: Node): boolean {
if (name.kind !== SyntaxKind.Identifier && name.kind !== SyntaxKind.StringLiteral && name.kind !== SyntaxKind.NumericLiteral) {
return false;
}
var parent = name.parent;
if (isDeclaration(parent) || parent.kind === SyntaxKind.FunctionExpression) {
return (<Declaration>parent).name === name;
}
if (parent.kind === SyntaxKind.CatchBlock) {
return (<CatchBlock>parent).variable === name;
}
return false;
}
enum ParsingContext {
SourceElements, // Elements in source file
ModuleElements, // Elements in module declaration
BlockStatements, // Statements in block
SwitchClauses, // Clauses in switch statement
SwitchClauseStatements, // Statements in switch clause
TypeMembers, // Members in interface or type literal
ClassMembers, // Members in class declaration
EnumMembers, // Members in enum declaration
BaseTypeReferences, // Type references in extends or implements clause
VariableDeclarations, // Variable declarations in variable statement
ArgumentExpressions, // Expressions in argument list
ObjectLiteralMembers, // Members in object literal
ArrayLiteralMembers, // Members in array literal
Parameters, // Parameters in parameter list
TypeParameters, // Type parameters in type parameter list
TypeArguments, // Type arguments in type argument list
TupleElementTypes, // Element types in tuple element type list
Count // Number of parsing contexts
}
enum Tristate {
False,
True,
Unknown
}
function parsingContextErrors(context: ParsingContext): DiagnosticMessage {
switch (context) {
case ParsingContext.SourceElements: return Diagnostics.Declaration_or_statement_expected;
case ParsingContext.ModuleElements: return Diagnostics.Declaration_or_statement_expected;
case ParsingContext.BlockStatements: return Diagnostics.Statement_expected;
case ParsingContext.SwitchClauses: return Diagnostics.case_or_default_expected;
case ParsingContext.SwitchClauseStatements: return Diagnostics.Statement_expected;
case ParsingContext.TypeMembers: return Diagnostics.Property_or_signature_expected;
case ParsingContext.ClassMembers: return Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected;
case ParsingContext.EnumMembers: return Diagnostics.Enum_member_expected;
case ParsingContext.BaseTypeReferences: return Diagnostics.Type_reference_expected;
case ParsingContext.VariableDeclarations: return Diagnostics.Variable_declaration_expected;
case ParsingContext.ArgumentExpressions: return Diagnostics.Argument_expression_expected;
case ParsingContext.ObjectLiteralMembers: return Diagnostics.Property_assignment_expected;
case ParsingContext.ArrayLiteralMembers: return Diagnostics.Expression_or_comma_expected;
case ParsingContext.Parameters: return Diagnostics.Parameter_declaration_expected;
case ParsingContext.TypeParameters: return Diagnostics.Type_parameter_declaration_expected;
case ParsingContext.TypeArguments: return Diagnostics.Type_argument_expected;
case ParsingContext.TupleElementTypes: return Diagnostics.Type_expected;
}
};
enum LookAheadMode {
NotLookingAhead,
NoErrorYet,
Error
}
enum ModifierContext {
SourceElements, // Top level elements in a source file
ModuleElements, // Elements in module declaration
ClassMembers, // Members in class declaration
Parameters, // Parameters in parameter list
}
enum TrailingCommaBehavior {
Disallow,
Allow,
Preserve
}
// Tracks whether we nested (directly or indirectly) in a certain control block.
// Used for validating break and continue statements.
enum ControlBlockContext {
NotNested,
Nested,
CrossingFunctionBoundary
}
interface LabelledStatementInfo {
addLabel(label: Identifier): void;
pushCurrentLabelSet(isIterationStatement: boolean): void;
pushFunctionBoundary(): void;
pop(): void;
nodeIsNestedInLabel(label: Identifier, requireIterationStatement: boolean, stopAtFunctionBoundary: boolean): ControlBlockContext;
}
export function isKeyword(token: SyntaxKind): boolean {
return SyntaxKind.FirstKeyword <= token && token <= SyntaxKind.LastKeyword;
}
export function isModifier(token: SyntaxKind): boolean {
switch (token) {
case SyntaxKind.PublicKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.StaticKeyword:
case SyntaxKind.ExportKeyword:
case SyntaxKind.DeclareKeyword:
return true;
}
return false;
}
export function createSourceFile(filename: string, sourceText: string, languageVersion: ScriptTarget, version: string, isOpen: boolean = false): SourceFile {
var file: SourceFile;
var scanner: Scanner;
var token: SyntaxKind;
var parsingContext: ParsingContext;
var commentRanges: TextRange[];
var identifiers: Map<string> = {};
var identifierCount = 0;
var nodeCount = 0;
var lineStarts: number[];
var isInStrictMode = false;
var lookAheadMode = LookAheadMode.NotLookingAhead;
var inAmbientContext = false;
var inFunctionBody = false;
var inSwitchStatement = ControlBlockContext.NotNested;
var inIterationStatement = ControlBlockContext.NotNested;
// The following is a state machine that tracks what labels are in our current parsing
// context. So if we are parsing a node that is nested (arbitrarily deeply) in a label,
// it will be tracked in this data structure. It is used for checking break/continue
// statements, and checking for duplicate labels.
var labelledStatementInfo: LabelledStatementInfo = (() => {
// These are initialized on demand because labels are rare, so it is usually
// not even necessary to allocate these.
var functionBoundarySentinel: StringSet;
var currentLabelSet: StringSet;
var labelSetStack: StringSet[];
var isIterationStack: boolean[];
function addLabel(label: Identifier): void {
if (!currentLabelSet) {
currentLabelSet = {};
}
currentLabelSet[label.text] = true;
}
function pushCurrentLabelSet(isIterationStatement: boolean): void {
if (!labelSetStack && !isIterationStack) {
labelSetStack = [];
isIterationStack = [];
}
Debug.assert(currentLabelSet !== undefined);
labelSetStack.push(currentLabelSet);
isIterationStack.push(isIterationStatement);
currentLabelSet = undefined;
}
function pushFunctionBoundary(): void {
if (!functionBoundarySentinel) {
functionBoundarySentinel = {};
if (!labelSetStack && !isIterationStack) {
labelSetStack = [];
isIterationStack = [];
}
}
Debug.assert(currentLabelSet === undefined);
labelSetStack.push(functionBoundarySentinel);
// It does not matter what we push here, since we will never ask if a function boundary
// is an iteration statement
isIterationStack.push(false);
}
function pop(): void {
// Assert that we are in a "pushed" state
Debug.assert(labelSetStack.length && isIterationStack.length && currentLabelSet === undefined);
labelSetStack.pop();
isIterationStack.pop();
}
function nodeIsNestedInLabel(label: Identifier, requireIterationStatement: boolean, stopAtFunctionBoundary: boolean): ControlBlockContext {
if (!requireIterationStatement && currentLabelSet && hasProperty(currentLabelSet, label.text)) {
return ControlBlockContext.Nested;
}
if (!labelSetStack) {
return ControlBlockContext.NotNested;
}
// We want to start searching for the label at the lowest point in the tree,
// and climb up from there. So we start at the end of the labelSetStack array.
var crossedFunctionBoundary = false;
for (var i = labelSetStack.length - 1; i >= 0; i--) {
var labelSet = labelSetStack[i];
// Not allowed to cross function boundaries, so stop if we encounter one
if (labelSet === functionBoundarySentinel) {
if (stopAtFunctionBoundary) {
break;
}
else {
crossedFunctionBoundary = true;
continue;
}
}
// If we require an iteration statement, only search in the current
// statement if it is an iteration statement
if (requireIterationStatement && isIterationStack[i] === false) {
continue;
}
if (hasProperty(labelSet, label.text)) {
return crossedFunctionBoundary ? ControlBlockContext.CrossingFunctionBoundary : ControlBlockContext.Nested;
}
}
// This is a bit of a misnomer. If the caller passed true for stopAtFunctionBoundary,
// there actually may be an enclosing label across a function boundary, but we will
// just return NotNested
return ControlBlockContext.NotNested;
}
return {
addLabel: addLabel,
pushCurrentLabelSet: pushCurrentLabelSet,
pushFunctionBoundary: pushFunctionBoundary,
pop: pop,
nodeIsNestedInLabel: nodeIsNestedInLabel,
};
})();
function getLineAndCharacterlFromSourcePosition(position: number) {
if (!lineStarts) {
lineStarts = getLineStarts(sourceText);
}
return getLineAndCharacterOfPosition(lineStarts, position);
}
function getPositionFromSourceLineAndCharacter(line: number, character: number): number {
if (!lineStarts) {
lineStarts = getLineStarts(sourceText);
}
return getPositionFromLineAndCharacter(lineStarts, line, character);
}
function error(message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): void {
var start = scanner.getTokenPos();
var length = scanner.getTextPos() - start;
errorAtPos(start, length, message, arg0, arg1, arg2);
}
// This is just like createDiagnosticForNode except that it uses the current file
// being parsed instead of the file containing the node. This is because during
// parse, the nodes do not have parent pointers to get to the file.
//
// It is very intentional that we are not checking or changing the lookAheadMode value
// here. 'grammarErrorOnNode' is called when we are doing extra grammar checks and not
// when we are doing the actual parsing to determine what the user wrote. In other
// words, this function is called once we have already parsed the node, and are just
// applying some stricter checks on that node.
function grammarErrorOnNode(node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): void {
var span = getErrorSpanForNode(node);
var start = skipTrivia(file.text, span.pos);
var length = span.end - start;
file.syntacticErrors.push(createFileDiagnostic(file, start, length, message, arg0, arg1, arg2));
}
function reportInvalidUseInStrictMode(node: Identifier): void {
// identifierToString cannot be used here since it uses a backreference to 'parent' that is not yet set
var name = sourceText.substring(skipTrivia(sourceText, node.pos), node.end);
grammarErrorOnNode(node, Diagnostics.Invalid_use_of_0_in_strict_mode, name);
}
function grammarErrorAtPos(start: number, length: number, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): void {
file.syntacticErrors.push(createFileDiagnostic(file, start, length, message, arg0, arg1, arg2));
}
function errorAtPos(start: number, length: number, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): void {
var lastErrorPos = file.syntacticErrors.length
? file.syntacticErrors[file.syntacticErrors.length - 1].start
: -1;
if (start !== lastErrorPos) {
file.syntacticErrors.push(createFileDiagnostic(file, start, length, message, arg0, arg1, arg2));
}
if (lookAheadMode === LookAheadMode.NoErrorYet) {
lookAheadMode = LookAheadMode.Error;
}
}
function scanError(message: DiagnosticMessage) {
var pos = scanner.getTextPos();
errorAtPos(pos, 0, message);
}
function onComment(pos: number, end: number) {
if (commentRanges) commentRanges.push({ pos: pos, end: end });
}
function getNodePos(): number {
return scanner.getStartPos();
}
function getNodeEnd(): number {
return scanner.getStartPos();
}
function nextToken(): SyntaxKind {
return token = scanner.scan();
}
function getTokenPos(pos: number): number {
return skipTrivia(sourceText, pos);
}
function reScanGreaterToken(): SyntaxKind {
return token = scanner.reScanGreaterToken();
}
function reScanSlashToken(): SyntaxKind {
return token = scanner.reScanSlashToken();
}
function lookAheadHelper<T>(callback: () => T, alwaysResetState: boolean): T {
// Keep track of the state we'll need to rollback to if lookahead fails (or if the
// caller asked us to always reset our state).
var saveToken = token;
var saveSyntacticErrorsLength = file.syntacticErrors.length;
// Keep track of the current look ahead mode (this matters if we have nested
// speculative parsing).
var saveLookAheadMode = lookAheadMode;
// Mark that we're in speculative parsing and then try to parse out whatever code
// the callback wants.
lookAheadMode = LookAheadMode.NoErrorYet;
var result = callback();
// If we switched from 1 to -1 then a parse error occurred during the callback.
// If that's the case, then we want to act as if we never got any result at all.
Debug.assert(lookAheadMode === LookAheadMode.Error || lookAheadMode === LookAheadMode.NoErrorYet);
if (lookAheadMode === LookAheadMode.Error) {
result = undefined;
}
// Now restore as appropriate.
lookAheadMode = saveLookAheadMode;
if (!result || alwaysResetState) {
token = saveToken;
file.syntacticErrors.length = saveSyntacticErrorsLength;
}
return result;
}
function lookAhead<T>(callback: () => T): T {
var result: T;
scanner.tryScan(() => {
result = lookAheadHelper(callback, /*alwaysResetState:*/ true);
// Returning false here indicates to the scanner that it should always jump
// back to where it started. This makes sense as 'lookahead' acts as if
// neither the parser nor scanner was affected by the operation.
//
// Note: the rewinding of the parser state is already handled in lookAheadHelper
// (because we passed 'true' for alwaysResetState).
return false;
});
return result;
}
function tryParse<T>(callback: () => T): T {
return scanner.tryScan(() => lookAheadHelper(callback, /*alwaysResetState:*/ false));
}
function isIdentifier(): boolean {
return token === SyntaxKind.Identifier || (isInStrictMode ? token > SyntaxKind.LastFutureReservedWord : token > SyntaxKind.LastReservedWord);
}
function parseExpected(t: SyntaxKind): boolean {
if (token === t) {
nextToken();
return true;
}
error(Diagnostics._0_expected, tokenToString(t));
return false;
}
function parseOptional(t: SyntaxKind): boolean {
if (token === t) {
nextToken();
return true;
}
return false;
}
function canParseSemicolon() {
// If there's a real semicolon, then we can always parse it out.
if (token === SyntaxKind.SemicolonToken) {
return true;
}
// We can parse out an optional semicolon in ASI cases in the following cases.
return token === SyntaxKind.CloseBraceToken || token === SyntaxKind.EndOfFileToken || scanner.hasPrecedingLineBreak();
}
function parseSemicolon(): void {
if (canParseSemicolon()) {
if (token === SyntaxKind.SemicolonToken) {
// consume the semicolon if it was explicitly provided.
nextToken();
}
}
else {
error(Diagnostics._0_expected, ";");
}
}
function createNode(kind: SyntaxKind, pos?: number): Node {
nodeCount++;
var node = new (nodeConstructors[kind] || (nodeConstructors[kind] = objectAllocator.getNodeConstructor(kind)))();
if (!(pos >= 0)) pos = scanner.getStartPos();
node.pos = pos;
node.end = pos;
return node;
}
function finishNode<T extends Node>(node: T): T {
node.end = scanner.getStartPos();
return node;
}
function createMissingNode(): Node {
return createNode(SyntaxKind.Missing);
}
function internIdentifier(text: string): string {
return hasProperty(identifiers, text) ? identifiers[text] : (identifiers[text] = text);
}
// An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues
// with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for
// each identifier in order to reduce memory consumption.
function createIdentifier(isIdentifier: boolean): Identifier {
identifierCount++;
if (isIdentifier) {
var node = <Identifier>createNode(SyntaxKind.Identifier);
var text = escapeIdentifier(scanner.getTokenValue());
node.text = internIdentifier(text);
nextToken();
return finishNode(node);
}
error(Diagnostics.Identifier_expected);
return <Identifier>createMissingNode();
}
function parseIdentifier(): Identifier {
return createIdentifier(isIdentifier());
}
function parseIdentifierName(): Identifier {
return createIdentifier(token >= SyntaxKind.Identifier);
}
function isPropertyName(): boolean {
return token >= SyntaxKind.Identifier || token === SyntaxKind.StringLiteral || token === SyntaxKind.NumericLiteral;
}
function parsePropertyName(): Identifier {
if (token === SyntaxKind.StringLiteral || token === SyntaxKind.NumericLiteral) {
return parseLiteralNode(/*internName:*/ true);
}
return parseIdentifierName();
}
function parseContextualModifier(t: SyntaxKind): boolean {
return token === t && tryParse(() => {
nextToken();
return token === SyntaxKind.OpenBracketToken || isPropertyName();
});
}
function parseAnyContextualModifier(): boolean {
return isModifier(token) && tryParse(() => {
nextToken();
return token === SyntaxKind.OpenBracketToken || isPropertyName();
});
}
// True if positioned at the start of a list element
function isListElement(kind: ParsingContext, inErrorRecovery: boolean): boolean {
switch (kind) {
case ParsingContext.SourceElements:
case ParsingContext.ModuleElements:
return isSourceElement(inErrorRecovery);
case ParsingContext.BlockStatements:
case ParsingContext.SwitchClauseStatements:
return isStatement(inErrorRecovery);