-
Notifications
You must be signed in to change notification settings - Fork 12.7k
/
Copy pathts.ts
3359 lines (2974 loc) · 152 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 decorated classes. */
ClassAliases = 1 << 0,
/** 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 {
startLexicalEnvironment,
resumeLexicalEnvironment,
endLexicalEnvironment,
hoistVariableDeclaration,
} = context;
const resolver = context.getEmitResolver();
const compilerOptions = context.getCompilerOptions();
const strictNullChecks = getStrictOptionValue(compilerOptions, "strictNullChecks");
const languageVersion = getEmitScriptTarget(compilerOptions);
const moduleKind = getEmitModuleKind(compilerOptions);
// 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 currentNameScope: ClassDeclaration | undefined;
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;
/**
* A map that keeps track of aliases created for classes with decorators to avoid issues
* with the double-binding behavior of classes.
*/
let classAliases: Identifier[];
/**
* 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 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 savedCurrentNameScope = currentNameScope;
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;
currentNameScope = savedCurrentNameScope;
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 = <SourceFile | CaseBlock | ModuleBlock | Block>node;
currentNameScope = undefined;
currentScopeFirstDeclarationsOfName = undefined;
break;
case SyntaxKind.ClassDeclaration:
case SyntaxKind.FunctionDeclaration:
if (hasModifier(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 || hasModifier(node, ModifierFlags.Default));
}
if (isClassDeclaration(node)) {
// XXX: should probably also cover interfaces and type aliases that can have type variables?
currentNameScope = node;
}
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 visitEllidableStatement(<ImportDeclaration | ImportEqualsDeclaration | ExportAssignment | ExportDeclaration>node);
default:
return visitorWorker(node);
}
}
function visitEllidableStatement(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 &&
(<ImportEqualsDeclaration>node).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 || hasModifier(node, ModifierFlags.Export)) {
return visitTypeScript(node);
}
return node;
}
/**
* Specialized visitor that visits the immediate children of a class with TypeScript syntax.
*
* @param node The node to visit.
*/
function classElementVisitor(node: Node): VisitResult<Node> {
return saveStateAndInvoke(node, classElementVisitorWorker);
}
/**
* Specialized visitor that visits the immediate children of a class with TypeScript syntax.
*
* @param node The node to visit.
*/
function classElementVisitorWorker(node: Node): 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);
case SyntaxKind.IndexSignature:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.MethodDeclaration:
// Fallback to the default visit behavior.
return visitorWorker(node);
case SyntaxKind.SemicolonClassElement:
return node;
default:
return Debug.failBadSyntaxKind(node);
}
}
function modifierVisitor(node: Node): VisitResult<Node> {
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) && hasModifier(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 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.ConstKeyword:
case SyntaxKind.DeclareKeyword:
case SyntaxKind.ReadonlyKeyword:
// 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.
// falls through
case SyntaxKind.Decorator:
// TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration.
// falls through
case SyntaxKind.TypeAliasDeclaration:
// TypeScript type-only declarations are elided.
return undefined;
case SyntaxKind.PropertyDeclaration:
// TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects
return visitPropertyDeclaration(node as PropertyDeclaration);
case SyntaxKind.NamespaceExportDeclaration:
// TypeScript namespace export declarations are elided.
return undefined;
case SyntaxKind.Constructor:
return visitConstructor(<ConstructorDeclaration>node);
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 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(<ClassDeclaration>node);
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(<ClassExpression>node);
case SyntaxKind.HeritageClause:
// This may be a heritage clause with TypeScript syntax extensions.
//
// TypeScript heritage clause extensions include:
// - `implements` clause
return visitHeritageClause(<HeritageClause>node);
case SyntaxKind.ExpressionWithTypeArguments:
// TypeScript supports type arguments on an expression in an `extends` heritage clause.
return visitExpressionWithTypeArguments(<ExpressionWithTypeArguments>node);
case SyntaxKind.MethodDeclaration:
// TypeScript method declarations may have decorators, modifiers
// or type annotations.
return visitMethodDeclaration(<MethodDeclaration>node);
case SyntaxKind.GetAccessor:
// Get Accessors can have TypeScript modifiers, decorators, and type annotations.
return visitGetAccessor(<GetAccessorDeclaration>node);
case SyntaxKind.SetAccessor:
// Set Accessors can have TypeScript modifiers and type annotations.
return visitSetAccessor(<SetAccessorDeclaration>node);
case SyntaxKind.FunctionDeclaration:
// Typescript function declarations can have modifiers, decorators, and type annotations.
return visitFunctionDeclaration(<FunctionDeclaration>node);
case SyntaxKind.FunctionExpression:
// TypeScript function expressions can have modifiers and type annotations.
return visitFunctionExpression(<FunctionExpression>node);
case SyntaxKind.ArrowFunction:
// TypeScript arrow functions can have modifiers and type annotations.
return visitArrowFunction(<ArrowFunction>node);
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(<ParameterDeclaration>node);
case SyntaxKind.ParenthesizedExpression:
// ParenthesizedExpressions are TypeScript if their expression is a
// TypeAssertion or AsExpression
return visitParenthesizedExpression(<ParenthesizedExpression>node);
case SyntaxKind.TypeAssertionExpression:
case SyntaxKind.AsExpression:
// TypeScript type assertions are removed, but their subtrees are preserved.
return visitAssertionExpression(<AssertionExpression>node);
case SyntaxKind.CallExpression:
return visitCallExpression(<CallExpression>node);
case SyntaxKind.NewExpression:
return visitNewExpression(<NewExpression>node);
case SyntaxKind.TaggedTemplateExpression:
return visitTaggedTemplateExpression(<TaggedTemplateExpression>node);
case SyntaxKind.NonNullExpression:
// TypeScript non-null expressions are removed, but their subtrees are preserved.
return visitNonNullExpression(<NonNullExpression>node);
case SyntaxKind.EnumDeclaration:
// TypeScript enum declarations do not exist in ES6 and must be rewritten.
return visitEnumDeclaration(<EnumDeclaration>node);
case SyntaxKind.VariableStatement:
// TypeScript namespace exports for variable statements must be transformed.
return visitVariableStatement(<VariableStatement>node);
case SyntaxKind.VariableDeclaration:
return visitVariableDeclaration(<VariableDeclaration>node);
case SyntaxKind.ModuleDeclaration:
// TypeScript namespace declarations must be transformed.
return visitModuleDeclaration(<ModuleDeclaration>node);
case SyntaxKind.ImportEqualsDeclaration:
// TypeScript namespace or external module import.
return visitImportEqualsDeclaration(<ImportEqualsDeclaration>node);
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 updateSourceFileNode(
node,
visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict));
}
/**
* Tests whether we should emit a __decorate call for a class declaration.
*/
function shouldEmitDecorateCallForClass(node: ClassDeclaration) {
if (node.decorators && node.decorators.length > 0) {
return true;
}
const constructor = getFirstConstructorWithBody(node);
if (constructor) {
return forEach(constructor.parameters, shouldEmitDecorateCallForParameter);
}
return false;
}
/**
* Tests whether we should emit a __decorate call for a parameter declaration.
*/
function shouldEmitDecorateCallForParameter(parameter: ParameterDeclaration) {
return parameter.decorators !== undefined && parameter.decorators.length > 0;
}
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 (shouldEmitDecorateCallForClass(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 some(node.decorators)
|| some(node.typeParameters)
|| some(node.heritageClauses, hasTypeScriptClassSyntax)
|| some(node.members, hasTypeScriptClassSyntax);
}
function visitClassDeclaration(node: ClassDeclaration): VisitResult<Statement> {
if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && hasModifier(node, ModifierFlags.Export))) {
return visitEachChild(node, visitor, context);
}
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 ? getGeneratedNameForNode(node) : undefined);
const classStatement = facts & ClassFacts.HasConstructorDecorators
? createClassDeclarationHeadWithDecorators(node, name)
: createClassDeclarationHeadWithoutDecorators(node, name, facts);
let statements: Statement[] = [classStatement];
// Write any decorators of the node.
addClassElementDecorationStatements(statements, node, /*isStatic*/ false);
addClassElementDecorationStatements(statements, node, /*isStatic*/ true);
addConstructorDecorationStatement(statements, node);
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 = getInternalName(node);
// The following partially-emitted expression exists purely to align our sourcemap
// emit with the original emitter.
const outer = createPartiallyEmittedExpression(localName);
outer.end = closingBraceLocation.end;
setEmitFlags(outer, EmitFlags.NoComments);
const statement = createReturn(outer);
statement.pos = closingBraceLocation.pos;
setEmitFlags(statement, EmitFlags.NoComments | EmitFlags.NoTokenSourceMaps);
statements.push(statement);
insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment());
const iife = createImmediatelyInvokedArrowFunction(statements);
setEmitFlags(iife, EmitFlags.TypeScriptClassWrapper);
const varStatement = createVariableStatement(
/*modifiers*/ undefined,
createVariableDeclarationList([
createVariableDeclaration(
getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false),
/*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(createExportDefault(getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)));
}
else if (facts & ClassFacts.IsNamedExternalExport) {
statements.push(createExternalModuleExport(getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)));
}
}
if (statements.length > 1) {
// Add a DeclarationMarker as a marker for the end of the declaration
statements.push(createEndOfDeclarationMarker(node));
setEmitFlags(classStatement, getEmitFlags(classStatement) | EmitFlags.HasEndOfDeclarationMarker);
}
return singleOrMany(statements);
}
/**
* Transforms a non-decorated class declaration and appends the resulting statements.
*
* @param node A ClassDeclaration node.
* @param name The name of the class.
* @param facts Precomputed facts about the class.
*/
function createClassDeclarationHeadWithoutDecorators(node: ClassDeclaration, name: Identifier | undefined, facts: ClassFacts) {
// ${modifiers} class ${name} ${heritageClauses} {
// ${members}
// }
// we do not emit modifiers on the declaration if we are emitting an IIFE
const modifiers = !(facts & ClassFacts.UseImmediatelyInvokedFunctionExpression)
? visitNodes(node.modifiers, modifierVisitor, isModifier)
: undefined;
const classDeclaration = createClassDeclaration(
/*decorators*/ undefined,
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;
}
aggregateTransformFlags(classDeclaration);
setTextRange(classDeclaration, node);
setOriginalNode(classDeclaration, node);
setEmitFlags(classDeclaration, emitFlags);
return classDeclaration;
}
/**
* Transforms a decorated class declaration and appends the resulting statements. If
* the class requires an alias to avoid issues with double-binding, the alias is returned.
*/
function createClassDeclarationHeadWithDecorators(node: ClassDeclaration, name: Identifier | undefined) {
// When we emit an ES6 class that has a class decorator, we must tailor the
// emit to certain specific cases.
//
// In the simplest case, we emit the class declaration as a let declaration, and
// evaluate decorators after the close of the class body:
//
// [Example 1]
// ---------------------------------------------------------------------
// TypeScript | Javascript
// ---------------------------------------------------------------------
// @dec | let C = class C {
// class C { | }
// } | C = __decorate([dec], C);
// ---------------------------------------------------------------------
// @dec | let C = class C {
// export class C { | }
// } | C = __decorate([dec], C);
// | export { C };
// ---------------------------------------------------------------------
//
// If a class declaration contains a reference to itself *inside* of the class body,
// this introduces two bindings to the class: One outside of the class body, and one
// inside of the class body. If we apply decorators as in [Example 1] above, there
// is the possibility that the decorator `dec` will return a new value for the
// constructor, which would result in the binding inside of the class no longer
// pointing to the same reference as the binding outside of the class.
//
// As a result, we must instead rewrite all references to the class *inside* of the
// class body to instead point to a local temporary alias for the class:
//
// [Example 2]
// ---------------------------------------------------------------------
// TypeScript | Javascript
// ---------------------------------------------------------------------
// @dec | let C = C_1 = class C {
// class C { | static x() { return C_1.y; }
// static x() { return C.y; } | }
// static y = 1; | C.y = 1;
// } | C = C_1 = __decorate([dec], C);
// | var C_1;
// ---------------------------------------------------------------------
// @dec | let C = class C {
// export class C { | static x() { return C_1.y; }
// static x() { return C.y; } | }
// static y = 1; | C.y = 1;
// } | C = C_1 = __decorate([dec], C);
// | export { C };
// | var C_1;
// ---------------------------------------------------------------------
//
// If a class declaration is the default export of a module, we instead emit
// the export after the decorated declaration:
//
// [Example 3]
// ---------------------------------------------------------------------
// TypeScript | Javascript
// ---------------------------------------------------------------------
// @dec | let default_1 = class {
// export default class { | }
// } | default_1 = __decorate([dec], default_1);
// | export default default_1;
// ---------------------------------------------------------------------
// @dec | let C = class C {
// export default class C { | }
// } | C = __decorate([dec], C);
// | export default C;
// ---------------------------------------------------------------------
//
// If the class declaration is the default export and a reference to itself
// inside of the class body, we must emit both an alias for the class *and*
// move the export after the declaration:
//
// [Example 4]
// ---------------------------------------------------------------------
// TypeScript | Javascript
// ---------------------------------------------------------------------
// @dec | let C = class C {
// export default class C { | static x() { return C_1.y; }
// static x() { return C.y; } | }
// static y = 1; | C.y = 1;
// } | C = C_1 = __decorate([dec], C);
// | export default C;
// | var C_1;
// ---------------------------------------------------------------------
//
const location = moveRangePastDecorators(node);
const classAlias = getClassAliasIfNeeded(node);
const declName = getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
// ... = class ${name} ${heritageClauses} {
// ${members}
// }
const heritageClauses = visitNodes(node.heritageClauses, visitor, isHeritageClause);
const members = transformClassMembers(node);
const classExpression = createClassExpression(/*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members);
aggregateTransformFlags(classExpression);
setOriginalNode(classExpression, node);
setTextRange(classExpression, location);
// let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference
// or decoratedClassAlias if the class contain self-reference.
const statement = createVariableStatement(
/*modifiers*/ undefined,
createVariableDeclarationList([
createVariableDeclaration(
declName,
/*type*/ undefined,
classAlias ? createAssignment(classAlias, classExpression) : classExpression
)
], NodeFlags.Let)
);
setOriginalNode(statement, node);
setTextRange(statement, location);
setCommentRange(statement, node);
return statement;
}
function visitClassExpression(node: ClassExpression): Expression {
if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) {
return visitEachChild(node, visitor, context);
}
const classExpression = createClassExpression(
/*modifiers*/ undefined,
node.name,
/*typeParameters*/ undefined,
visitNodes(node.heritageClauses, visitor, isHeritageClause),
transformClassMembers(node)
);
aggregateTransformFlags(classExpression);
setOriginalNode(classExpression, node);
setTextRange(classExpression, node);
return classExpression;
}
/**
* 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(aggregateTransformFlags(createProperty(
/*decorators*/ undefined,
/*modifiers*/ undefined,
parameter.name,
/*questionOrExclamationToken*/ undefined,
/*type*/ undefined,
/*initializer*/ undefined)));
}
}
}
addRange(members, visitNodes(node.members, classElementVisitor, isClassElement));
return setTextRange(createNodeArray(members), /*location*/ node.members);
}
/**
* Gets either the static or instance members of a class that are decorated, or have
* parameters that are decorated.
*
* @param node The class containing the member.
* @param isStatic A value indicating whether to retrieve static or instance members of
* the class.
*/
function getDecoratedClassElements(node: ClassExpression | ClassDeclaration, isStatic: boolean): readonly ClassElement[] {
return filter(node.members, isStatic ? m => isStaticDecoratedClassElement(m, node) : m => isInstanceDecoratedClassElement(m, node));
}
/**
* Determines whether a class member is a static member of a class that is decorated, or
* has parameters that are decorated.
*
* @param member The class member.
*/
function isStaticDecoratedClassElement(member: ClassElement, parent: ClassLikeDeclaration) {
return isDecoratedClassElement(member, /*isStatic*/ true, parent);
}
/**
* Determines whether a class member is an instance member of a class that is decorated,
* or has parameters that are decorated.
*
* @param member The class member.
*/
function isInstanceDecoratedClassElement(member: ClassElement, parent: ClassLikeDeclaration) {
return isDecoratedClassElement(member, /*isStatic*/ false, parent);
}
/**
* Determines whether a class member is either a static or an instance member of a class
* that is decorated, or has parameters that are decorated.
*
* @param member The class member.
*/
function isDecoratedClassElement(member: ClassElement, isStatic: boolean, parent: ClassLikeDeclaration) {
return nodeOrChildIsDecorated(member, parent)
&& isStatic === hasModifier(member, ModifierFlags.Static);
}
/**
* A structure describing the decorators for a class element.
*/
interface AllDecorators {
decorators: readonly Decorator[] | undefined;
parameters?: readonly (readonly Decorator[] | undefined)[];
}
/**
* Gets an array of arrays of decorators for the parameters of a function-like node.
* The offset into the result array should correspond to the offset of the parameter.
*
* @param node The function-like node.
*/
function getDecoratorsOfParameters(node: FunctionLikeDeclaration | undefined) {
let decorators: (readonly Decorator[] | undefined)[] | undefined;
if (node) {
const parameters = node.parameters;
const firstParameterIsThis = parameters.length > 0 && parameterIsThisKeyword(parameters[0]);
const firstParameterOffset = firstParameterIsThis ? 1 : 0;
const numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length;
for (let i = 0; i < numParameters; i++) {
const parameter = parameters[i + firstParameterOffset];
if (decorators || parameter.decorators) {
if (!decorators) {
decorators = new Array(numParameters);
}
decorators[i] = parameter.decorators;
}
}
}
return decorators;
}
/**
* Gets an AllDecorators object containing the decorators for the class and the decorators for the
* parameters of the constructor of the class.