/
ts.ts
2471 lines (2178 loc) · 115 KB
/
ts.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
/*@internal*/
namespace ts {
/**
* Indicates whether to emit type metadata in the new format.
*/
const USE_NEW_TYPE_METADATA_FORMAT = false;
const enum TypeScriptSubstitutionFlags {
/** Enables substitutions for namespace exports. */
NamespaceExports = 1 << 1,
/* Enables substitutions for unqualified enum members */
NonQualifiedEnumMembers = 1 << 3
}
const enum ClassFacts {
None = 0,
HasStaticInitializedProperties = 1 << 0,
HasConstructorDecorators = 1 << 1,
HasMemberDecorators = 1 << 2,
IsExportOfNamespace = 1 << 3,
IsNamedExternalExport = 1 << 4,
IsDefaultExternalExport = 1 << 5,
IsDerivedClass = 1 << 6,
UseImmediatelyInvokedFunctionExpression = 1 << 7,
HasAnyDecorators = HasConstructorDecorators | HasMemberDecorators,
NeedsName = HasStaticInitializedProperties | HasMemberDecorators,
MayNeedImmediatelyInvokedFunctionExpression = HasAnyDecorators | HasStaticInitializedProperties,
IsExported = IsExportOfNamespace | IsDefaultExternalExport | IsNamedExternalExport,
}
export function transformTypeScript(context: TransformationContext) {
const {
factory,
getEmitHelperFactory: emitHelpers,
startLexicalEnvironment,
resumeLexicalEnvironment,
endLexicalEnvironment,
hoistVariableDeclaration,
} = context;
const resolver = context.getEmitResolver();
const compilerOptions = context.getCompilerOptions();
const languageVersion = getEmitScriptTarget(compilerOptions);
const moduleKind = getEmitModuleKind(compilerOptions);
const typeSerializer = compilerOptions.emitDecoratorMetadata ? createRuntimeTypeSerializer(context) : undefined;
// Save the previous transformation hooks.
const previousOnEmitNode = context.onEmitNode;
const previousOnSubstituteNode = context.onSubstituteNode;
// Set new transformation hooks.
context.onEmitNode = onEmitNode;
context.onSubstituteNode = onSubstituteNode;
// Enable substitution for property/element access to emit const enum values.
context.enableSubstitution(SyntaxKind.PropertyAccessExpression);
context.enableSubstitution(SyntaxKind.ElementAccessExpression);
// These variables contain state that changes as we descend into the tree.
let currentSourceFile: SourceFile;
let currentNamespace: ModuleDeclaration;
let currentNamespaceContainerName: Identifier;
let currentLexicalScope: SourceFile | Block | ModuleBlock | CaseBlock;
let currentScopeFirstDeclarationsOfName: UnderscoreEscapedMap<Node> | undefined;
let currentClassHasParameterProperties: boolean | undefined;
/**
* Keeps track of whether expression substitution has been enabled for specific edge cases.
* They are persisted between each SourceFile transformation and should not be reset.
*/
let enabledSubstitutions: TypeScriptSubstitutionFlags;
/**
* Keeps track of whether we are within any containing namespaces when performing
* just-in-time substitution while printing an expression identifier.
*/
let applicableSubstitutions: TypeScriptSubstitutionFlags;
return transformSourceFileOrBundle;
function transformSourceFileOrBundle(node: SourceFile | Bundle) {
if (node.kind === SyntaxKind.Bundle) {
return transformBundle(node);
}
return transformSourceFile(node);
}
function transformBundle(node: Bundle) {
return factory.createBundle(node.sourceFiles.map(transformSourceFile), mapDefined(node.prepends, prepend => {
if (prepend.kind === SyntaxKind.InputFiles) {
return createUnparsedSourceFile(prepend, "js");
}
return prepend;
}));
}
/**
* Transform TypeScript-specific syntax in a SourceFile.
*
* @param node A SourceFile node.
*/
function transformSourceFile(node: SourceFile) {
if (node.isDeclarationFile) {
return node;
}
currentSourceFile = node;
const visited = saveStateAndInvoke(node, visitSourceFile);
addEmitHelpers(visited, context.readEmitHelpers());
currentSourceFile = undefined!;
return visited;
}
/**
* Visits a node, saving and restoring state variables on the stack.
*
* @param node The node to visit.
*/
function saveStateAndInvoke<T>(node: Node, f: (node: Node) => T): T {
// Save state
const savedCurrentScope = currentLexicalScope;
const savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
const savedCurrentClassHasParameterProperties = currentClassHasParameterProperties;
// Handle state changes before visiting a node.
onBeforeVisitNode(node);
const visited = f(node);
// Restore state
if (currentLexicalScope !== savedCurrentScope) {
currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
}
currentLexicalScope = savedCurrentScope;
currentClassHasParameterProperties = savedCurrentClassHasParameterProperties;
return visited;
}
/**
* Performs actions that should always occur immediately before visiting a node.
*
* @param node The node to visit.
*/
function onBeforeVisitNode(node: Node) {
switch (node.kind) {
case SyntaxKind.SourceFile:
case SyntaxKind.CaseBlock:
case SyntaxKind.ModuleBlock:
case SyntaxKind.Block:
currentLexicalScope = node as SourceFile | CaseBlock | ModuleBlock | Block;
currentScopeFirstDeclarationsOfName = undefined;
break;
case SyntaxKind.ClassDeclaration:
case SyntaxKind.FunctionDeclaration:
if (hasSyntacticModifier(node, ModifierFlags.Ambient)) {
break;
}
// Record these declarations provided that they have a name.
if ((node as ClassDeclaration | FunctionDeclaration).name) {
recordEmittedDeclarationInScope(node as ClassDeclaration | FunctionDeclaration);
}
else {
// These nodes should always have names unless they are default-exports;
// however, class declaration parsing allows for undefined names, so syntactically invalid
// programs may also have an undefined name.
Debug.assert(node.kind === SyntaxKind.ClassDeclaration || hasSyntacticModifier(node, ModifierFlags.Default));
}
break;
}
}
/**
* General-purpose node visitor.
*
* @param node The node to visit.
*/
function visitor(node: Node): VisitResult<Node> {
return saveStateAndInvoke(node, visitorWorker);
}
/**
* Visits and possibly transforms any node.
*
* @param node The node to visit.
*/
function visitorWorker(node: Node): VisitResult<Node> {
if (node.transformFlags & TransformFlags.ContainsTypeScript) {
return visitTypeScript(node);
}
return node;
}
/**
* Specialized visitor that visits the immediate children of a SourceFile.
*
* @param node The node to visit.
*/
function sourceElementVisitor(node: Node): VisitResult<Node> {
return saveStateAndInvoke(node, sourceElementVisitorWorker);
}
/**
* Specialized visitor that visits the immediate children of a SourceFile.
*
* @param node The node to visit.
*/
function sourceElementVisitorWorker(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.ImportDeclaration:
case SyntaxKind.ImportEqualsDeclaration:
case SyntaxKind.ExportAssignment:
case SyntaxKind.ExportDeclaration:
return visitElidableStatement(node as ImportDeclaration | ImportEqualsDeclaration | ExportAssignment | ExportDeclaration);
default:
return visitorWorker(node);
}
}
function visitElidableStatement(node: ImportDeclaration | ImportEqualsDeclaration | ExportAssignment | ExportDeclaration): VisitResult<Node> {
const parsed = getParseTreeNode(node);
if (parsed !== node) {
// If the node has been transformed by a `before` transformer, perform no ellision on it
// As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes
// We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`,
// and will trigger debug failures when debug verbosity is turned up
if (node.transformFlags & TransformFlags.ContainsTypeScript) {
// This node contains TypeScript, so we should visit its children.
return visitEachChild(node, visitor, context);
}
// Otherwise, we can just return the node
return node;
}
switch (node.kind) {
case SyntaxKind.ImportDeclaration:
return visitImportDeclaration(node);
case SyntaxKind.ImportEqualsDeclaration:
return visitImportEqualsDeclaration(node);
case SyntaxKind.ExportAssignment:
return visitExportAssignment(node);
case SyntaxKind.ExportDeclaration:
return visitExportDeclaration(node);
default:
Debug.fail("Unhandled ellided statement");
}
}
/**
* Specialized visitor that visits the immediate children of a namespace.
*
* @param node The node to visit.
*/
function namespaceElementVisitor(node: Node): VisitResult<Node> {
return saveStateAndInvoke(node, namespaceElementVisitorWorker);
}
/**
* Specialized visitor that visits the immediate children of a namespace.
*
* @param node The node to visit.
*/
function namespaceElementVisitorWorker(node: Node): VisitResult<Node> {
if (node.kind === SyntaxKind.ExportDeclaration ||
node.kind === SyntaxKind.ImportDeclaration ||
node.kind === SyntaxKind.ImportClause ||
(node.kind === SyntaxKind.ImportEqualsDeclaration &&
(node as ImportEqualsDeclaration).moduleReference.kind === SyntaxKind.ExternalModuleReference)) {
// do not emit ES6 imports and exports since they are illegal inside a namespace
return undefined;
}
else if (node.transformFlags & TransformFlags.ContainsTypeScript || hasSyntacticModifier(node, ModifierFlags.Export)) {
return visitTypeScript(node);
}
return node;
}
/**
* Gets a specialized visitor that visits the immediate children of a class with TypeScript syntax.
*
* @param parent The class containing the elements to visit.
*/
function getClassElementVisitor(parent: ClassLikeDeclaration): (node: Node) => VisitResult<Node> {
return node => saveStateAndInvoke(node, n => classElementVisitorWorker(n, parent));
}
/**
* Specialized visitor that visits the immediate children of a class with TypeScript syntax.
*
* @param node The node to visit.
*/
function classElementVisitorWorker(node: Node, parent: ClassLikeDeclaration): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.Constructor:
return visitConstructor(node as ConstructorDeclaration);
case SyntaxKind.PropertyDeclaration:
// Property declarations are not TypeScript syntax, but they must be visited
// for the decorator transformation.
return visitPropertyDeclaration(node as PropertyDeclaration, parent);
case SyntaxKind.GetAccessor:
// Get Accessors can have TypeScript modifiers, decorators, and type annotations.
return visitGetAccessor(node as GetAccessorDeclaration, parent);
case SyntaxKind.SetAccessor:
// Set Accessors can have TypeScript modifiers and type annotations.
return visitSetAccessor(node as SetAccessorDeclaration, parent);
case SyntaxKind.MethodDeclaration:
// TypeScript method declarations may have decorators, modifiers
// or type annotations.
return visitMethodDeclaration(node as MethodDeclaration, parent);
case SyntaxKind.ClassStaticBlockDeclaration:
return visitEachChild(node, visitor, context);
case SyntaxKind.SemicolonClassElement:
return node;
case SyntaxKind.IndexSignature:
// Index signatures are elided
return;
default:
return Debug.failBadSyntaxKind(node);
}
}
function getObjectLiteralElementVisitor(parent: ObjectLiteralExpression): (node: Node) => VisitResult<Node> {
return node => saveStateAndInvoke(node, n => objectLiteralElementVisitorWorker(n, parent));
}
function objectLiteralElementVisitorWorker(node: Node, parent: ObjectLiteralExpression): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.PropertyAssignment:
case SyntaxKind.ShorthandPropertyAssignment:
case SyntaxKind.SpreadAssignment:
return visitor(node);
case SyntaxKind.GetAccessor:
// Get Accessors can have TypeScript modifiers, decorators, and type annotations.
return visitGetAccessor(node as GetAccessorDeclaration, parent);
case SyntaxKind.SetAccessor:
// Set Accessors can have TypeScript modifiers and type annotations.
return visitSetAccessor(node as SetAccessorDeclaration, parent);
case SyntaxKind.MethodDeclaration:
// TypeScript method declarations may have decorators, modifiers
// or type annotations.
return visitMethodDeclaration(node as MethodDeclaration, parent);
default:
return Debug.failBadSyntaxKind(node);
}
}
function modifierVisitor(node: Node): VisitResult<Node> {
if (isDecorator(node)) return undefined;
if (modifierToFlag(node.kind) & ModifierFlags.TypeScriptModifier) {
return undefined;
}
else if (currentNamespace && node.kind === SyntaxKind.ExportKeyword) {
return undefined;
}
return node;
}
/**
* Branching visitor, visits a TypeScript syntax node.
*
* @param node The node to visit.
*/
function visitTypeScript(node: Node): VisitResult<Node> {
if (isStatement(node) && hasSyntacticModifier(node, ModifierFlags.Ambient)) {
// TypeScript ambient declarations are elided, but some comments may be preserved.
// See the implementation of `getLeadingComments` in comments.ts for more details.
return factory.createNotEmittedStatement(node);
}
switch (node.kind) {
case SyntaxKind.ExportKeyword:
case SyntaxKind.DefaultKeyword:
// ES6 export and default modifiers are elided when inside a namespace.
return currentNamespace ? undefined : node;
case SyntaxKind.PublicKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
case SyntaxKind.AbstractKeyword:
case SyntaxKind.OverrideKeyword:
case SyntaxKind.ConstKeyword:
case SyntaxKind.DeclareKeyword:
case SyntaxKind.ReadonlyKeyword:
case SyntaxKind.InKeyword:
case SyntaxKind.OutKeyword:
// TypeScript accessibility and readonly modifiers are elided
// falls through
case SyntaxKind.ArrayType:
case SyntaxKind.TupleType:
case SyntaxKind.OptionalType:
case SyntaxKind.RestType:
case SyntaxKind.TypeLiteral:
case SyntaxKind.TypePredicate:
case SyntaxKind.TypeParameter:
case SyntaxKind.AnyKeyword:
case SyntaxKind.UnknownKeyword:
case SyntaxKind.BooleanKeyword:
case SyntaxKind.StringKeyword:
case SyntaxKind.NumberKeyword:
case SyntaxKind.NeverKeyword:
case SyntaxKind.VoidKeyword:
case SyntaxKind.SymbolKeyword:
case SyntaxKind.ConstructorType:
case SyntaxKind.FunctionType:
case SyntaxKind.TypeQuery:
case SyntaxKind.TypeReference:
case SyntaxKind.UnionType:
case SyntaxKind.IntersectionType:
case SyntaxKind.ConditionalType:
case SyntaxKind.ParenthesizedType:
case SyntaxKind.ThisType:
case SyntaxKind.TypeOperator:
case SyntaxKind.IndexedAccessType:
case SyntaxKind.MappedType:
case SyntaxKind.LiteralType:
// TypeScript type nodes are elided.
// falls through
case SyntaxKind.IndexSignature:
// TypeScript index signatures are elided.
return undefined;
case SyntaxKind.TypeAliasDeclaration:
// TypeScript type-only declarations are elided.
return factory.createNotEmittedStatement(node);
case SyntaxKind.NamespaceExportDeclaration:
// TypeScript namespace export declarations are elided.
return undefined;
case SyntaxKind.InterfaceDeclaration:
// TypeScript interfaces are elided, but some comments may be preserved.
// See the implementation of `getLeadingComments` in comments.ts for more details.
return factory.createNotEmittedStatement(node);
case SyntaxKind.ClassDeclaration:
// This may be a class declaration with TypeScript syntax extensions.
//
// TypeScript class syntax extensions include:
// - decorators
// - optional `implements` heritage clause
// - parameter property assignments in the constructor
// - index signatures
// - method overload signatures
return visitClassDeclaration(node as ClassDeclaration);
case SyntaxKind.ClassExpression:
// This may be a class expression with TypeScript syntax extensions.
//
// TypeScript class syntax extensions include:
// - decorators
// - optional `implements` heritage clause
// - parameter property assignments in the constructor
// - index signatures
// - method overload signatures
return visitClassExpression(node as ClassExpression);
case SyntaxKind.HeritageClause:
// This may be a heritage clause with TypeScript syntax extensions.
//
// TypeScript heritage clause extensions include:
// - `implements` clause
return visitHeritageClause(node as HeritageClause);
case SyntaxKind.ExpressionWithTypeArguments:
// TypeScript supports type arguments on an expression in an `extends` heritage clause.
return visitExpressionWithTypeArguments(node as ExpressionWithTypeArguments);
case SyntaxKind.ObjectLiteralExpression:
return visitObjectLiteralExpression(node as ObjectLiteralExpression);
case SyntaxKind.Constructor:
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.ClassStaticBlockDeclaration:
return Debug.fail("Class and object literal elements must be visited with their respective visitors");
case SyntaxKind.FunctionDeclaration:
// Typescript function declarations can have modifiers, decorators, and type annotations.
return visitFunctionDeclaration(node as FunctionDeclaration);
case SyntaxKind.FunctionExpression:
// TypeScript function expressions can have modifiers and type annotations.
return visitFunctionExpression(node as FunctionExpression);
case SyntaxKind.ArrowFunction:
// TypeScript arrow functions can have modifiers and type annotations.
return visitArrowFunction(node as ArrowFunction);
case SyntaxKind.Parameter:
// This may be a parameter declaration with TypeScript syntax extensions.
//
// TypeScript parameter declaration syntax extensions include:
// - decorators
// - accessibility modifiers
// - the question mark (?) token for optional parameters
// - type annotations
// - this parameters
return visitParameter(node as ParameterDeclaration);
case SyntaxKind.ParenthesizedExpression:
// ParenthesizedExpressions are TypeScript if their expression is a
// TypeAssertion or AsExpression
return visitParenthesizedExpression(node as ParenthesizedExpression);
case SyntaxKind.TypeAssertionExpression:
case SyntaxKind.AsExpression:
// TypeScript type assertions are removed, but their subtrees are preserved.
return visitAssertionExpression(node as AssertionExpression);
case SyntaxKind.SatisfiesExpression:
return visitSatisfiesExpression(node as SatisfiesExpression);
case SyntaxKind.CallExpression:
return visitCallExpression(node as CallExpression);
case SyntaxKind.NewExpression:
return visitNewExpression(node as NewExpression);
case SyntaxKind.TaggedTemplateExpression:
return visitTaggedTemplateExpression(node as TaggedTemplateExpression);
case SyntaxKind.NonNullExpression:
// TypeScript non-null expressions are removed, but their subtrees are preserved.
return visitNonNullExpression(node as NonNullExpression);
case SyntaxKind.EnumDeclaration:
// TypeScript enum declarations do not exist in ES6 and must be rewritten.
return visitEnumDeclaration(node as EnumDeclaration);
case SyntaxKind.VariableStatement:
// TypeScript namespace exports for variable statements must be transformed.
return visitVariableStatement(node as VariableStatement);
case SyntaxKind.VariableDeclaration:
return visitVariableDeclaration(node as VariableDeclaration);
case SyntaxKind.ModuleDeclaration:
// TypeScript namespace declarations must be transformed.
return visitModuleDeclaration(node as ModuleDeclaration);
case SyntaxKind.ImportEqualsDeclaration:
// TypeScript namespace or external module import.
return visitImportEqualsDeclaration(node as ImportEqualsDeclaration);
case SyntaxKind.JsxSelfClosingElement:
return visitJsxSelfClosingElement(node as JsxSelfClosingElement);
case SyntaxKind.JsxOpeningElement:
return visitJsxJsxOpeningElement(node as JsxOpeningElement);
default:
// node contains some other TypeScript syntax
return visitEachChild(node, visitor, context);
}
}
function visitSourceFile(node: SourceFile) {
const alwaysStrict = getStrictOptionValue(compilerOptions, "alwaysStrict") &&
!(isExternalModule(node) && moduleKind >= ModuleKind.ES2015) &&
!isJsonSourceFile(node);
return factory.updateSourceFile(
node,
visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict));
}
function visitObjectLiteralExpression(node: ObjectLiteralExpression) {
return factory.updateObjectLiteralExpression(
node,
visitNodes(node.properties, getObjectLiteralElementVisitor(node), isObjectLiteralElement)
);
}
function getClassFacts(node: ClassDeclaration, staticProperties: readonly PropertyDeclaration[]) {
let facts = ClassFacts.None;
if (some(staticProperties)) facts |= ClassFacts.HasStaticInitializedProperties;
const extendsClauseElement = getEffectiveBaseTypeNode(node);
if (extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== SyntaxKind.NullKeyword) facts |= ClassFacts.IsDerivedClass;
if (classOrConstructorParameterIsDecorated(node)) facts |= ClassFacts.HasConstructorDecorators;
if (childIsDecorated(node)) facts |= ClassFacts.HasMemberDecorators;
if (isExportOfNamespace(node)) facts |= ClassFacts.IsExportOfNamespace;
else if (isDefaultExternalModuleExport(node)) facts |= ClassFacts.IsDefaultExternalExport;
else if (isNamedExternalModuleExport(node)) facts |= ClassFacts.IsNamedExternalExport;
if (languageVersion <= ScriptTarget.ES5 && (facts & ClassFacts.MayNeedImmediatelyInvokedFunctionExpression)) facts |= ClassFacts.UseImmediatelyInvokedFunctionExpression;
return facts;
}
function hasTypeScriptClassSyntax(node: Node) {
return !!(node.transformFlags & TransformFlags.ContainsTypeScriptClassSyntax);
}
function isClassLikeDeclarationWithTypeScriptSyntax(node: ClassLikeDeclaration) {
return hasDecorators(node)
|| some(node.typeParameters)
|| some(node.heritageClauses, hasTypeScriptClassSyntax)
|| some(node.members, hasTypeScriptClassSyntax);
}
function visitClassDeclaration(node: ClassDeclaration): VisitResult<Statement> {
if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && hasSyntacticModifier(node, ModifierFlags.Export))) {
return factory.updateClassDeclaration(
node,
visitNodes(node.modifiers, modifierVisitor, isModifier),
node.name,
/*typeParameters*/ undefined,
visitNodes(node.heritageClauses, visitor, isHeritageClause),
visitNodes(node.members, getClassElementVisitor(node), isClassElement)
);
}
const staticProperties = getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
const facts = getClassFacts(node, staticProperties);
if (facts & ClassFacts.UseImmediatelyInvokedFunctionExpression) {
context.startLexicalEnvironment();
}
const name = node.name || (facts & ClassFacts.NeedsName ? factory.getGeneratedNameForNode(node) : undefined);
const allDecorators = getAllDecoratorsOfClass(node);
const decorators = transformAllDecoratorsOfDeclaration(node, node, allDecorators);
// we do not emit modifiers on the declaration if we are emitting an IIFE
const modifiers = !(facts & ClassFacts.UseImmediatelyInvokedFunctionExpression)
? visitNodes(node.modifiers, modifierVisitor, isModifier)
: elideNodes(factory, node.modifiers); // preserve positions, if available
// ${modifiers} class ${name} ${heritageClauses} {
// ${members}
// }
const classStatement = factory.updateClassDeclaration(
node,
concatenate<ModifierLike>(decorators, modifiers),
name,
/*typeParameters*/ undefined,
visitNodes(node.heritageClauses, visitor, isHeritageClause),
transformClassMembers(node)
);
// To better align with the old emitter, we should not emit a trailing source map
// entry if the class has static properties.
let emitFlags = getEmitFlags(node);
if (facts & ClassFacts.HasStaticInitializedProperties) {
emitFlags |= EmitFlags.NoTrailingSourceMap;
}
setEmitFlags(classStatement, emitFlags);
let statements: Statement[] = [classStatement];
if (facts & ClassFacts.UseImmediatelyInvokedFunctionExpression) {
// When we emit a TypeScript class down to ES5, we must wrap it in an IIFE so that the
// 'es2015' transformer can properly nest static initializers and decorators. The result
// looks something like:
//
// var C = function () {
// class C {
// }
// C.static_prop = 1;
// return C;
// }();
//
const closingBraceLocation = createTokenRange(skipTrivia(currentSourceFile.text, node.members.end), SyntaxKind.CloseBraceToken);
const localName = factory.getInternalName(node);
// The following partially-emitted expression exists purely to align our sourcemap
// emit with the original emitter.
const outer = factory.createPartiallyEmittedExpression(localName);
setTextRangeEnd(outer, closingBraceLocation.end);
setEmitFlags(outer, EmitFlags.NoComments);
const statement = factory.createReturnStatement(outer);
setTextRangePos(statement, closingBraceLocation.pos);
setEmitFlags(statement, EmitFlags.NoComments | EmitFlags.NoTokenSourceMaps);
statements.push(statement);
insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment());
const iife = factory.createImmediatelyInvokedArrowFunction(statements);
setEmitFlags(iife, EmitFlags.TypeScriptClassWrapper);
const varStatement = factory.createVariableStatement(
/*modifiers*/ undefined,
factory.createVariableDeclarationList([
factory.createVariableDeclaration(
factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false),
/*exclamationToken*/ undefined,
/*type*/ undefined,
iife
)
])
);
setOriginalNode(varStatement, node);
setCommentRange(varStatement, node);
setSourceMapRange(varStatement, moveRangePastDecorators(node));
startOnNewLine(varStatement);
statements = [varStatement];
}
// If the class is exported as part of a TypeScript namespace, emit the namespace export.
// Otherwise, if the class was exported at the top level and was decorated, emit an export
// declaration or export default for the class.
if (facts & ClassFacts.IsExportOfNamespace) {
addExportMemberAssignment(statements, node);
}
else if (facts & ClassFacts.UseImmediatelyInvokedFunctionExpression || facts & ClassFacts.HasConstructorDecorators) {
if (facts & ClassFacts.IsDefaultExternalExport) {
statements.push(factory.createExportDefault(factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)));
}
else if (facts & ClassFacts.IsNamedExternalExport) {
statements.push(factory.createExternalModuleExport(factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)));
}
}
if (statements.length > 1) {
// Add a DeclarationMarker as a marker for the end of the declaration
statements.push(factory.createEndOfDeclarationMarker(node));
setEmitFlags(classStatement, getEmitFlags(classStatement) | EmitFlags.HasEndOfDeclarationMarker);
}
return singleOrMany(statements);
}
function visitClassExpression(node: ClassExpression): Expression {
const allDecorators = getAllDecoratorsOfClass(node);
const decorators = transformAllDecoratorsOfDeclaration(node, node, allDecorators);
return factory.updateClassExpression(
node,
decorators,
node.name,
/*typeParameters*/ undefined,
visitNodes(node.heritageClauses, visitor, isHeritageClause),
isClassLikeDeclarationWithTypeScriptSyntax(node) ?
transformClassMembers(node) :
visitNodes(node.members, getClassElementVisitor(node), isClassElement)
);
}
/**
* Transforms the members of a class.
*
* @param node The current class.
*/
function transformClassMembers(node: ClassDeclaration | ClassExpression) {
const members: ClassElement[] = [];
const constructor = getFirstConstructorWithBody(node);
const parametersWithPropertyAssignments = constructor &&
filter(constructor.parameters, p => isParameterPropertyDeclaration(p, constructor));
if (parametersWithPropertyAssignments) {
for (const parameter of parametersWithPropertyAssignments) {
if (isIdentifier(parameter.name)) {
members.push(setOriginalNode(factory.createPropertyDeclaration(
/*modifiers*/ undefined,
parameter.name,
/*questionOrExclamationToken*/ undefined,
/*type*/ undefined,
/*initializer*/ undefined), parameter));
}
}
}
addRange(members, visitNodes(node.members, getClassElementVisitor(node), isClassElement));
return setTextRange(factory.createNodeArray(members), /*location*/ node.members);
}
/**
* Transforms all of the decorators for a declaration into an array of expressions.
*
* @param node The declaration node.
* @param allDecorators An object containing all of the decorators for the declaration.
*/
function transformAllDecoratorsOfDeclaration(node: Declaration, container: ClassLikeDeclaration, allDecorators: AllDecorators | undefined) {
if (!allDecorators) {
return undefined;
}
const decorators = visitArray(allDecorators.decorators, visitor, isDecorator);
const parameterDecorators = flatMap(allDecorators.parameters, transformDecoratorsOfParameter);
const metadataDecorators = some(decorators) || some(parameterDecorators) ? getTypeMetadata(node, container) : undefined;
const result = factory.createNodeArray(concatenate(concatenate(decorators, parameterDecorators), metadataDecorators));
const pos = firstOrUndefined(allDecorators.decorators)?.pos ?? -1;
const end = lastOrUndefined(allDecorators.decorators)?.end ?? -1;
setTextRangePosEnd(result, pos, end);
return result;
}
/**
* Transforms the decorators of a parameter into decorators of the class/method.
*
* @param parameterDecorators The decorators for the parameter at the provided offset.
* @param parameterOffset The offset of the parameter.
*/
function transformDecoratorsOfParameter(parameterDecorators: Decorator[], parameterOffset: number) {
if (parameterDecorators) {
const decorators: Decorator[] = [];
for (const parameterDecorator of parameterDecorators) {
const expression = visitNode(parameterDecorator.expression, visitor, isExpression);
const helper = emitHelpers().createParamHelper(expression, parameterOffset);
setTextRange(helper, parameterDecorator.expression);
setEmitFlags(helper, EmitFlags.NoComments);
const decorator = factory.createDecorator(helper);
setSourceMapRange(decorator, parameterDecorator.expression);
setCommentRange(decorator, parameterDecorator.expression);
setEmitFlags(decorator, EmitFlags.NoComments);
decorators.push(decorator);
}
return decorators;
}
}
/**
* Gets optional type metadata for a declaration.
*
* @param node The declaration node.
*/
function getTypeMetadata(node: Declaration, container: ClassLikeDeclaration) {
return USE_NEW_TYPE_METADATA_FORMAT ?
getNewTypeMetadata(node, container) :
getOldTypeMetadata(node, container);
}
function getOldTypeMetadata(node: Declaration, container: ClassLikeDeclaration) {
if (typeSerializer) {
let decorators: Decorator[] | undefined;
if (shouldAddTypeMetadata(node)) {
const typeMetadata = emitHelpers().createMetadataHelper("design:type", typeSerializer.serializeTypeOfNode({ currentLexicalScope, currentNameScope: container }, node));
decorators = append(decorators, factory.createDecorator(typeMetadata));
}
if (shouldAddParamTypesMetadata(node)) {
const paramTypesMetadata = emitHelpers().createMetadataHelper("design:paramtypes", typeSerializer.serializeParameterTypesOfNode({ currentLexicalScope, currentNameScope: container }, node, container));
decorators = append(decorators, factory.createDecorator(paramTypesMetadata));
}
if (shouldAddReturnTypeMetadata(node)) {
const returnTypeMetadata = emitHelpers().createMetadataHelper("design:returntype", typeSerializer.serializeReturnTypeOfNode({ currentLexicalScope, currentNameScope: container }, node));
decorators = append(decorators, factory.createDecorator(returnTypeMetadata));
}
return decorators;
}
}
function getNewTypeMetadata(node: Declaration, container: ClassLikeDeclaration) {
if (typeSerializer) {
let properties: ObjectLiteralElementLike[] | undefined;
if (shouldAddTypeMetadata(node)) {
const typeProperty = factory.createPropertyAssignment("type", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(SyntaxKind.EqualsGreaterThanToken), typeSerializer.serializeTypeOfNode({ currentLexicalScope, currentNameScope: container }, node)));
properties = append(properties, typeProperty);
}
if (shouldAddParamTypesMetadata(node)) {
const paramTypeProperty = factory.createPropertyAssignment("paramTypes", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(SyntaxKind.EqualsGreaterThanToken), typeSerializer.serializeParameterTypesOfNode({ currentLexicalScope, currentNameScope: container }, node, container)));
properties = append(properties, paramTypeProperty);
}
if (shouldAddReturnTypeMetadata(node)) {
const returnTypeProperty = factory.createPropertyAssignment("returnType", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(SyntaxKind.EqualsGreaterThanToken), typeSerializer.serializeReturnTypeOfNode({ currentLexicalScope, currentNameScope: container }, node)));
properties = append(properties, returnTypeProperty);
}
if (properties) {
const typeInfoMetadata = emitHelpers().createMetadataHelper("design:typeinfo", factory.createObjectLiteralExpression(properties, /*multiLine*/ true));
return [factory.createDecorator(typeInfoMetadata)];
}
}
}
/**
* Determines whether to emit the "design:type" metadata based on the node's kind.
* The caller should have already tested whether the node has decorators and whether the
* emitDecoratorMetadata compiler option is set.
*
* @param node The node to test.
*/
function shouldAddTypeMetadata(node: Declaration): node is MethodDeclaration | AccessorDeclaration | PropertyDeclaration {
const kind = node.kind;
return kind === SyntaxKind.MethodDeclaration
|| kind === SyntaxKind.GetAccessor
|| kind === SyntaxKind.SetAccessor
|| kind === SyntaxKind.PropertyDeclaration;
}
/**
* Determines whether to emit the "design:returntype" metadata based on the node's kind.
* The caller should have already tested whether the node has decorators and whether the
* emitDecoratorMetadata compiler option is set.
*
* @param node The node to test.
*/
function shouldAddReturnTypeMetadata(node: Declaration): node is MethodDeclaration {
return node.kind === SyntaxKind.MethodDeclaration;
}
/**
* Determines whether to emit the "design:paramtypes" metadata based on the node's kind.
* The caller should have already tested whether the node has decorators and whether the
* emitDecoratorMetadata compiler option is set.
*
* @param node The node to test.
*/
function shouldAddParamTypesMetadata(node: Declaration): node is ClassLikeDeclaration & { _hasConstructorBrand: never } | MethodDeclaration | AccessorDeclaration {
switch (node.kind) {
case SyntaxKind.ClassDeclaration:
case SyntaxKind.ClassExpression:
return getFirstConstructorWithBody(node as ClassLikeDeclaration) !== undefined;
case SyntaxKind.MethodDeclaration:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
return true;
}
return false;
}
/**
* Gets an expression that represents a property name (for decorated properties or enums).
* For a computed property, a name is generated for the node.
*
* @param member The member whose name should be converted into an expression.
*/
function getExpressionForPropertyName(member: ClassElement | EnumMember, generateNameForComputedPropertyName: boolean): Expression {
const name = member.name!;
if (isPrivateIdentifier(name)) {
return factory.createIdentifier("");
}
else if (isComputedPropertyName(name)) {
return generateNameForComputedPropertyName && !isSimpleInlineableExpression(name.expression)
? factory.getGeneratedNameForNode(name)
: name.expression;
}
else if (isIdentifier(name)) {
return factory.createStringLiteral(idText(name));
}
else {
return factory.cloneNode(name);
}
}
/**
* Visits the property name of a class element, for use when emitting property
* initializers. For a computed property on a node with decorators, a temporary
* value is stored for later use.
*
* @param member The member whose name should be visited.
*/
function visitPropertyNameOfClassElement(member: ClassElement): PropertyName {
const name = member.name!;
// Computed property names need to be transformed into a hoisted variable when they are used more than once.
// The names are used more than once when:
// - the property is non-static and its initializer is moved to the constructor (when there are parameter property assignments).
// - the property has a decorator.
if (isComputedPropertyName(name) && ((!hasStaticModifier(member) && currentClassHasParameterProperties) || hasDecorators(member))) {
const expression = visitNode(name.expression, visitor, isExpression);
const innerExpression = skipPartiallyEmittedExpressions(expression);
if (!isSimpleInlineableExpression(innerExpression)) {
const generatedName = factory.getGeneratedNameForNode(name);
hoistVariableDeclaration(generatedName);
return factory.updateComputedPropertyName(name, factory.createAssignment(generatedName, expression));
}
}
return visitNode(name, visitor, isPropertyName);
}
/**
* Transforms a HeritageClause with TypeScript syntax.
*
* This function will only be called when one of the following conditions are met:
* - The node is a non-`extends` heritage clause that should be elided.
* - The node is an `extends` heritage clause that should be visited, but only allow a single type.
*
* @param node The HeritageClause to transform.
*/
function visitHeritageClause(node: HeritageClause): HeritageClause | undefined {
if (node.token === SyntaxKind.ImplementsKeyword) {
// implements clauses are elided
return undefined;
}
return visitEachChild(node, visitor, context);
}
/**
* Transforms an ExpressionWithTypeArguments with TypeScript syntax.