-
Notifications
You must be signed in to change notification settings - Fork 12.5k
/
parser.ts
9533 lines (8550 loc) · 492 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
namespace ts {
const enum SignatureFlags {
None = 0,
Yield = 1 << 0,
Await = 1 << 1,
Type = 1 << 2,
IgnoreMissingOpenBrace = 1 << 4,
JSDoc = 1 << 5,
}
const enum SpeculationKind {
TryParse,
Lookahead,
Reparse
}
let NodeConstructor: new (kind: SyntaxKind, pos?: number, end?: number) => Node;
let TokenConstructor: new (kind: SyntaxKind, pos?: number, end?: number) => Node;
let IdentifierConstructor: new (kind: SyntaxKind, pos?: number, end?: number) => Node;
let PrivateIdentifierConstructor: new (kind: SyntaxKind, pos?: number, end?: number) => Node;
let SourceFileConstructor: new (kind: SyntaxKind, pos?: number, end?: number) => Node;
/**
* NOTE: You should not use this, it is only exported to support `createNode` in `~/src/deprecatedCompat/deprecations.ts`.
*/
/* @internal */
export const parseBaseNodeFactory: BaseNodeFactory = {
createBaseSourceFileNode: kind => new (SourceFileConstructor || (SourceFileConstructor = objectAllocator.getSourceFileConstructor()))(kind, -1, -1),
createBaseIdentifierNode: kind => new (IdentifierConstructor || (IdentifierConstructor = objectAllocator.getIdentifierConstructor()))(kind, -1, -1),
createBasePrivateIdentifierNode: kind => new (PrivateIdentifierConstructor || (PrivateIdentifierConstructor = objectAllocator.getPrivateIdentifierConstructor()))(kind, -1, -1),
createBaseTokenNode: kind => new (TokenConstructor || (TokenConstructor = objectAllocator.getTokenConstructor()))(kind, -1, -1),
createBaseNode: kind => new (NodeConstructor || (NodeConstructor = objectAllocator.getNodeConstructor()))(kind, -1, -1),
};
/* @internal */
export const parseNodeFactory = createNodeFactory(NodeFactoryFlags.NoParenthesizerRules, parseBaseNodeFactory);
function visitNode<T>(cbNode: (node: Node) => T, node: Node | undefined): T | undefined {
return node && cbNode(node);
}
function visitNodes<T>(cbNode: (node: Node) => T, cbNodes: ((node: NodeArray<Node>) => T | undefined) | undefined, nodes: NodeArray<Node> | undefined): T | undefined {
if (nodes) {
if (cbNodes) {
return cbNodes(nodes);
}
for (const node of nodes) {
const result = cbNode(node);
if (result) {
return result;
}
}
}
}
/*@internal*/
export function isJSDocLikeText(text: string, start: number) {
return text.charCodeAt(start + 1) === CharacterCodes.asterisk &&
text.charCodeAt(start + 2) === CharacterCodes.asterisk &&
text.charCodeAt(start + 3) !== CharacterCodes.slash;
}
/**
* 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.
*
* @param node a given node to visit its children
* @param cbNode a callback to be invoked for all child nodes
* @param cbNodes a callback to be invoked for embedded array
*
* @remarks `forEachChild` must visit the children of a node in the order
* that they appear in the source code. The language service depends on this property to locate nodes by position.
*/
export function forEachChild<T>(node: Node, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray<Node>) => T | undefined): T | undefined {
if (!node || node.kind <= SyntaxKind.LastToken) {
return;
}
switch (node.kind) {
case SyntaxKind.QualifiedName:
return visitNode(cbNode, (node as QualifiedName).left) ||
visitNode(cbNode, (node as QualifiedName).right);
case SyntaxKind.TypeParameter:
return visitNode(cbNode, (node as TypeParameterDeclaration).name) ||
visitNode(cbNode, (node as TypeParameterDeclaration).constraint) ||
visitNode(cbNode, (node as TypeParameterDeclaration).default) ||
visitNode(cbNode, (node as TypeParameterDeclaration).expression);
case SyntaxKind.ShorthandPropertyAssignment:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, (node as ShorthandPropertyAssignment).name) ||
visitNode(cbNode, (node as ShorthandPropertyAssignment).questionToken) ||
visitNode(cbNode, (node as ShorthandPropertyAssignment).exclamationToken) ||
visitNode(cbNode, (node as ShorthandPropertyAssignment).equalsToken) ||
visitNode(cbNode, (node as ShorthandPropertyAssignment).objectAssignmentInitializer);
case SyntaxKind.SpreadAssignment:
return visitNode(cbNode, (node as SpreadAssignment).expression);
case SyntaxKind.Parameter:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, (node as ParameterDeclaration).dotDotDotToken) ||
visitNode(cbNode, (node as ParameterDeclaration).name) ||
visitNode(cbNode, (node as ParameterDeclaration).questionToken) ||
visitNode(cbNode, (node as ParameterDeclaration).type) ||
visitNode(cbNode, (node as ParameterDeclaration).initializer);
case SyntaxKind.PropertyDeclaration:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, (node as PropertyDeclaration).name) ||
visitNode(cbNode, (node as PropertyDeclaration).questionToken) ||
visitNode(cbNode, (node as PropertyDeclaration).exclamationToken) ||
visitNode(cbNode, (node as PropertyDeclaration).type) ||
visitNode(cbNode, (node as PropertyDeclaration).initializer);
case SyntaxKind.PropertySignature:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, (node as PropertySignature).name) ||
visitNode(cbNode, (node as PropertySignature).questionToken) ||
visitNode(cbNode, (node as PropertySignature).type) ||
visitNode(cbNode, (node as PropertySignature).initializer);
case SyntaxKind.PropertyAssignment:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, (node as PropertyAssignment).name) ||
visitNode(cbNode, (node as PropertyAssignment).questionToken) ||
visitNode(cbNode, (node as PropertyAssignment).initializer);
case SyntaxKind.VariableDeclaration:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, (node as VariableDeclaration).name) ||
visitNode(cbNode, (node as VariableDeclaration).exclamationToken) ||
visitNode(cbNode, (node as VariableDeclaration).type) ||
visitNode(cbNode, (node as VariableDeclaration).initializer);
case SyntaxKind.BindingElement:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, (node as BindingElement).dotDotDotToken) ||
visitNode(cbNode, (node as BindingElement).propertyName) ||
visitNode(cbNode, (node as BindingElement).name) ||
visitNode(cbNode, (node as BindingElement).initializer);
case SyntaxKind.FunctionType:
case SyntaxKind.ConstructorType:
case SyntaxKind.CallSignature:
case SyntaxKind.ConstructSignature:
case SyntaxKind.IndexSignature:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNodes(cbNode, cbNodes, (node as SignatureDeclaration).typeParameters) ||
visitNodes(cbNode, cbNodes, (node as SignatureDeclaration).parameters) ||
visitNode(cbNode, (node as SignatureDeclaration).type);
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
case SyntaxKind.Constructor:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.FunctionExpression:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.ArrowFunction:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, (node as FunctionLikeDeclaration).asteriskToken) ||
visitNode(cbNode, (node as FunctionLikeDeclaration).name) ||
visitNode(cbNode, (node as FunctionLikeDeclaration).questionToken) ||
visitNode(cbNode, (node as FunctionLikeDeclaration).exclamationToken) ||
visitNodes(cbNode, cbNodes, (node as FunctionLikeDeclaration).typeParameters) ||
visitNodes(cbNode, cbNodes, (node as FunctionLikeDeclaration).parameters) ||
visitNode(cbNode, (node as FunctionLikeDeclaration).type) ||
visitNode(cbNode, (node as ArrowFunction).equalsGreaterThanToken) ||
visitNode(cbNode, (node as FunctionLikeDeclaration).body);
case SyntaxKind.ClassStaticBlockDeclaration:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, (node as ClassStaticBlockDeclaration).body);
case SyntaxKind.TypeReference:
return visitNode(cbNode, (node as TypeReferenceNode).typeName) ||
visitNodes(cbNode, cbNodes, (node as TypeReferenceNode).typeArguments);
case SyntaxKind.TypePredicate:
return visitNode(cbNode, (node as TypePredicateNode).assertsModifier) ||
visitNode(cbNode, (node as TypePredicateNode).parameterName) ||
visitNode(cbNode, (node as TypePredicateNode).type);
case SyntaxKind.TypeQuery:
return visitNode(cbNode, (node as TypeQueryNode).exprName);
case SyntaxKind.TypeLiteral:
return visitNodes(cbNode, cbNodes, (node as TypeLiteralNode).members);
case SyntaxKind.ArrayType:
return visitNode(cbNode, (node as ArrayTypeNode).elementType);
case SyntaxKind.TupleType:
return visitNodes(cbNode, cbNodes, (node as TupleTypeNode).elements);
case SyntaxKind.UnionType:
case SyntaxKind.IntersectionType:
return visitNodes(cbNode, cbNodes, (node as UnionOrIntersectionTypeNode).types);
case SyntaxKind.ConditionalType:
return visitNode(cbNode, (node as ConditionalTypeNode).checkType) ||
visitNode(cbNode, (node as ConditionalTypeNode).extendsType) ||
visitNode(cbNode, (node as ConditionalTypeNode).trueType) ||
visitNode(cbNode, (node as ConditionalTypeNode).falseType);
case SyntaxKind.InferType:
return visitNode(cbNode, (node as InferTypeNode).typeParameter);
case SyntaxKind.ImportType:
return visitNode(cbNode, (node as ImportTypeNode).argument) ||
visitNode(cbNode, (node as ImportTypeNode).qualifier) ||
visitNodes(cbNode, cbNodes, (node as ImportTypeNode).typeArguments);
case SyntaxKind.ParenthesizedType:
case SyntaxKind.TypeOperator:
return visitNode(cbNode, (node as ParenthesizedTypeNode | TypeOperatorNode).type);
case SyntaxKind.IndexedAccessType:
return visitNode(cbNode, (node as IndexedAccessTypeNode).objectType) ||
visitNode(cbNode, (node as IndexedAccessTypeNode).indexType);
case SyntaxKind.MappedType:
return visitNode(cbNode, (node as MappedTypeNode).readonlyToken) ||
visitNode(cbNode, (node as MappedTypeNode).typeParameter) ||
visitNode(cbNode, (node as MappedTypeNode).nameType) ||
visitNode(cbNode, (node as MappedTypeNode).questionToken) ||
visitNode(cbNode, (node as MappedTypeNode).type) ||
visitNodes(cbNode, cbNodes, (node as MappedTypeNode).members);
case SyntaxKind.LiteralType:
return visitNode(cbNode, (node as LiteralTypeNode).literal);
case SyntaxKind.NamedTupleMember:
return visitNode(cbNode, (node as NamedTupleMember).dotDotDotToken) ||
visitNode(cbNode, (node as NamedTupleMember).name) ||
visitNode(cbNode, (node as NamedTupleMember).questionToken) ||
visitNode(cbNode, (node as NamedTupleMember).type);
case SyntaxKind.ObjectBindingPattern:
case SyntaxKind.ArrayBindingPattern:
return visitNodes(cbNode, cbNodes, (node as BindingPattern).elements);
case SyntaxKind.ArrayLiteralExpression:
return visitNodes(cbNode, cbNodes, (node as ArrayLiteralExpression).elements);
case SyntaxKind.ObjectLiteralExpression:
return visitNodes(cbNode, cbNodes, (node as ObjectLiteralExpression).properties);
case SyntaxKind.PropertyAccessExpression:
return visitNode(cbNode, (node as PropertyAccessExpression).expression) ||
visitNode(cbNode, (node as PropertyAccessExpression).questionDotToken) ||
visitNode(cbNode, (node as PropertyAccessExpression).name);
case SyntaxKind.ElementAccessExpression:
return visitNode(cbNode, (node as ElementAccessExpression).expression) ||
visitNode(cbNode, (node as ElementAccessExpression).questionDotToken) ||
visitNode(cbNode, (node as ElementAccessExpression).argumentExpression);
case SyntaxKind.CallExpression:
case SyntaxKind.NewExpression:
return visitNode(cbNode, (node as CallExpression).expression) ||
visitNode(cbNode, (node as CallExpression).questionDotToken) ||
visitNodes(cbNode, cbNodes, (node as CallExpression).typeArguments) ||
visitNodes(cbNode, cbNodes, (node as CallExpression).arguments);
case SyntaxKind.TaggedTemplateExpression:
return visitNode(cbNode, (node as TaggedTemplateExpression).tag) ||
visitNode(cbNode, (node as TaggedTemplateExpression).questionDotToken) ||
visitNodes(cbNode, cbNodes, (node as TaggedTemplateExpression).typeArguments) ||
visitNode(cbNode, (node as TaggedTemplateExpression).template);
case SyntaxKind.TypeAssertionExpression:
return visitNode(cbNode, (node as TypeAssertion).type) ||
visitNode(cbNode, (node as TypeAssertion).expression);
case SyntaxKind.ParenthesizedExpression:
return visitNode(cbNode, (node as ParenthesizedExpression).expression);
case SyntaxKind.DeleteExpression:
return visitNode(cbNode, (node as DeleteExpression).expression);
case SyntaxKind.TypeOfExpression:
return visitNode(cbNode, (node as TypeOfExpression).expression);
case SyntaxKind.VoidExpression:
return visitNode(cbNode, (node as VoidExpression).expression);
case SyntaxKind.PrefixUnaryExpression:
return visitNode(cbNode, (node as PrefixUnaryExpression).operand);
case SyntaxKind.YieldExpression:
return visitNode(cbNode, (node as YieldExpression).asteriskToken) ||
visitNode(cbNode, (node as YieldExpression).expression);
case SyntaxKind.AwaitExpression:
return visitNode(cbNode, (node as AwaitExpression).expression);
case SyntaxKind.PostfixUnaryExpression:
return visitNode(cbNode, (node as PostfixUnaryExpression).operand);
case SyntaxKind.BinaryExpression:
return visitNode(cbNode, (node as BinaryExpression).left) ||
visitNode(cbNode, (node as BinaryExpression).operatorToken) ||
visitNode(cbNode, (node as BinaryExpression).right);
case SyntaxKind.AsExpression:
return visitNode(cbNode, (node as AsExpression).expression) ||
visitNode(cbNode, (node as AsExpression).type);
case SyntaxKind.NonNullExpression:
return visitNode(cbNode, (node as NonNullExpression).expression);
case SyntaxKind.MetaProperty:
return visitNode(cbNode, (node as MetaProperty).name);
case SyntaxKind.ConditionalExpression:
return visitNode(cbNode, (node as ConditionalExpression).condition) ||
visitNode(cbNode, (node as ConditionalExpression).questionToken) ||
visitNode(cbNode, (node as ConditionalExpression).whenTrue) ||
visitNode(cbNode, (node as ConditionalExpression).colonToken) ||
visitNode(cbNode, (node as ConditionalExpression).whenFalse);
case SyntaxKind.SpreadElement:
return visitNode(cbNode, (node as SpreadElement).expression);
case SyntaxKind.Block:
case SyntaxKind.ModuleBlock:
return visitNodes(cbNode, cbNodes, (node as Block).statements);
case SyntaxKind.SourceFile:
return visitNodes(cbNode, cbNodes, (node as SourceFile).statements) ||
visitNode(cbNode, (node as SourceFile).endOfFileToken);
case SyntaxKind.VariableStatement:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, (node as VariableStatement).declarationList);
case SyntaxKind.VariableDeclarationList:
return visitNodes(cbNode, cbNodes, (node as VariableDeclarationList).declarations);
case SyntaxKind.ExpressionStatement:
return visitNode(cbNode, (node as ExpressionStatement).expression);
case SyntaxKind.IfStatement:
return visitNode(cbNode, (node as IfStatement).expression) ||
visitNode(cbNode, (node as IfStatement).thenStatement) ||
visitNode(cbNode, (node as IfStatement).elseStatement);
case SyntaxKind.DoStatement:
return visitNode(cbNode, (node as DoStatement).statement) ||
visitNode(cbNode, (node as DoStatement).expression);
case SyntaxKind.WhileStatement:
return visitNode(cbNode, (node as WhileStatement).expression) ||
visitNode(cbNode, (node as WhileStatement).statement);
case SyntaxKind.ForStatement:
return visitNode(cbNode, (node as ForStatement).initializer) ||
visitNode(cbNode, (node as ForStatement).condition) ||
visitNode(cbNode, (node as ForStatement).incrementor) ||
visitNode(cbNode, (node as ForStatement).statement);
case SyntaxKind.ForInStatement:
return visitNode(cbNode, (node as ForInStatement).initializer) ||
visitNode(cbNode, (node as ForInStatement).expression) ||
visitNode(cbNode, (node as ForInStatement).statement);
case SyntaxKind.ForOfStatement:
return visitNode(cbNode, (node as ForOfStatement).awaitModifier) ||
visitNode(cbNode, (node as ForOfStatement).initializer) ||
visitNode(cbNode, (node as ForOfStatement).expression) ||
visitNode(cbNode, (node as ForOfStatement).statement);
case SyntaxKind.ContinueStatement:
case SyntaxKind.BreakStatement:
return visitNode(cbNode, (node as BreakOrContinueStatement).label);
case SyntaxKind.ReturnStatement:
return visitNode(cbNode, (node as ReturnStatement).expression);
case SyntaxKind.WithStatement:
return visitNode(cbNode, (node as WithStatement).expression) ||
visitNode(cbNode, (node as WithStatement).statement);
case SyntaxKind.SwitchStatement:
return visitNode(cbNode, (node as SwitchStatement).expression) ||
visitNode(cbNode, (node as SwitchStatement).caseBlock);
case SyntaxKind.CaseBlock:
return visitNodes(cbNode, cbNodes, (node as CaseBlock).clauses);
case SyntaxKind.CaseClause:
return visitNode(cbNode, (node as CaseClause).expression) ||
visitNodes(cbNode, cbNodes, (node as CaseClause).statements);
case SyntaxKind.DefaultClause:
return visitNodes(cbNode, cbNodes, (node as DefaultClause).statements);
case SyntaxKind.LabeledStatement:
return visitNode(cbNode, (node as LabeledStatement).label) ||
visitNode(cbNode, (node as LabeledStatement).statement);
case SyntaxKind.ThrowStatement:
return visitNode(cbNode, (node as ThrowStatement).expression);
case SyntaxKind.TryStatement:
return visitNode(cbNode, (node as TryStatement).tryBlock) ||
visitNode(cbNode, (node as TryStatement).catchClause) ||
visitNode(cbNode, (node as TryStatement).finallyBlock);
case SyntaxKind.CatchClause:
return visitNode(cbNode, (node as CatchClause).variableDeclaration) ||
visitNode(cbNode, (node as CatchClause).block);
case SyntaxKind.Decorator:
return visitNode(cbNode, (node as Decorator).expression);
case SyntaxKind.ClassDeclaration:
case SyntaxKind.ClassExpression:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, (node as ClassLikeDeclaration).name) ||
visitNodes(cbNode, cbNodes, (node as ClassLikeDeclaration).typeParameters) ||
visitNodes(cbNode, cbNodes, (node as ClassLikeDeclaration).heritageClauses) ||
visitNodes(cbNode, cbNodes, (node as ClassLikeDeclaration).members);
case SyntaxKind.InterfaceDeclaration:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, (node as InterfaceDeclaration).name) ||
visitNodes(cbNode, cbNodes, (node as InterfaceDeclaration).typeParameters) ||
visitNodes(cbNode, cbNodes, (node as ClassDeclaration).heritageClauses) ||
visitNodes(cbNode, cbNodes, (node as InterfaceDeclaration).members);
case SyntaxKind.TypeAliasDeclaration:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, (node as TypeAliasDeclaration).name) ||
visitNodes(cbNode, cbNodes, (node as TypeAliasDeclaration).typeParameters) ||
visitNode(cbNode, (node as TypeAliasDeclaration).type);
case SyntaxKind.EnumDeclaration:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, (node as EnumDeclaration).name) ||
visitNodes(cbNode, cbNodes, (node as EnumDeclaration).members);
case SyntaxKind.EnumMember:
return visitNode(cbNode, (node as EnumMember).name) ||
visitNode(cbNode, (node as EnumMember).initializer);
case SyntaxKind.ModuleDeclaration:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, (node as ModuleDeclaration).name) ||
visitNode(cbNode, (node as ModuleDeclaration).body);
case SyntaxKind.ImportEqualsDeclaration:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, (node as ImportEqualsDeclaration).name) ||
visitNode(cbNode, (node as ImportEqualsDeclaration).moduleReference);
case SyntaxKind.ImportDeclaration:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, (node as ImportDeclaration).importClause) ||
visitNode(cbNode, (node as ImportDeclaration).moduleSpecifier) ||
visitNode(cbNode, (node as ImportDeclaration).assertClause);
case SyntaxKind.ImportClause:
return visitNode(cbNode, (node as ImportClause).name) ||
visitNode(cbNode, (node as ImportClause).namedBindings);
case SyntaxKind.AssertClause:
return visitNodes(cbNode, cbNodes, (node as AssertClause).elements);
case SyntaxKind.AssertEntry:
return visitNode(cbNode, (node as AssertEntry).name) ||
visitNode(cbNode, (node as AssertEntry).value);
case SyntaxKind.NamespaceExportDeclaration:
return visitNode(cbNode, (node as NamespaceExportDeclaration).name);
case SyntaxKind.NamespaceImport:
return visitNode(cbNode, (node as NamespaceImport).name);
case SyntaxKind.NamespaceExport:
return visitNode(cbNode, (node as NamespaceExport).name);
case SyntaxKind.NamedImports:
case SyntaxKind.NamedExports:
return visitNodes(cbNode, cbNodes, (node as NamedImportsOrExports).elements);
case SyntaxKind.ExportDeclaration:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, (node as ExportDeclaration).exportClause) ||
visitNode(cbNode, (node as ExportDeclaration).moduleSpecifier) ||
visitNode(cbNode, (node as ExportDeclaration).assertClause);
case SyntaxKind.ImportSpecifier:
case SyntaxKind.ExportSpecifier:
return visitNode(cbNode, (node as ImportOrExportSpecifier).propertyName) ||
visitNode(cbNode, (node as ImportOrExportSpecifier).name);
case SyntaxKind.ExportAssignment:
return visitNodes(cbNode, cbNodes, node.decorators) ||
visitNodes(cbNode, cbNodes, node.modifiers) ||
visitNode(cbNode, (node as ExportAssignment).expression);
case SyntaxKind.TemplateExpression:
return visitNode(cbNode, (node as TemplateExpression).head) || visitNodes(cbNode, cbNodes, (node as TemplateExpression).templateSpans);
case SyntaxKind.TemplateSpan:
return visitNode(cbNode, (node as TemplateSpan).expression) || visitNode(cbNode, (node as TemplateSpan).literal);
case SyntaxKind.TemplateLiteralType:
return visitNode(cbNode, (node as TemplateLiteralTypeNode).head) || visitNodes(cbNode, cbNodes, (node as TemplateLiteralTypeNode).templateSpans);
case SyntaxKind.TemplateLiteralTypeSpan:
return visitNode(cbNode, (node as TemplateLiteralTypeSpan).type) || visitNode(cbNode, (node as TemplateLiteralTypeSpan).literal);
case SyntaxKind.ComputedPropertyName:
return visitNode(cbNode, (node as ComputedPropertyName).expression);
case SyntaxKind.HeritageClause:
return visitNodes(cbNode, cbNodes, (node as HeritageClause).types);
case SyntaxKind.ExpressionWithTypeArguments:
return visitNode(cbNode, (node as ExpressionWithTypeArguments).expression) ||
visitNodes(cbNode, cbNodes, (node as ExpressionWithTypeArguments).typeArguments);
case SyntaxKind.ExternalModuleReference:
return visitNode(cbNode, (node as ExternalModuleReference).expression);
case SyntaxKind.MissingDeclaration:
return visitNodes(cbNode, cbNodes, node.decorators);
case SyntaxKind.CommaListExpression:
return visitNodes(cbNode, cbNodes, (node as CommaListExpression).elements);
case SyntaxKind.JsxElement:
return visitNode(cbNode, (node as JsxElement).openingElement) ||
visitNodes(cbNode, cbNodes, (node as JsxElement).children) ||
visitNode(cbNode, (node as JsxElement).closingElement);
case SyntaxKind.JsxFragment:
return visitNode(cbNode, (node as JsxFragment).openingFragment) ||
visitNodes(cbNode, cbNodes, (node as JsxFragment).children) ||
visitNode(cbNode, (node as JsxFragment).closingFragment);
case SyntaxKind.JsxSelfClosingElement:
case SyntaxKind.JsxOpeningElement:
return visitNode(cbNode, (node as JsxOpeningLikeElement).tagName) ||
visitNodes(cbNode, cbNodes, (node as JsxOpeningLikeElement).typeArguments) ||
visitNode(cbNode, (node as JsxOpeningLikeElement).attributes);
case SyntaxKind.JsxAttributes:
return visitNodes(cbNode, cbNodes, (node as JsxAttributes).properties);
case SyntaxKind.JsxAttribute:
return visitNode(cbNode, (node as JsxAttribute).name) ||
visitNode(cbNode, (node as JsxAttribute).initializer);
case SyntaxKind.JsxSpreadAttribute:
return visitNode(cbNode, (node as JsxSpreadAttribute).expression);
case SyntaxKind.JsxExpression:
return visitNode(cbNode, (node as JsxExpression).dotDotDotToken) ||
visitNode(cbNode, (node as JsxExpression).expression);
case SyntaxKind.JsxClosingElement:
return visitNode(cbNode, (node as JsxClosingElement).tagName);
case SyntaxKind.OptionalType:
case SyntaxKind.RestType:
case SyntaxKind.JSDocTypeExpression:
case SyntaxKind.JSDocNonNullableType:
case SyntaxKind.JSDocNullableType:
case SyntaxKind.JSDocOptionalType:
case SyntaxKind.JSDocVariadicType:
return visitNode(cbNode, (node as OptionalTypeNode | RestTypeNode | JSDocTypeExpression | JSDocTypeReferencingNode).type);
case SyntaxKind.JSDocFunctionType:
return visitNodes(cbNode, cbNodes, (node as JSDocFunctionType).parameters) ||
visitNode(cbNode, (node as JSDocFunctionType).type);
case SyntaxKind.JSDocComment:
return (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray<JSDocComment> | undefined))
|| visitNodes(cbNode, cbNodes, (node as JSDoc).tags);
case SyntaxKind.JSDocSeeTag:
return visitNode(cbNode, (node as JSDocSeeTag).tagName) ||
visitNode(cbNode, (node as JSDocSeeTag).name) ||
(typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray<JSDocComment> | undefined));
case SyntaxKind.JSDocNameReference:
return visitNode(cbNode, (node as JSDocNameReference).name);
case SyntaxKind.JSDocMemberName:
return visitNode(cbNode, (node as JSDocMemberName).left) ||
visitNode(cbNode, (node as JSDocMemberName).right);
case SyntaxKind.JSDocParameterTag:
case SyntaxKind.JSDocPropertyTag:
return visitNode(cbNode, (node as JSDocTag).tagName) ||
((node as JSDocPropertyLikeTag).isNameFirst
? visitNode(cbNode, (node as JSDocPropertyLikeTag).name) ||
visitNode(cbNode, (node as JSDocPropertyLikeTag).typeExpression) ||
(typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray<JSDocComment> | undefined))
: visitNode(cbNode, (node as JSDocPropertyLikeTag).typeExpression) ||
visitNode(cbNode, (node as JSDocPropertyLikeTag).name) ||
(typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray<JSDocComment> | undefined)));
case SyntaxKind.JSDocAuthorTag:
return visitNode(cbNode, (node as JSDocTag).tagName) ||
(typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray<JSDocComment> | undefined));
case SyntaxKind.JSDocImplementsTag:
return visitNode(cbNode, (node as JSDocTag).tagName) ||
visitNode(cbNode, (node as JSDocImplementsTag).class) ||
(typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray<JSDocComment> | undefined));
case SyntaxKind.JSDocAugmentsTag:
return visitNode(cbNode, (node as JSDocTag).tagName) ||
visitNode(cbNode, (node as JSDocAugmentsTag).class) ||
(typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray<JSDocComment> | undefined));
case SyntaxKind.JSDocTemplateTag:
return visitNode(cbNode, (node as JSDocTag).tagName) ||
visitNode(cbNode, (node as JSDocTemplateTag).constraint) ||
visitNodes(cbNode, cbNodes, (node as JSDocTemplateTag).typeParameters) ||
(typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray<JSDocComment> | undefined));
case SyntaxKind.JSDocTypedefTag:
return visitNode(cbNode, (node as JSDocTag).tagName) ||
((node as JSDocTypedefTag).typeExpression &&
(node as JSDocTypedefTag).typeExpression!.kind === SyntaxKind.JSDocTypeExpression
? visitNode(cbNode, (node as JSDocTypedefTag).typeExpression) ||
visitNode(cbNode, (node as JSDocTypedefTag).fullName) ||
(typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray<JSDocComment> | undefined))
: visitNode(cbNode, (node as JSDocTypedefTag).fullName) ||
visitNode(cbNode, (node as JSDocTypedefTag).typeExpression) ||
(typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray<JSDocComment> | undefined)));
case SyntaxKind.JSDocCallbackTag:
return visitNode(cbNode, (node as JSDocTag).tagName) ||
visitNode(cbNode, (node as JSDocCallbackTag).fullName) ||
visitNode(cbNode, (node as JSDocCallbackTag).typeExpression) ||
(typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray<JSDocComment> | undefined));
case SyntaxKind.JSDocReturnTag:
case SyntaxKind.JSDocTypeTag:
case SyntaxKind.JSDocThisTag:
case SyntaxKind.JSDocEnumTag:
return visitNode(cbNode, (node as JSDocTag).tagName) ||
visitNode(cbNode, (node as JSDocReturnTag | JSDocTypeTag | JSDocThisTag | JSDocEnumTag).typeExpression) ||
(typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray<JSDocComment> | undefined));
case SyntaxKind.JSDocSignature:
return forEach((node as JSDocSignature).typeParameters, cbNode) ||
forEach((node as JSDocSignature).parameters, cbNode) ||
visitNode(cbNode, (node as JSDocSignature).type);
case SyntaxKind.JSDocLink:
case SyntaxKind.JSDocLinkCode:
case SyntaxKind.JSDocLinkPlain:
return visitNode(cbNode, (node as JSDocLink | JSDocLinkCode | JSDocLinkPlain).name);
case SyntaxKind.JSDocTypeLiteral:
return forEach((node as JSDocTypeLiteral).jsDocPropertyTags, cbNode);
case SyntaxKind.JSDocTag:
case SyntaxKind.JSDocClassTag:
case SyntaxKind.JSDocPublicTag:
case SyntaxKind.JSDocPrivateTag:
case SyntaxKind.JSDocProtectedTag:
case SyntaxKind.JSDocReadonlyTag:
case SyntaxKind.JSDocDeprecatedTag:
return visitNode(cbNode, (node as JSDocTag).tagName)
|| (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray<JSDocComment> | undefined));
case SyntaxKind.PartiallyEmittedExpression:
return visitNode(cbNode, (node as PartiallyEmittedExpression).expression);
}
}
/** @internal */
/**
* 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; additionally,
* unlike `forEachChild`, 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.
*
* @param node a given node to visit its children
* @param cbNode a callback to be invoked for all child nodes
* @param cbNodes a callback to be invoked for embedded array
*
* @remarks Unlike `forEachChild`, `forEachChildRecursively` handles recursively invoking the traversal on each child node found,
* and while doing so, handles traversing the structure without relying on the callstack to encode the tree structure.
*/
export function forEachChildRecursively<T>(rootNode: Node, cbNode: (node: Node, parent: Node) => T | "skip" | undefined, cbNodes?: (nodes: NodeArray<Node>, parent: Node) => T | "skip" | undefined): T | undefined {
const queue: (Node | NodeArray<Node>)[] = gatherPossibleChildren(rootNode);
const parents: Node[] = []; // tracks parent references for elements in queue
while (parents.length < queue.length) {
parents.push(rootNode);
}
while (queue.length !== 0) {
const current = queue.pop()!;
const parent = parents.pop()!;
if (isArray(current)) {
if (cbNodes) {
const res = cbNodes(current, parent);
if (res) {
if (res === "skip") continue;
return res;
}
}
for (let i = current.length - 1; i >= 0; --i) {
queue.push(current[i]);
parents.push(parent);
}
}
else {
const res = cbNode(current, parent);
if (res) {
if (res === "skip") continue;
return res;
}
if (current.kind >= SyntaxKind.FirstNode) {
// add children in reverse order to the queue, so popping gives the first child
for (const child of gatherPossibleChildren(current)) {
queue.push(child);
parents.push(current);
}
}
}
}
}
function gatherPossibleChildren(node: Node) {
const children: (Node | NodeArray<Node>)[] = [];
forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal
return children;
function addWorkItem(n: Node | NodeArray<Node>) {
children.unshift(n);
}
}
export function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes = false, scriptKind?: ScriptKind): SourceFile {
tracing?.push(tracing.Phase.Parse, "createSourceFile", { path: fileName }, /*separateBeginAndEnd*/ true);
performance.mark("beforeParse");
let result: SourceFile;
perfLogger.logStartParseSourceFile(fileName);
if (languageVersion === ScriptTarget.JSON) {
result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, ScriptKind.JSON);
}
else {
result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind);
}
perfLogger.logStopParseSourceFile();
performance.mark("afterParse");
performance.measure("Parse", "beforeParse", "afterParse");
tracing?.pop();
return result;
}
export function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName | undefined {
return Parser.parseIsolatedEntityName(text, languageVersion);
}
/**
* Parse json text into SyntaxTree and return node and parse errors if any
* @param fileName
* @param sourceText
*/
export function parseJsonText(fileName: string, sourceText: string): JsonSourceFile {
return Parser.parseJsonText(fileName, sourceText);
}
// See also `isExternalOrCommonJsModule` in utilities.ts
export function isExternalModule(file: SourceFile): boolean {
return file.externalModuleIndicator !== undefined;
}
// Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter
// indicates what changed between the 'text' that this SourceFile has and the 'newText'.
// The SourceFile will be created with the compiler attempting to reuse as many nodes from
// this file as possible.
//
// Note: this function mutates nodes from this SourceFile. That means any existing nodes
// from this SourceFile that are being held onto may change as a result (including
// becoming detached from any SourceFile). It is recommended that this SourceFile not
// be used once 'update' is called on it.
export function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks = false): SourceFile {
const newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks);
// Because new source file node is created, it may not have the flag PossiblyContainDynamicImport. This is the case if there is no new edit to add dynamic import.
// We will manually port the flag to the new source file.
(newSourceFile as Mutable<SourceFile>).flags |= (sourceFile.flags & NodeFlags.PermanentlySetIncrementalFlags);
return newSourceFile;
}
/* @internal */
export function parseIsolatedJSDocComment(content: string, start?: number, length?: number) {
const result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length);
if (result && result.jsDoc) {
// because the jsDocComment was parsed out of the source file, it might
// not be covered by the fixupParentReferences.
Parser.fixupParentReferences(result.jsDoc);
}
return result;
}
/* @internal */
// Exposed only for testing.
export function parseJSDocTypeExpressionForTests(content: string, start?: number, length?: number) {
return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length);
}
// Implement the parser as a singleton module. We do this for perf reasons because creating
// parser instances can actually be expensive enough to impact us on projects with many source
// files.
namespace Parser {
// Share a single scanner across all calls to parse a source file. This helps speed things
// up by avoiding the cost of creating/compiling scanners over and over again.
const scanner = createScanner(ScriptTarget.Latest, /*skipTrivia*/ true);
const disallowInAndDecoratorContext = NodeFlags.DisallowInContext | NodeFlags.DecoratorContext;
// capture constructors in 'initializeState' to avoid null checks
// tslint:disable variable-name
let NodeConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
let TokenConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
let IdentifierConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
let PrivateIdentifierConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
let SourceFileConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
// tslint:enable variable-name
function countNode(node: Node) {
nodeCount++;
return node;
}
// Rather than using `createBaseNodeFactory` here, we establish a `BaseNodeFactory` that closes over the
// constructors above, which are reset each time `initializeState` is called.
const baseNodeFactory: BaseNodeFactory = {
createBaseSourceFileNode: kind => countNode(new SourceFileConstructor(kind, /*pos*/ 0, /*end*/ 0)),
createBaseIdentifierNode: kind => countNode(new IdentifierConstructor(kind, /*pos*/ 0, /*end*/ 0)),
createBasePrivateIdentifierNode: kind => countNode(new PrivateIdentifierConstructor(kind, /*pos*/ 0, /*end*/ 0)),
createBaseTokenNode: kind => countNode(new TokenConstructor(kind, /*pos*/ 0, /*end*/ 0)),
createBaseNode: kind => countNode(new NodeConstructor(kind, /*pos*/ 0, /*end*/ 0))
};
const factory = createNodeFactory(NodeFactoryFlags.NoParenthesizerRules | NodeFactoryFlags.NoNodeConverters | NodeFactoryFlags.NoOriginalNode, baseNodeFactory);
let fileName: string;
let sourceFlags: NodeFlags;
let sourceText: string;
let languageVersion: ScriptTarget;
let scriptKind: ScriptKind;
let languageVariant: LanguageVariant;
let parseDiagnostics: DiagnosticWithDetachedLocation[];
let jsDocDiagnostics: DiagnosticWithDetachedLocation[];
let syntaxCursor: IncrementalParser.SyntaxCursor | undefined;
let currentToken: SyntaxKind;
let nodeCount: number;
let identifiers: ESMap<string, string>;
let privateIdentifiers: ESMap<string, string>;
let identifierCount: number;
let parsingContext: ParsingContext;
let notParenthesizedArrow: Set<number> | undefined;
// Flags that dictate what parsing context we're in. For example:
// Whether or not we are in strict parsing mode. All that changes in strict parsing mode is
// that some tokens that would be considered identifiers may be considered keywords.
//
// When adding more parser context flags, consider which is the more common case that the
// flag will be in. This should be the 'false' state for that flag. The reason for this is
// that we don't store data in our nodes unless the value is in the *non-default* state. So,
// for example, more often than code 'allows-in' (or doesn't 'disallow-in'). We opt for
// 'disallow-in' set to 'false'. Otherwise, if we had 'allowsIn' set to 'true', then almost
// all nodes would need extra state on them to store this info.
//
// Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6
// grammar specification.
//
// An important thing about these context concepts. By default they are effectively inherited
// while parsing through every grammar production. i.e. if you don't change them, then when
// you parse a sub-production, it will have the same context values as the parent production.
// This is great most of the time. After all, consider all the 'expression' grammar productions
// and how nearly all of them pass along the 'in' and 'yield' context values:
//
// EqualityExpression[In, Yield] :
// RelationalExpression[?In, ?Yield]
// EqualityExpression[?In, ?Yield] == RelationalExpression[?In, ?Yield]
// EqualityExpression[?In, ?Yield] != RelationalExpression[?In, ?Yield]
// EqualityExpression[?In, ?Yield] === RelationalExpression[?In, ?Yield]
// EqualityExpression[?In, ?Yield] !== RelationalExpression[?In, ?Yield]
//
// Where you have to be careful is then understanding what the points are in the grammar
// where the values are *not* passed along. For example:
//
// SingleNameBinding[Yield,GeneratorParameter]
// [+GeneratorParameter]BindingIdentifier[Yield] Initializer[In]opt
// [~GeneratorParameter]BindingIdentifier[?Yield]Initializer[In, ?Yield]opt
//
// Here this is saying that if the GeneratorParameter context flag is set, that we should
// explicitly set the 'yield' context flag to false before calling into the BindingIdentifier
// and we should explicitly unset the 'yield' context flag before calling into the Initializer.
// production. Conversely, if the GeneratorParameter context flag is not set, then we
// should leave the 'yield' context flag alone.
//
// Getting this all correct is tricky and requires careful reading of the grammar to
// understand when these values should be changed versus when they should be inherited.
//
// Note: it should not be necessary to save/restore these flags during speculative/lookahead
// parsing. These context flags are naturally stored and restored through normal recursive
// descent parsing and unwinding.
let contextFlags: NodeFlags;
// Indicates whether we are currently parsing top-level statements.
let topLevel = true;
// Whether or not we've had a parse error since creating the last AST node. If we have
// encountered an error, it will be stored on the next AST node we create. Parse errors
// can be broken down into three categories:
//
// 1) An error that occurred during scanning. For example, an unterminated literal, or a
// character that was completely not understood.
//
// 2) A token was expected, but was not present. This type of error is commonly produced
// by the 'parseExpected' function.
//
// 3) A token was present that no parsing function was able to consume. This type of error
// only occurs in the 'abortParsingListOrMoveToNextToken' function when the parser
// decides to skip the token.
//
// In all of these cases, we want to mark the next node as having had an error before it.
// With this mark, we can know in incremental settings if this node can be reused, or if
// we have to reparse it. If we don't keep this information around, we may just reuse the
// node. in that event we would then not produce the same errors as we did before, causing
// significant confusion problems.
//
// Note: it is necessary that this value be saved/restored during speculative/lookahead
// parsing. During lookahead parsing, we will often create a node. That node will have
// this value attached, and then this value will be set back to 'false'. If we decide to
// rewind, we must get back to the same value we had prior to the lookahead.
//
// Note: any errors at the end of the file that do not precede a regular node, should get
// attached to the EOF token.
let parseErrorBeforeNextFinishedNode = false;
export function parseSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, syntaxCursor: IncrementalParser.SyntaxCursor | undefined, setParentNodes = false, scriptKind?: ScriptKind): SourceFile {
scriptKind = ensureScriptKind(fileName, scriptKind);
if (scriptKind === ScriptKind.JSON) {
const result = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes);
convertToObjectWorker(result, result.statements[0]?.expression, result.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
result.referencedFiles = emptyArray;
result.typeReferenceDirectives = emptyArray;
result.libReferenceDirectives = emptyArray;
result.amdDependencies = emptyArray;
result.hasNoDefaultLib = false;
result.pragmas = emptyMap as ReadonlyPragmaMap;
return result;
}
initializeState(fileName, sourceText, languageVersion, syntaxCursor, scriptKind);
const result = parseSourceFileWorker(languageVersion, setParentNodes, scriptKind);
clearState();
return result;
}
export function parseIsolatedEntityName(content: string, languageVersion: ScriptTarget): EntityName | undefined {
// Choice of `isDeclarationFile` should be arbitrary
initializeState("", content, languageVersion, /*syntaxCursor*/ undefined, ScriptKind.JS);
// Prime the scanner.
nextToken();
const entityName = parseEntityName(/*allowReservedWords*/ true);
const isInvalid = token() === SyntaxKind.EndOfFileToken && !parseDiagnostics.length;
clearState();
return isInvalid ? entityName : undefined;
}
export function parseJsonText(fileName: string, sourceText: string, languageVersion: ScriptTarget = ScriptTarget.ES2015, syntaxCursor?: IncrementalParser.SyntaxCursor, setParentNodes = false): JsonSourceFile {
initializeState(fileName, sourceText, languageVersion, syntaxCursor, ScriptKind.JSON);
sourceFlags = contextFlags;
// Prime the scanner.
nextToken();
const pos = getNodePos();
let statements, endOfFileToken;
if (token() === SyntaxKind.EndOfFileToken) {
statements = createNodeArray([], pos, pos);
endOfFileToken = parseTokenNode<EndOfFileToken>();
}
else {
// Loop and synthesize an ArrayLiteralExpression if there are more than
// one top-level expressions to ensure all input text is consumed.
let expressions: Expression[] | Expression | undefined;
while (token() !== SyntaxKind.EndOfFileToken) {
let expression;
switch (token()) {
case SyntaxKind.OpenBracketToken:
expression = parseArrayLiteralExpression();
break;
case SyntaxKind.TrueKeyword:
case SyntaxKind.FalseKeyword:
case SyntaxKind.NullKeyword:
expression = parseTokenNode<BooleanLiteral | NullLiteral>();
break;
case SyntaxKind.MinusToken:
if (lookAhead(() => nextToken() === SyntaxKind.NumericLiteral && nextToken() !== SyntaxKind.ColonToken)) {
expression = parsePrefixUnaryExpression() as JsonMinusNumericLiteral;
}
else {
expression = parseObjectLiteralExpression();
}
break;
case SyntaxKind.NumericLiteral:
case SyntaxKind.StringLiteral:
if (lookAhead(() => nextToken() !== SyntaxKind.ColonToken)) {
expression = parseLiteralNode() as StringLiteral | NumericLiteral;
break;
}
// falls through
default:
expression = parseObjectLiteralExpression();
break;
}
// Error recovery: collect multiple top-level expressions
if (expressions && isArray(expressions)) {
expressions.push(expression);
}
else if (expressions) {
expressions = [expressions, expression];
}
else {
expressions = expression;
if (token() !== SyntaxKind.EndOfFileToken) {
parseErrorAtCurrentToken(Diagnostics.Unexpected_token);
}
}
}
const expression = isArray(expressions) ? finishNode(factory.createArrayLiteralExpression(expressions), pos) : Debug.checkDefined(expressions);
const statement = factory.createExpressionStatement(expression) as JsonObjectExpressionStatement;
finishNode(statement, pos);
statements = createNodeArray([statement], pos);
endOfFileToken = parseExpectedToken(SyntaxKind.EndOfFileToken, Diagnostics.Unexpected_token);
}
// Set source file so that errors will be reported with this file name
const sourceFile = createSourceFile(fileName, ScriptTarget.ES2015, ScriptKind.JSON, /*isDeclaration*/ false, statements, endOfFileToken, sourceFlags);
if (setParentNodes) {
fixupParentReferences(sourceFile);
}
sourceFile.nodeCount = nodeCount;
sourceFile.identifierCount = identifierCount;
sourceFile.identifiers = identifiers;
sourceFile.parseDiagnostics = attachFileToDiagnostics(parseDiagnostics, sourceFile);
if (jsDocDiagnostics) {
sourceFile.jsDocDiagnostics = attachFileToDiagnostics(jsDocDiagnostics, sourceFile);
}
const result = sourceFile as JsonSourceFile;
clearState();
return result;
}
function initializeState(_fileName: string, _sourceText: string, _languageVersion: ScriptTarget, _syntaxCursor: IncrementalParser.SyntaxCursor | undefined, _scriptKind: ScriptKind) {
NodeConstructor = objectAllocator.getNodeConstructor();
TokenConstructor = objectAllocator.getTokenConstructor();
IdentifierConstructor = objectAllocator.getIdentifierConstructor();
PrivateIdentifierConstructor = objectAllocator.getPrivateIdentifierConstructor();
SourceFileConstructor = objectAllocator.getSourceFileConstructor();
fileName = normalizePath(_fileName);
sourceText = _sourceText;
languageVersion = _languageVersion;
syntaxCursor = _syntaxCursor;
scriptKind = _scriptKind;
languageVariant = getLanguageVariant(_scriptKind);
parseDiagnostics = [];
parsingContext = 0;
identifiers = new Map<string, string>();
privateIdentifiers = new Map<string, string>();
identifierCount = 0;
nodeCount = 0;
sourceFlags = 0;
topLevel = true;
switch (scriptKind) {
case ScriptKind.JS:
case ScriptKind.JSX:
contextFlags = NodeFlags.JavaScriptFile;
break;