forked from microsoft/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvisitor.ts
More file actions
960 lines (888 loc) · 41.7 KB
/
Copy pathvisitor.ts
File metadata and controls
960 lines (888 loc) · 41.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
/// <reference path="checker.ts" />
/// <reference path="factory.ts" />
/* @internal */
namespace ts {
export type VisitResult<T extends Node> = T | T[];
/**
* Describes an edge of a Node, used when traversing a syntax tree.
*/
interface NodeEdge {
/** The property name for the edge. */
name: string;
/** Indicates that the result is optional. */
optional?: boolean;
/** A callback used to test whether a node is valid. */
test?: (node: Node) => node is Node;
/** A callback used to lift a NodeArrayNode into a valid node. */
lift?: (nodes: NodeArray<Node>) => Node;
/** A callback used to parenthesize a node to preserve the intended order of operations. */
parenthesize?: (value: Node, parentNode: Node) => Node;
};
/**
* Describes the shape of a Node.
*/
type NodeTraversalPath = NodeEdge[];
/**
* This map contains information about the shape of each Node in "types.ts" pertaining to how
* each node should be traversed during a transformation.
*
* Each edge corresponds to a property in a Node subtype that should be traversed when visiting
* each child. The properties are assigned in the order in which traversal should occur.
*
* NOTE: This needs to be kept up to date with changes to nodes in "types.ts". Currently, this
* map is not comprehensive. Only node edges relevant to tree transformation are
* currently defined. We may extend this to be more comprehensive, and eventually
* supplant the existing `forEachChild` implementation if performance is not
* significantly impacted.
*/
const nodeEdgeTraversalMap: Map<NodeTraversalPath> = {
[SyntaxKind.QualifiedName]: [
{ name: "left", test: isEntityName },
{ name: "right", test: isIdentifier }
],
[SyntaxKind.ComputedPropertyName]: [
{ name: "expression", test: isExpression }
],
[SyntaxKind.Parameter]: [
{ name: "decorators", test: isDecorator },
{ name: "modifiers", test: isModifier },
{ name: "name", test: isBindingName },
{ name: "type", test: isTypeNode, optional: true },
{ name: "initializer", test: isExpression, optional: true, parenthesize: parenthesizeExpressionForList }
],
[SyntaxKind.Decorator]: [
{ name: "expression", test: isLeftHandSideExpression }
],
[SyntaxKind.PropertyDeclaration]: [
{ name: "decorators", test: isDecorator },
{ name: "modifiers", test: isModifier },
{ name: "name", test: isPropertyName },
{ name: "type", test: isTypeNode, optional: true },
{ name: "initializer", test: isExpression, optional: true }
],
[SyntaxKind.MethodDeclaration]: [
{ name: "decorators", test: isDecorator },
{ name: "modifiers", test: isModifier },
{ name: "name", test: isPropertyName },
{ name: "typeParameters", test: isTypeParameter },
{ name: "parameters", test: isParameter },
{ name: "type", test: isTypeNode, optional: true },
{ name: "body", test: isBlock, optional: true }
],
[SyntaxKind.Constructor]: [
{ name: "decorators", test: isDecorator },
{ name: "modifiers", test: isModifier },
{ name: "typeParameters", test: isTypeParameter },
{ name: "parameters", test: isParameter },
{ name: "type", test: isTypeNode, optional: true },
{ name: "body", test: isBlock, optional: true }
],
[SyntaxKind.GetAccessor]: [
{ name: "decorators", test: isDecorator },
{ name: "modifiers", test: isModifier },
{ name: "name", test: isPropertyName },
{ name: "typeParameters", test: isTypeParameter },
{ name: "parameters", test: isParameter },
{ name: "type", test: isTypeNode, optional: true },
{ name: "body", test: isBlock, optional: true }
],
[SyntaxKind.SetAccessor]: [
{ name: "decorators", test: isDecorator },
{ name: "modifiers", test: isModifier },
{ name: "name", test: isPropertyName },
{ name: "typeParameters", test: isTypeParameter },
{ name: "parameters", test: isParameter },
{ name: "type", test: isTypeNode, optional: true },
{ name: "body", test: isBlock, optional: true }
],
[SyntaxKind.ObjectBindingPattern]: [
{ name: "elements", test: isBindingElement }
],
[SyntaxKind.ArrayBindingPattern]: [
{ name: "elements", test: isBindingElement }
],
[SyntaxKind.BindingElement]: [
{ name: "propertyName", test: isPropertyName, optional: true },
{ name: "name", test: isBindingName },
{ name: "initializer", test: isExpression, optional: true, parenthesize: parenthesizeExpressionForList }
],
[SyntaxKind.ArrayLiteralExpression]: [
{ name: "elements", test: isExpression, parenthesize: parenthesizeExpressionForList }
],
[SyntaxKind.ObjectLiteralExpression]: [
{ name: "properties", test: isObjectLiteralElement }
],
[SyntaxKind.PropertyAccessExpression]: [
{ name: "expression", test: isLeftHandSideExpression, parenthesize: parenthesizeForAccess },
{ name: "name", test: isIdentifier }
],
[SyntaxKind.ElementAccessExpression]: [
{ name: "expression", test: isLeftHandSideExpression, parenthesize: parenthesizeForAccess },
{ name: "argumentExpression", test: isExpression }
],
[SyntaxKind.CallExpression]: [
{ name: "expression", test: isLeftHandSideExpression, parenthesize: parenthesizeForAccess },
{ name: "typeArguments", test: isTypeNode },
{ name: "arguments", test: isExpression, parenthesize: parenthesizeExpressionForList }
],
[SyntaxKind.NewExpression]: [
{ name: "expression", test: isLeftHandSideExpression, parenthesize: parenthesizeForNew },
{ name: "typeArguments", test: isTypeNode },
{ name: "arguments", test: isExpression, parenthesize: parenthesizeExpressionForList }
],
[SyntaxKind.TaggedTemplateExpression]: [
{ name: "tag", test: isLeftHandSideExpression, parenthesize: parenthesizeForAccess },
{ name: "template", test: isTemplate }
],
[SyntaxKind.TypeAssertionExpression]: [
{ name: "type", test: isTypeNode },
{ name: "expression", test: isUnaryExpression }
],
[SyntaxKind.ParenthesizedExpression]: [
{ name: "expression", test: isExpression }
],
[SyntaxKind.FunctionExpression]: [
{ name: "decorators", test: isDecorator },
{ name: "modifiers", test: isModifier },
{ name: "name", test: isIdentifier, optional: true },
{ name: "typeParameters", test: isTypeParameter },
{ name: "parameters", test: isParameter },
{ name: "type", test: isTypeNode, optional: true },
{ name: "body", test: isBlock, optional: true }
],
[SyntaxKind.ArrowFunction]: [
{ name: "decorators", test: isDecorator },
{ name: "modifiers", test: isModifier },
{ name: "typeParameters", test: isTypeParameter },
{ name: "parameters", test: isParameter },
{ name: "type", test: isTypeNode, optional: true },
{ name: "body", test: isConciseBody, lift: liftToBlock, parenthesize: parenthesizeConciseBody }
],
[SyntaxKind.DeleteExpression]: [
{ name: "expression", test: isUnaryExpression, parenthesize: parenthesizePrefixOperand }
],
[SyntaxKind.TypeOfExpression]: [
{ name: "expression", test: isUnaryExpression, parenthesize: parenthesizePrefixOperand }
],
[SyntaxKind.VoidExpression]: [
{ name: "expression", test: isUnaryExpression, parenthesize: parenthesizePrefixOperand }
],
[SyntaxKind.AwaitExpression]: [
{ name: "expression", test: isUnaryExpression, parenthesize: parenthesizePrefixOperand }
],
[SyntaxKind.PrefixUnaryExpression]: [
{ name: "operand", test: isUnaryExpression, parenthesize: parenthesizePrefixOperand }
],
[SyntaxKind.PostfixUnaryExpression]: [
{ name: "operand", test: isLeftHandSideExpression, parenthesize: parenthesizePostfixOperand }
],
[SyntaxKind.BinaryExpression]: [
{ name: "left", test: isExpression, parenthesize: (node: Expression, parent: BinaryExpression) => parenthesizeBinaryOperand(getOperator(parent), node, true, /*leftOperand*/ undefined) },
{ name: "right", test: isExpression, parenthesize: (node: Expression, parent: BinaryExpression) => parenthesizeBinaryOperand(getOperator(parent), node, false, parent.left) }
],
[SyntaxKind.ConditionalExpression]: [
{ name: "condition", test: isExpression },
{ name: "whenTrue", test: isExpression },
{ name: "whenFalse", test: isExpression }
],
[SyntaxKind.TemplateExpression]: [
{ name: "head", test: isTemplateLiteralFragment },
{ name: "templateSpans", test: isTemplateSpan }
],
[SyntaxKind.YieldExpression]: [
{ name: "expression", test: isExpression, optional: true }
],
[SyntaxKind.SpreadElementExpression]: [
{ name: "expression", test: isExpression, parenthesize: parenthesizeExpressionForList }
],
[SyntaxKind.ClassExpression]: [
{ name: "decorators", test: isDecorator },
{ name: "modifiers", test: isModifier },
{ name: "name", test: isIdentifier, optional: true },
{ name: "typeParameters", test: isTypeParameter },
{ name: "heritageClauses", test: isHeritageClause },
{ name: "members", test: isClassElement }
],
[SyntaxKind.ExpressionWithTypeArguments]: [
{ name: "expression", test: isLeftHandSideExpression, parenthesize: parenthesizeForAccess },
{ name: "typeArguments", test: isTypeNode }
],
[SyntaxKind.AsExpression]: [
{ name: "expression", test: isExpression },
{ name: "type", test: isTypeNode }
],
[SyntaxKind.TemplateSpan]: [
{ name: "expression", test: isExpression },
{ name: "literal", test: isTemplateLiteralFragment }
],
[SyntaxKind.Block]: [
{ name: "statements", test: isStatement }
],
[SyntaxKind.VariableStatement]: [
{ name: "decorators", test: isDecorator },
{ name: "modifiers", test: isModifier },
{ name: "declarationList", test: isVariableDeclarationList }
],
[SyntaxKind.ExpressionStatement]: [
{ name: "expression", test: isExpression, parenthesize: parenthesizeExpressionForExpressionStatement }
],
[SyntaxKind.IfStatement]: [
{ name: "expression", test: isExpression },
{ name: "thenStatement", test: isStatement, lift: liftToBlock },
{ name: "elseStatement", test: isStatement, lift: liftToBlock, optional: true }
],
[SyntaxKind.DoStatement]: [
{ name: "statement", test: isStatement, lift: liftToBlock },
{ name: "expression", test: isExpression }
],
[SyntaxKind.WhileStatement]: [
{ name: "expression", test: isExpression },
{ name: "statement", test: isStatement, lift: liftToBlock }
],
[SyntaxKind.ForStatement]: [
{ name: "initializer", test: isForInitializer, optional: true },
{ name: "condition", test: isExpression, optional: true },
{ name: "incrementor", test: isExpression, optional: true },
{ name: "statement", test: isStatement, lift: liftToBlock }
],
[SyntaxKind.ForInStatement]: [
{ name: "initializer", test: isForInitializer },
{ name: "expression", test: isExpression },
{ name: "statement", test: isStatement, lift: liftToBlock }
],
[SyntaxKind.ForOfStatement]: [
{ name: "initializer", test: isForInitializer },
{ name: "expression", test: isExpression },
{ name: "statement", test: isStatement, lift: liftToBlock }
],
[SyntaxKind.ContinueStatement]: [
{ name: "label", test: isIdentifier, optional: true }
],
[SyntaxKind.BreakStatement]: [
{ name: "label", test: isIdentifier, optional: true }
],
[SyntaxKind.ReturnStatement]: [
{ name: "expression", test: isExpression, optional: true }
],
[SyntaxKind.WithStatement]: [
{ name: "expression", test: isExpression },
{ name: "statement", test: isStatement, lift: liftToBlock }
],
[SyntaxKind.SwitchStatement]: [
{ name: "expression", test: isExpression },
{ name: "caseBlock", test: isCaseBlock }
],
[SyntaxKind.LabeledStatement]: [
{ name: "label", test: isIdentifier },
{ name: "statement", test: isStatement, lift: liftToBlock }
],
[SyntaxKind.ThrowStatement]: [
{ name: "expression", test: isExpression }
],
[SyntaxKind.TryStatement]: [
{ name: "tryBlock", test: isBlock },
{ name: "catchClause", test: isCatchClause, optional: true },
{ name: "finallyBlock", test: isBlock, optional: true }
],
[SyntaxKind.VariableDeclaration]: [
{ name: "name", test: isBindingName },
{ name: "type", test: isTypeNode, optional: true },
{ name: "initializer", test: isExpression, optional: true, parenthesize: parenthesizeExpressionForList }
],
[SyntaxKind.VariableDeclarationList]: [
{ name: "declarations", test: isVariableDeclaration }
],
[SyntaxKind.FunctionDeclaration]: [
{ name: "decorators", test: isDecorator },
{ name: "modifiers", test: isModifier },
{ name: "name", test: isIdentifier, optional: true },
{ name: "typeParameters", test: isTypeParameter },
{ name: "parameters", test: isParameter },
{ name: "type", test: isTypeNode, optional: true },
{ name: "body", test: isBlock, optional: true }
],
[SyntaxKind.ClassDeclaration]: [
{ name: "decorators", test: isDecorator },
{ name: "modifiers", test: isModifier },
{ name: "name", test: isIdentifier, optional: true },
{ name: "typeParameters", test: isTypeParameter },
{ name: "heritageClauses", test: isHeritageClause },
{ name: "members", test: isClassElement }
],
[SyntaxKind.EnumDeclaration]: [
{ name: "decorators", test: isDecorator },
{ name: "modifiers", test: isModifier },
{ name: "name", test: isIdentifier },
{ name: "members", test: isEnumMember }
],
[SyntaxKind.ModuleDeclaration]: [
{ name: "decorators", test: isDecorator },
{ name: "modifiers", test: isModifier },
{ name: "name", test: isModuleName },
{ name: "body", test: isModuleBody }
],
[SyntaxKind.ModuleBlock]: [
{ name: "statements", test: isStatement }
],
[SyntaxKind.CaseBlock]: [
{ name: "clauses", test: isCaseOrDefaultClause }
],
[SyntaxKind.ImportEqualsDeclaration]: [
{ name: "decorators", test: isDecorator },
{ name: "modifiers", test: isModifier },
{ name: "name", test: isIdentifier },
{ name: "moduleReference", test: isModuleReference }
],
[SyntaxKind.ImportDeclaration]: [
{ name: "decorators", test: isDecorator },
{ name: "modifiers", test: isModifier },
{ name: "importClause", test: isImportClause, optional: true },
{ name: "moduleSpecifier", test: isExpression }
],
[SyntaxKind.ImportClause]: [
{ name: "name", test: isIdentifier, optional: true },
{ name: "namedBindings", test: isNamedImportBindings, optional: true }
],
[SyntaxKind.NamespaceImport]: [
{ name: "name", test: isIdentifier }
],
[SyntaxKind.NamedImports]: [
{ name: "elements", test: isImportSpecifier }
],
[SyntaxKind.ImportSpecifier]: [
{ name: "propertyName", test: isIdentifier, optional: true },
{ name: "name", test: isIdentifier }
],
[SyntaxKind.ExportAssignment]: [
{ name: "decorators", test: isDecorator },
{ name: "modifiers", test: isModifier },
{ name: "expression", test: isExpression }
],
[SyntaxKind.ExportDeclaration]: [
{ name: "decorators", test: isDecorator },
{ name: "modifiers", test: isModifier },
{ name: "exportClause", test: isNamedExports, optional: true },
{ name: "moduleSpecifier", test: isExpression, optional: true }
],
[SyntaxKind.NamedExports]: [
{ name: "elements", test: isExportSpecifier }
],
[SyntaxKind.ExportSpecifier]: [
{ name: "propertyName", test: isIdentifier, optional: true },
{ name: "name", test: isIdentifier }
],
[SyntaxKind.ExternalModuleReference]: [
{ name: "expression", test: isExpression, optional: true }
],
[SyntaxKind.JsxElement]: [
{ name: "openingElement", test: isJsxOpeningElement },
{ name: "children", test: isJsxChild },
{ name: "closingElement", test: isJsxClosingElement }
],
[SyntaxKind.JsxSelfClosingElement]: [
{ name: "tagName", test: isEntityName },
{ name: "attributes", test: isJsxAttributeLike }
],
[SyntaxKind.JsxOpeningElement]: [
{ name: "tagName", test: isEntityName },
{ name: "attributes", test: isJsxAttributeLike }
],
[SyntaxKind.JsxClosingElement]: [
{ name: "tagName", test: isEntityName }
],
[SyntaxKind.JsxAttribute]: [
{ name: "name", test: isIdentifier },
{ name: "initializer", test: isStringLiteralOrJsxExpression, optional: true }
],
[SyntaxKind.JsxSpreadAttribute]: [
{ name: "expression", test: isExpression }
],
[SyntaxKind.JsxExpression]: [
{ name: "expression", test: isExpression, optional: true }
],
[SyntaxKind.CaseClause]: [
{ name: "expression", test: isExpression, parenthesize: parenthesizeExpressionForList },
{ name: "statements", test: isStatement }
],
[SyntaxKind.DefaultClause]: [
{ name: "statements", test: isStatement }
],
[SyntaxKind.HeritageClause]: [
{ name: "types", test: isExpressionWithTypeArguments }
],
[SyntaxKind.CatchClause]: [
{ name: "variableDeclaration", test: isVariableDeclaration },
{ name: "block", test: isBlock }
],
[SyntaxKind.PropertyAssignment]: [
{ name: "name", test: isPropertyName },
{ name: "initializer", test: isExpression, parenthesize: parenthesizeExpressionForList }
],
[SyntaxKind.ShorthandPropertyAssignment]: [
{ name: "name", test: isIdentifier },
{ name: "objectAssignmentInitializer", test: isExpression, optional: true }
],
[SyntaxKind.EnumMember]: [
{ name: "name", test: isPropertyName },
{ name: "initializer", test: isExpression, optional: true, parenthesize: parenthesizeExpressionForList }
],
[SyntaxKind.SourceFile]: [
{ name: "statements", test: isStatement }
],
[SyntaxKind.NotEmittedStatement]: [],
[SyntaxKind.PartiallyEmittedExpression]: [
{ name: "expression", test: isExpression }
]
};
/**
* Similar to `reduceLeft`, performs a reduction against each child of a node.
* NOTE: Unlike `forEachChild`, this does *not* visit every node. Only nodes added to the
* `nodeEdgeTraversalMap` above will be visited.
*
* @param node The node containing the children to reduce.
* @param f The callback function
* @param initial The initial value to supply to the reduction.
*/
export function reduceEachChild<T>(node: Node, f: (memo: T, node: Node) => T, initial: T): T {
if (node === undefined) {
return undefined;
}
let result = initial;
const edgeTraversalPath = nodeEdgeTraversalMap[node.kind];
if (edgeTraversalPath) {
for (const edge of edgeTraversalPath) {
const value = (<Map<any>>node)[edge.name];
if (value !== undefined) {
result = isArray(value)
? reduceLeft(<NodeArray<Node>>value, f, result)
: f(result, <Node>value);
}
}
}
return result;
}
/**
* Visits a Node using the supplied visitor, possibly returning a new Node in its place.
*
* @param node The Node to visit.
* @param visitor The callback used to visit the Node.
* @param test A callback to execute to verify the Node is valid.
* @param optional An optional value indicating whether the Node is itself optional.
* @param lift An optional callback to execute to lift a NodeArrayNode into a valid Node.
*/
export function visitNode<T extends Node>(node: T, visitor: (node: Node) => VisitResult<Node>, test: (node: Node) => boolean, optional?: boolean, lift?: (node: NodeArray<Node>) => T): T {
return <T>visitNodeWorker(node, visitor, test, optional, lift, /*parenthesize*/ undefined, /*parentNode*/ undefined);
}
/**
* Visits a Node using the supplied visitor, possibly returning a new Node in its place.
*
* @param node The Node to visit.
* @param visitor The callback used to visit the Node.
* @param test A callback to execute to verify the Node is valid.
* @param optional A value indicating whether the Node is itself optional.
* @param lift A callback to execute to lift a NodeArrayNode into a valid Node.
* @param parenthesize A callback used to parenthesize the node if needed.
* @param parentNode A parentNode for the node.
*/
function visitNodeWorker(node: Node, visitor: (node: Node) => VisitResult<Node>, test: (node: Node) => boolean, optional: boolean, lift: (node: Node[]) => Node, parenthesize: (node: Node, parentNode: Node) => Node, parentNode: Node): Node {
if (node === undefined) {
return undefined;
}
const visited = visitor(node);
if (visited === node) {
return node;
}
let visitedNode: Node;
if (visited === undefined) {
if (!optional) {
Debug.failNotOptional();
}
return undefined;
}
else if (isArray(visited)) {
visitedNode = (lift || extractSingleNode)(visited);
}
else {
visitedNode = visited;
}
if (parenthesize !== undefined) {
visitedNode = parenthesize(visitedNode, parentNode);
}
Debug.assertNode(visitedNode, test);
aggregateTransformFlags(visitedNode);
return visitedNode;
}
/**
* Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place.
*
* @param nodes The NodeArray to visit.
* @param visitor The callback used to visit a Node.
* @param test A node test to execute for each node.
* @param start An optional value indicating the starting offset at which to start visiting.
* @param count An optional value indicating the maximum number of nodes to visit.
*/
export function visitNodes<T extends Node, TArray extends NodeArray<T>>(nodes: TArray, visitor: (node: Node) => VisitResult<Node>, test: (node: Node) => boolean, start?: number, count?: number): TArray {
return <TArray>visitNodesWorker(nodes, visitor, test, /*parenthesize*/ undefined, /*parentNode*/ undefined, start, count);
}
/**
* Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place.
*
* @param nodes The NodeArray to visit.
* @param visitor The callback used to visit a Node.
* @param test A node test to execute for each node.
* @param start An optional value indicating the starting offset at which to start visiting.
* @param count An optional value indicating the maximum number of nodes to visit.
*/
function visitNodesWorker(nodes: NodeArray<Node>, visitor: (node: Node) => VisitResult<Node>, test: (node: Node) => boolean, parenthesize: (node: Node, parentNode: Node) => Node, parentNode: Node, start: number, count: number): NodeArray<Node> {
if (nodes === undefined) {
return undefined;
}
let updated: NodeArray<Node>;
// Ensure start and count have valid values
const length = nodes.length;
if (start === undefined || start < 0) {
start = 0;
}
if (count === undefined || count > length - start) {
count = length - start;
}
if (start > 0 || count < length) {
// If we are not visiting all of the original nodes, we must always create a new array.
// Since this is a fragment of a node array, we do not copy over the previous location
// and will only copy over `hasTrailingComma` if we are including the last element.
updated = createNodeArray<Node>([], /*location*/ undefined,
/*hasTrailingComma*/ nodes.hasTrailingComma && start + count === length);
}
// Visit each original node.
for (let i = 0; i < count; i++) {
const node = nodes[i + start];
const visited = node !== undefined ? visitor(node) : undefined;
if (updated !== undefined || visited === undefined || visited !== node) {
if (updated === undefined) {
// Ensure we have a copy of `nodes`, up to the current index.
updated = createNodeArray(nodes.slice(0, i), /*location*/ nodes, nodes.hasTrailingComma);
}
addNodeWorker(updated, visited, /*addOnNewLine*/ undefined, test, parenthesize, parentNode, /*isVisiting*/ visited !== node);
}
}
return updated || nodes;
}
/**
* Visits each child of a Node using the supplied visitor, possibly returning a new Node of the same kind in its place.
*
* @param node The Node whose children will be visited.
* @param visitor The callback used to visit each child.
* @param context A lexical environment context for the visitor.
*/
export function visitEachChild<T extends Node>(node: T, visitor: (node: Node) => VisitResult<Node>, context: LexicalEnvironment): T;
export function visitEachChild<T extends Node>(node: T & Map<any>, visitor: (node: Node) => VisitResult<Node>, context: LexicalEnvironment): T {
if (node === undefined) {
return undefined;
}
let updated: T & Map<any>;
// If this node starts a new lexical environment, start a new lexical environment on the context.
const isNewLexicalEnvironment = nodeStartsNewLexicalEnvironment(node);
if (isNewLexicalEnvironment) {
context.startLexicalEnvironment();
}
const edgeTraversalPath = nodeEdgeTraversalMap[node.kind];
if (edgeTraversalPath) {
for (const edge of edgeTraversalPath) {
const value = <Node | NodeArray<Node>>node[edge.name];
if (value !== undefined) {
let visited: Node | NodeArray<Node>;
if (isArray(value)) {
const visitedArray = visitNodesWorker(value, visitor, edge.test, edge.parenthesize, node, 0, value.length);
visited = visitedArray;
}
else {
visited = visitNodeWorker(<Node>value, visitor, edge.test, edge.optional, edge.lift, edge.parenthesize, node);
}
if (updated !== undefined || visited !== value) {
if (updated === undefined) {
updated = getMutableClone(node);
}
if (visited !== value) {
updated[edge.name] = visited;
}
}
}
}
}
if (updated === undefined) {
updated = node;
}
if (isNewLexicalEnvironment) {
const declarations = context.endLexicalEnvironment();
if (declarations !== undefined && declarations.length > 0) {
updated = <T>mergeLexicalEnvironment(updated, declarations);
}
}
if (updated !== node) {
aggregateTransformFlags(updated);
updated.original = node;
}
return updated;
}
/**
* Appends a node to an array.
*
* @param to The destination array.
* @param from The source Node or NodeArrayNode.
*/
export function addNode<T extends Node>(to: T[], from: VisitResult<T>, startOnNewLine?: boolean): void {
addNodeWorker(to, from, startOnNewLine, /*test*/ undefined, /*parenthesize*/ undefined, /*parentNode*/ undefined, /*isVisiting*/ false);
}
/**
* Appends an array of nodes to an array.
*
* @param to The destination NodeArray.
* @param from The source array of Node or NodeArrayNode.
*/
export function addNodes<T extends Node>(to: T[], from: VisitResult<T>[], startOnNewLine?: boolean): void {
addNodesWorker(to, from, startOnNewLine, /*test*/ undefined, /*parenthesize*/ undefined, /*parentNode*/ undefined, /*isVisiting*/ false);
}
function addNodeWorker(to: Node[], from: VisitResult<Node>, startOnNewLine: boolean, test: (node: Node) => boolean, parenthesize: (node: Node, parentNode: Node) => Node, parentNode: Node, isVisiting: boolean): void {
if (to && from) {
if (isArray(from)) {
addNodesWorker(to, from, startOnNewLine, test, parenthesize, parentNode, isVisiting);
}
else {
const node = parenthesize !== undefined
? parenthesize(from, parentNode)
: from;
Debug.assertNode(node, test);
if (startOnNewLine) {
node.startsOnNewLine = true;
}
if (isVisiting) {
aggregateTransformFlags(node);
}
to.push(node);
}
}
}
function addNodesWorker(to: Node[], from: VisitResult<Node>[], startOnNewLine: boolean, test: (node: Node) => boolean, parenthesize: (node: Node, parentNode: Node) => Node, parentNode: Node, isVisiting: boolean): void {
if (to && from) {
for (const node of from) {
addNodeWorker(to, node, startOnNewLine, test, parenthesize, parentNode, isVisiting);
}
}
}
/**
* Merge generated declarations of a lexical environment.
*
* @param node The source node.
* @param declarations The generated lexical declarations.
*/
function mergeLexicalEnvironment(node: Node, declarations: Statement[]): Node {
switch (node.kind) {
case SyntaxKind.SourceFile:
return mergeSourceFileLexicalEnvironment(<SourceFile>node, declarations);
case SyntaxKind.ModuleDeclaration:
return mergeModuleDeclarationLexicalEnvironment(<ModuleDeclaration>node, declarations);
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.Constructor:
case SyntaxKind.ArrowFunction:
return mergeFunctionLikeLexicalEnvironment(<FunctionLikeDeclaration>node, declarations);
}
Debug.fail("Node is not a valid lexical environment.");
}
/**
* Merge generated declarations of a lexical environment into a SourceFile.
*
* @param node The SourceFile node.
* @param declarations The generated lexical declarations.
*/
export function mergeSourceFileLexicalEnvironment(node: SourceFile, declarations: Statement[]): SourceFile {
if (declarations !== undefined && declarations.length) {
const mutableNode = getMutableClone(node);
mutableNode.statements = mergeStatements(mutableNode.statements, declarations);
return mutableNode;
}
return node;
}
/**
* Merge generated declarations of a lexical environment into a ModuleDeclaration.
*
* @param node The ModuleDeclaration node.
* @param declarations The generated lexical declarations.
*/
export function mergeModuleDeclarationLexicalEnvironment(node: ModuleDeclaration, declarations: Statement[]): ModuleDeclaration {
Debug.assert(node.body.kind === SyntaxKind.ModuleBlock);
if (declarations !== undefined && declarations.length) {
const mutableNode = getMutableClone(node);
mutableNode.body = mergeBlockLexicalEnvironment(<ModuleBlock>node.body, declarations);
return mutableNode;
}
return node;
}
/**
* Merge generated declarations of a lexical environment into a FunctionLikeDeclaration.
*
* @param node The function-like node.
* @param declarations The generated lexical declarations.
*/
function mergeFunctionLikeLexicalEnvironment(node: FunctionLikeDeclaration, declarations: Statement[]): FunctionLikeDeclaration {
Debug.assert(node.body !== undefined);
if (declarations !== undefined && declarations.length) {
const mutableNode = getMutableClone(node);
mutableNode.body = mergeConciseBodyLexicalEnvironment(mutableNode.body, declarations);
return mutableNode;
}
return node;
}
/**
* Merges generated lexical declarations into the FunctionBody of a non-arrow function-like declaration.
*
* @param node The ConciseBody of an arrow function.
* @param declarations The lexical declarations to merge.
*/
export function mergeFunctionBodyLexicalEnvironment(body: FunctionBody, declarations: Statement[]): FunctionBody {
if (declarations !== undefined && declarations.length > 0) {
return mergeBlockLexicalEnvironment(body, declarations);
}
return body;
}
/**
* Merges generated lexical declarations into the ConciseBody of an ArrowFunction.
*
* @param node The ConciseBody of an arrow function.
* @param declarations The lexical declarations to merge.
*/
export function mergeConciseBodyLexicalEnvironment(body: ConciseBody, declarations: Statement[]): ConciseBody {
if (declarations !== undefined && declarations.length > 0) {
if (isBlock(body)) {
return mergeBlockLexicalEnvironment(body, declarations);
}
else {
return createBlock([
createReturn(body),
...declarations
]);
}
}
return body;
}
/**
* Merge generated declarations of a lexical environment into a FunctionBody or ModuleBlock.
*
* @param node The block into which to merge lexical declarations.
* @param declarations The lexical declarations to merge.
*/
function mergeBlockLexicalEnvironment<T extends Block>(node: T, declarations: Statement[]): T {
const mutableNode = getMutableClone(node);
mutableNode.statements = mergeStatements(node.statements, declarations);
return mutableNode;
}
/**
* Merge generated declarations of a lexical environment into a NodeArray of Statement.
*
* @param statements The node array to concatentate with the supplied lexical declarations.
* @param declarations The lexical declarations to merge.
*/
function mergeStatements(statements: NodeArray<Statement>, declarations: Statement[]): NodeArray<Statement> {
return createNodeArray(concatenate(statements, declarations), /*location*/ statements);
}
/**
* Lifts a NodeArray containing only Statement nodes to a block.
*
* @param nodes The NodeArray.
*/
export function liftToBlock(nodes: Node[]): Statement {
Debug.assert(every(nodes, isStatement), "Cannot lift nodes to a Block.");
return <Statement>singleOrUndefined(nodes) || createBlock(<NodeArray<Statement>>nodes);
}
/**
* Extracts the single node from a NodeArray.
*
* @param nodes The NodeArray.
*/
function extractSingleNode(nodes: Node[]): Node {
Debug.assert(nodes.length <= 1, "Too many nodes written to output.");
return singleOrUndefined(nodes);
}
/**
* Aggregates the TransformFlags for a Node and its subtree.
*/
export function aggregateTransformFlags(node: Node): void {
aggregateTransformFlagsForNode(node);
}
/**
* Aggregates the TransformFlags for a Node and its subtree. The flags for the subtree are
* computed first, then the transform flags for the current node are computed from the subtree
* flags and the state of the current node. Finally, the transform flags of the node are
* returned, excluding any flags that should not be included in its parent node's subtree
* flags.
*/
function aggregateTransformFlagsForNode(node: Node): TransformFlags {
if (node === undefined) {
return TransformFlags.None;
}
else if (node.transformFlags & TransformFlags.HasComputedFlags) {
return node.transformFlags & ~node.excludeTransformFlags;
}
else {
const subtreeFlags = aggregateTransformFlagsForSubtree(node);
return computeTransformFlagsForNode(node, subtreeFlags);
}
}
/**
* Aggregates the transform flags for the subtree of a node.
*/
function aggregateTransformFlagsForSubtree(node: Node): TransformFlags {
// We do not transform ambient declarations or types, so there is no need to
// recursively aggregate transform flags.
if (hasModifier(node, ModifierFlags.Ambient) || isTypeNode(node)) {
return TransformFlags.None;
}
// Aggregate the transform flags of each child.
return reduceEachChild(node, aggregateTransformFlagsForChildNode, TransformFlags.None);
}
/**
* Aggregates the TransformFlags of a child node with the TransformFlags of its
* siblings.
*/
function aggregateTransformFlagsForChildNode(transformFlags: TransformFlags, child: Node): TransformFlags {
return transformFlags | aggregateTransformFlagsForNode(child);
}
export namespace Debug {
export function failNotOptional(message?: string) {
if (shouldAssert(AssertionLevel.Normal)) {
Debug.assert(false, message || "Node not optional.");
}
}
export function failBadSyntaxKind(node: Node, message?: string) {
if (shouldAssert(AssertionLevel.Normal)) {
Debug.assert(false,
message || "Unexpected node.",
() => `Node ${formatSyntaxKind(node.kind)} was unexpected.`);
}
}
export function assertNode<T extends Node>(node: Node, test: (node: Node) => boolean, message?: string): void {
if (shouldAssert(AssertionLevel.Normal)) {
Debug.assert(
test === undefined || test(node),
message || "Unexpected node.",
() => `Node ${formatSyntaxKind(node.kind)} did not pass test '${getFunctionName(test)}'.`);
};
}
function getFunctionName(func: Function) {
if (typeof func !== "function") {
return "";
}
else if (func.hasOwnProperty("name")) {
return (<any>func).name;
}
else {
const text = Function.prototype.toString.call(func);
const match = /^function\s+([\w\$]+)\s*\(/.exec(text);
return match ? match[1] : "";
}
}
}
}