-
Notifications
You must be signed in to change notification settings - Fork 12.6k
/
Copy pathemitter.ts
3067 lines (2670 loc) · 125 KB
/
emitter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/// <reference path="checker.ts" />
/// <reference path="transformer.ts" />
/// <reference path="declarationEmitter.ts" />
/// <reference path="sourcemap.ts" />
/// <reference path="comments.ts" />
namespace ts {
const delimiters = createDelimiterMap();
const brackets = createBracketsMap();
/*@internal*/
// targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
export function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFile: SourceFile, emitOnlyDtsFiles?: boolean, transformers?: TransformerFactory<SourceFile>[]): EmitResult {
const compilerOptions = host.getCompilerOptions();
const moduleKind = getEmitModuleKind(compilerOptions);
const sourceMapDataList: SourceMapData[] = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined;
const emittedFilesList: string[] = compilerOptions.listEmittedFiles ? [] : undefined;
const emitterDiagnostics = createDiagnosticCollection();
const newLine = host.getNewLine();
const writer = createTextWriter(newLine);
const sourceMap = createSourceMapWriter(host, writer);
let currentSourceFile: SourceFile;
let bundledHelpers: Map<boolean>;
let isOwnFileEmit: boolean;
let emitSkipped = false;
const sourceFiles = getSourceFilesToEmit(host, targetSourceFile);
// Transform the source files
const transform = transformNodes(resolver, host, compilerOptions, sourceFiles, transformers, /*allowDtsFiles*/ false);
// Create a printer to print the nodes
const printer = createPrinter(compilerOptions, {
// resolver hooks
hasGlobalName: resolver.hasGlobalName,
// transform hooks
onEmitNode: transform.emitNodeWithNotification,
substituteNode: transform.substituteNode,
// sourcemap hooks
onEmitSourceMapOfNode: sourceMap.emitNodeWithSourceMap,
onEmitSourceMapOfToken: sourceMap.emitTokenWithSourceMap,
onEmitSourceMapOfPosition: sourceMap.emitPos,
// emitter hooks
onEmitHelpers: emitHelpers,
onSetSourceFile: setSourceFile,
});
// Emit each output file
performance.mark("beforePrint");
forEachEmittedFile(host, emitSourceFileOrBundle, transform.transformed, emitOnlyDtsFiles);
performance.measure("printTime", "beforePrint");
// Clean up emit nodes on parse tree
transform.dispose();
return {
emitSkipped,
diagnostics: emitterDiagnostics.getDiagnostics(),
emittedFiles: emittedFilesList,
sourceMaps: sourceMapDataList
};
function emitSourceFileOrBundle({ jsFilePath, sourceMapFilePath, declarationFilePath }: EmitFileNames, sourceFileOrBundle: SourceFile | Bundle) {
// Make sure not to write js file and source map file if any of them cannot be written
if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) {
if (!emitOnlyDtsFiles) {
printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle);
}
}
else {
emitSkipped = true;
}
if (declarationFilePath) {
emitSkipped = writeDeclarationFile(declarationFilePath, getOriginalSourceFileOrBundle(sourceFileOrBundle), host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped;
}
if (!emitSkipped && emittedFilesList) {
if (!emitOnlyDtsFiles) {
emittedFilesList.push(jsFilePath);
}
if (sourceMapFilePath) {
emittedFilesList.push(sourceMapFilePath);
}
if (declarationFilePath) {
emittedFilesList.push(declarationFilePath);
}
}
}
function printSourceFileOrBundle(jsFilePath: string, sourceMapFilePath: string, sourceFileOrBundle: SourceFile | Bundle) {
const bundle = sourceFileOrBundle.kind === SyntaxKind.Bundle ? sourceFileOrBundle : undefined;
const sourceFile = sourceFileOrBundle.kind === SyntaxKind.SourceFile ? sourceFileOrBundle : undefined;
const sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFileOrBundle);
if (bundle) {
bundledHelpers = createMap<boolean>();
isOwnFileEmit = false;
printer.writeBundle(bundle, writer);
}
else {
isOwnFileEmit = true;
printer.writeFile(sourceFile, writer);
}
writer.writeLine();
const sourceMappingURL = sourceMap.getSourceMappingURL();
if (sourceMappingURL) {
writer.write(`//# ${"sourceMappingURL"}=${sourceMappingURL}`); // Sometimes tools can sometimes see this line as a source mapping url comment
}
// Write the source map
if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) {
writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), /*writeByteOrderMark*/ false, sourceFiles);
}
// Record source map data for the test harness.
if (sourceMapDataList) {
sourceMapDataList.push(sourceMap.getSourceMapData());
}
// Write the output file
writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles);
// Reset state
sourceMap.reset();
writer.reset();
currentSourceFile = undefined;
bundledHelpers = undefined;
isOwnFileEmit = false;
}
function setSourceFile(node: SourceFile) {
currentSourceFile = node;
sourceMap.setSourceFile(node);
}
function emitHelpers(node: Node, writeLines: (text: string) => void) {
let helpersEmitted = false;
const bundle = node.kind === SyntaxKind.Bundle ? <Bundle>node : undefined;
if (bundle && moduleKind === ModuleKind.None) {
return;
}
const numNodes = bundle ? bundle.sourceFiles.length : 1;
for (let i = 0; i < numNodes; i++) {
const currentNode = bundle ? bundle.sourceFiles[i] : node;
const sourceFile = isSourceFile(currentNode) ? currentNode : currentSourceFile;
const shouldSkip = compilerOptions.noEmitHelpers || getExternalHelpersModuleName(sourceFile) !== undefined;
const shouldBundle = isSourceFile(currentNode) && !isOwnFileEmit;
const helpers = getEmitHelpers(currentNode);
if (helpers) {
for (const helper of stableSort(helpers, compareEmitHelpers)) {
if (!helper.scoped) {
// Skip the helper if it can be skipped and the noEmitHelpers compiler
// option is set, or if it can be imported and the importHelpers compiler
// option is set.
if (shouldSkip) continue;
// Skip the helper if it can be bundled but hasn't already been emitted and we
// are emitting a bundled module.
if (shouldBundle) {
if (bundledHelpers.get(helper.name)) {
continue;
}
bundledHelpers.set(helper.name, true);
}
}
else if (bundle) {
// Skip the helper if it is scoped and we are emitting bundled helpers
continue;
}
writeLines(helper.text);
helpersEmitted = true;
}
}
}
return helpersEmitted;
}
}
export function createPrinter(printerOptions: PrinterOptions = {}, handlers: PrintHandlers = {}): Printer {
const {
hasGlobalName,
onEmitSourceMapOfNode,
onEmitSourceMapOfToken,
onEmitSourceMapOfPosition,
onEmitNode,
onEmitHelpers,
onSetSourceFile,
substituteNode,
onBeforeEmitNodeArray,
onAfterEmitNodeArray,
onBeforeEmitToken,
onAfterEmitToken
} = handlers;
const newLine = getNewLineCharacter(printerOptions);
const comments = createCommentWriter(printerOptions, onEmitSourceMapOfPosition);
const {
emitNodeWithComments,
emitBodyWithDetachedComments,
emitTrailingCommentsOfPosition,
emitLeadingCommentsOfPosition,
} = comments;
let currentSourceFile: SourceFile | undefined;
let nodeIdToGeneratedName: string[]; // Map of generated names for specific nodes.
let autoGeneratedIdToGeneratedName: string[]; // Map of generated names for temp and loop variables.
let generatedNames: Map<string>; // Set of names generated by the NameGenerator.
let tempFlagsStack: TempFlags[]; // Stack of enclosing name generation scopes.
let tempFlags: TempFlags; // TempFlags for the current name generation scope.
let writer: EmitTextWriter;
let ownWriter: EmitTextWriter;
reset();
return {
// public API
printNode,
printFile,
printBundle,
// internal API
writeNode,
writeFile,
writeBundle
};
function printNode(hint: EmitHint, node: Node, sourceFile: SourceFile): string {
switch (hint) {
case EmitHint.SourceFile:
Debug.assert(isSourceFile(node), "Expected a SourceFile node.");
break;
case EmitHint.IdentifierName:
Debug.assert(isIdentifier(node), "Expected an Identifier node.");
break;
case EmitHint.Expression:
Debug.assert(isExpression(node), "Expected an Expression node.");
break;
}
switch (node.kind) {
case SyntaxKind.SourceFile: return printFile(<SourceFile>node);
case SyntaxKind.Bundle: return printBundle(<Bundle>node);
}
writeNode(hint, node, sourceFile, beginPrint());
return endPrint();
}
function printBundle(bundle: Bundle): string {
writeBundle(bundle, beginPrint());
return endPrint();
}
function printFile(sourceFile: SourceFile): string {
writeFile(sourceFile, beginPrint());
return endPrint();
}
/**
* If `sourceFile` is `undefined`, `node` must be a synthesized `TypeNode`.
*/
function writeNode(hint: EmitHint, node: TypeNode, sourceFile: undefined, output: EmitTextWriter): void;
function writeNode(hint: EmitHint, node: Node, sourceFile: SourceFile, output: EmitTextWriter): void;
function writeNode(hint: EmitHint, node: Node, sourceFile: SourceFile | undefined, output: EmitTextWriter) {
const previousWriter = writer;
setWriter(output);
print(hint, node, sourceFile);
reset();
writer = previousWriter;
}
function writeBundle(bundle: Bundle, output: EmitTextWriter) {
const previousWriter = writer;
setWriter(output);
emitShebangIfNeeded(bundle);
emitPrologueDirectivesIfNeeded(bundle);
emitHelpersIndirect(bundle);
for (const sourceFile of bundle.sourceFiles) {
print(EmitHint.SourceFile, sourceFile, sourceFile);
}
reset();
writer = previousWriter;
}
function writeFile(sourceFile: SourceFile, output: EmitTextWriter) {
const previousWriter = writer;
setWriter(output);
emitShebangIfNeeded(sourceFile);
emitPrologueDirectivesIfNeeded(sourceFile);
print(EmitHint.SourceFile, sourceFile, sourceFile);
reset();
writer = previousWriter;
}
function beginPrint() {
return ownWriter || (ownWriter = createTextWriter(newLine));
}
function endPrint() {
const text = ownWriter.getText();
ownWriter.reset();
return text;
}
function print(hint: EmitHint, node: Node, sourceFile: SourceFile | undefined) {
if (sourceFile) {
setSourceFile(sourceFile);
}
pipelineEmitWithNotification(hint, node);
}
function setSourceFile(sourceFile: SourceFile) {
currentSourceFile = sourceFile;
comments.setSourceFile(sourceFile);
if (onSetSourceFile) {
onSetSourceFile(sourceFile);
}
}
function setWriter(output: EmitTextWriter | undefined) {
writer = output;
comments.setWriter(output);
}
function reset() {
nodeIdToGeneratedName = [];
autoGeneratedIdToGeneratedName = [];
generatedNames = createMap<string>();
tempFlagsStack = [];
tempFlags = TempFlags.Auto;
comments.reset();
setWriter(/*output*/ undefined);
}
function emit(node: Node) {
pipelineEmitWithNotification(EmitHint.Unspecified, node);
}
function emitIdentifierName(node: Identifier) {
pipelineEmitWithNotification(EmitHint.IdentifierName, node);
}
function emitExpression(node: Expression) {
pipelineEmitWithNotification(EmitHint.Expression, node);
}
function pipelineEmitWithNotification(hint: EmitHint, node: Node) {
if (onEmitNode) {
onEmitNode(hint, node, pipelineEmitWithComments);
}
else {
pipelineEmitWithComments(hint, node);
}
}
function pipelineEmitWithComments(hint: EmitHint, node: Node) {
node = trySubstituteNode(hint, node);
if (emitNodeWithComments && hint !== EmitHint.SourceFile) {
emitNodeWithComments(hint, node, pipelineEmitWithSourceMap);
}
else {
pipelineEmitWithSourceMap(hint, node);
}
}
function pipelineEmitWithSourceMap(hint: EmitHint, node: Node) {
if (onEmitSourceMapOfNode && hint !== EmitHint.SourceFile && hint !== EmitHint.IdentifierName) {
onEmitSourceMapOfNode(hint, node, pipelineEmitWithHint);
}
else {
pipelineEmitWithHint(hint, node);
}
}
function pipelineEmitWithHint(hint: EmitHint, node: Node): void {
switch (hint) {
case EmitHint.SourceFile: return pipelineEmitSourceFile(node);
case EmitHint.IdentifierName: return pipelineEmitIdentifierName(node);
case EmitHint.Expression: return pipelineEmitExpression(node);
case EmitHint.Unspecified: return pipelineEmitUnspecified(node);
}
}
function pipelineEmitSourceFile(node: Node): void {
Debug.assertNode(node, isSourceFile);
emitSourceFile(<SourceFile>node);
}
function pipelineEmitIdentifierName(node: Node): void {
Debug.assertNode(node, isIdentifier);
emitIdentifier(<Identifier>node);
}
function pipelineEmitUnspecified(node: Node): void {
const kind = node.kind;
// Reserved words
// Strict mode reserved words
// Contextual keywords
if (isKeyword(kind)) {
writeTokenNode(node);
return;
}
switch (kind) {
// Pseudo-literals
case SyntaxKind.TemplateHead:
case SyntaxKind.TemplateMiddle:
case SyntaxKind.TemplateTail:
return emitLiteral(<LiteralExpression>node);
// Identifiers
case SyntaxKind.Identifier:
return emitIdentifier(<Identifier>node);
// Parse tree nodes
// Names
case SyntaxKind.QualifiedName:
return emitQualifiedName(<QualifiedName>node);
case SyntaxKind.ComputedPropertyName:
return emitComputedPropertyName(<ComputedPropertyName>node);
// Signature elements
case SyntaxKind.TypeParameter:
return emitTypeParameter(<TypeParameterDeclaration>node);
case SyntaxKind.Parameter:
return emitParameter(<ParameterDeclaration>node);
case SyntaxKind.Decorator:
return emitDecorator(<Decorator>node);
// Type members
case SyntaxKind.PropertySignature:
return emitPropertySignature(<PropertySignature>node);
case SyntaxKind.PropertyDeclaration:
return emitPropertyDeclaration(<PropertyDeclaration>node);
case SyntaxKind.MethodSignature:
return emitMethodSignature(<MethodSignature>node);
case SyntaxKind.MethodDeclaration:
return emitMethodDeclaration(<MethodDeclaration>node);
case SyntaxKind.Constructor:
return emitConstructor(<ConstructorDeclaration>node);
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
return emitAccessorDeclaration(<AccessorDeclaration>node);
case SyntaxKind.CallSignature:
return emitCallSignature(<CallSignatureDeclaration>node);
case SyntaxKind.ConstructSignature:
return emitConstructSignature(<ConstructSignatureDeclaration>node);
case SyntaxKind.IndexSignature:
return emitIndexSignature(<IndexSignatureDeclaration>node);
// Types
case SyntaxKind.TypePredicate:
return emitTypePredicate(<TypePredicateNode>node);
case SyntaxKind.TypeReference:
return emitTypeReference(<TypeReferenceNode>node);
case SyntaxKind.FunctionType:
return emitFunctionType(<FunctionTypeNode>node);
case SyntaxKind.ConstructorType:
return emitConstructorType(<ConstructorTypeNode>node);
case SyntaxKind.TypeQuery:
return emitTypeQuery(<TypeQueryNode>node);
case SyntaxKind.TypeLiteral:
return emitTypeLiteral(<TypeLiteralNode>node);
case SyntaxKind.ArrayType:
return emitArrayType(<ArrayTypeNode>node);
case SyntaxKind.TupleType:
return emitTupleType(<TupleTypeNode>node);
case SyntaxKind.UnionType:
return emitUnionType(<UnionTypeNode>node);
case SyntaxKind.IntersectionType:
return emitIntersectionType(<IntersectionTypeNode>node);
case SyntaxKind.ParenthesizedType:
return emitParenthesizedType(<ParenthesizedTypeNode>node);
case SyntaxKind.ExpressionWithTypeArguments:
return emitExpressionWithTypeArguments(<ExpressionWithTypeArguments>node);
case SyntaxKind.ThisType:
return emitThisType();
case SyntaxKind.TypeOperator:
return emitTypeOperator(<TypeOperatorNode>node);
case SyntaxKind.IndexedAccessType:
return emitIndexedAccessType(<IndexedAccessTypeNode>node);
case SyntaxKind.MappedType:
return emitMappedType(<MappedTypeNode>node);
case SyntaxKind.LiteralType:
return emitLiteralType(<LiteralTypeNode>node);
// Binding patterns
case SyntaxKind.ObjectBindingPattern:
return emitObjectBindingPattern(<ObjectBindingPattern>node);
case SyntaxKind.ArrayBindingPattern:
return emitArrayBindingPattern(<ArrayBindingPattern>node);
case SyntaxKind.BindingElement:
return emitBindingElement(<BindingElement>node);
// Misc
case SyntaxKind.TemplateSpan:
return emitTemplateSpan(<TemplateSpan>node);
case SyntaxKind.SemicolonClassElement:
return emitSemicolonClassElement();
// Statements
case SyntaxKind.Block:
return emitBlock(<Block>node);
case SyntaxKind.VariableStatement:
return emitVariableStatement(<VariableStatement>node);
case SyntaxKind.EmptyStatement:
return emitEmptyStatement();
case SyntaxKind.ExpressionStatement:
return emitExpressionStatement(<ExpressionStatement>node);
case SyntaxKind.IfStatement:
return emitIfStatement(<IfStatement>node);
case SyntaxKind.DoStatement:
return emitDoStatement(<DoStatement>node);
case SyntaxKind.WhileStatement:
return emitWhileStatement(<WhileStatement>node);
case SyntaxKind.ForStatement:
return emitForStatement(<ForStatement>node);
case SyntaxKind.ForInStatement:
return emitForInStatement(<ForInStatement>node);
case SyntaxKind.ForOfStatement:
return emitForOfStatement(<ForOfStatement>node);
case SyntaxKind.ContinueStatement:
return emitContinueStatement(<ContinueStatement>node);
case SyntaxKind.BreakStatement:
return emitBreakStatement(<BreakStatement>node);
case SyntaxKind.ReturnStatement:
return emitReturnStatement(<ReturnStatement>node);
case SyntaxKind.WithStatement:
return emitWithStatement(<WithStatement>node);
case SyntaxKind.SwitchStatement:
return emitSwitchStatement(<SwitchStatement>node);
case SyntaxKind.LabeledStatement:
return emitLabeledStatement(<LabeledStatement>node);
case SyntaxKind.ThrowStatement:
return emitThrowStatement(<ThrowStatement>node);
case SyntaxKind.TryStatement:
return emitTryStatement(<TryStatement>node);
case SyntaxKind.DebuggerStatement:
return emitDebuggerStatement(<DebuggerStatement>node);
// Declarations
case SyntaxKind.VariableDeclaration:
return emitVariableDeclaration(<VariableDeclaration>node);
case SyntaxKind.VariableDeclarationList:
return emitVariableDeclarationList(<VariableDeclarationList>node);
case SyntaxKind.FunctionDeclaration:
return emitFunctionDeclaration(<FunctionDeclaration>node);
case SyntaxKind.ClassDeclaration:
return emitClassDeclaration(<ClassDeclaration>node);
case SyntaxKind.InterfaceDeclaration:
return emitInterfaceDeclaration(<InterfaceDeclaration>node);
case SyntaxKind.TypeAliasDeclaration:
return emitTypeAliasDeclaration(<TypeAliasDeclaration>node);
case SyntaxKind.EnumDeclaration:
return emitEnumDeclaration(<EnumDeclaration>node);
case SyntaxKind.ModuleDeclaration:
return emitModuleDeclaration(<ModuleDeclaration>node);
case SyntaxKind.ModuleBlock:
return emitModuleBlock(<ModuleBlock>node);
case SyntaxKind.CaseBlock:
return emitCaseBlock(<CaseBlock>node);
case SyntaxKind.NamespaceExportDeclaration:
return emitNamespaceExportDeclaration(<NamespaceExportDeclaration>node);
case SyntaxKind.ImportEqualsDeclaration:
return emitImportEqualsDeclaration(<ImportEqualsDeclaration>node);
case SyntaxKind.ImportDeclaration:
return emitImportDeclaration(<ImportDeclaration>node);
case SyntaxKind.ImportClause:
return emitImportClause(<ImportClause>node);
case SyntaxKind.NamespaceImport:
return emitNamespaceImport(<NamespaceImport>node);
case SyntaxKind.NamedImports:
return emitNamedImports(<NamedImports>node);
case SyntaxKind.ImportSpecifier:
return emitImportSpecifier(<ImportSpecifier>node);
case SyntaxKind.ExportAssignment:
return emitExportAssignment(<ExportAssignment>node);
case SyntaxKind.ExportDeclaration:
return emitExportDeclaration(<ExportDeclaration>node);
case SyntaxKind.NamedExports:
return emitNamedExports(<NamedExports>node);
case SyntaxKind.ExportSpecifier:
return emitExportSpecifier(<ExportSpecifier>node);
case SyntaxKind.MissingDeclaration:
return;
// Module references
case SyntaxKind.ExternalModuleReference:
return emitExternalModuleReference(<ExternalModuleReference>node);
// JSX (non-expression)
case SyntaxKind.JsxText:
return emitJsxText(<JsxText>node);
case SyntaxKind.JsxOpeningElement:
return emitJsxOpeningElement(<JsxOpeningElement>node);
case SyntaxKind.JsxClosingElement:
return emitJsxClosingElement(<JsxClosingElement>node);
case SyntaxKind.JsxAttribute:
return emitJsxAttribute(<JsxAttribute>node);
case SyntaxKind.JsxAttributes:
return emitJsxAttributes(<JsxAttributes>node);
case SyntaxKind.JsxSpreadAttribute:
return emitJsxSpreadAttribute(<JsxSpreadAttribute>node);
case SyntaxKind.JsxExpression:
return emitJsxExpression(<JsxExpression>node);
// Clauses
case SyntaxKind.CaseClause:
return emitCaseClause(<CaseClause>node);
case SyntaxKind.DefaultClause:
return emitDefaultClause(<DefaultClause>node);
case SyntaxKind.HeritageClause:
return emitHeritageClause(<HeritageClause>node);
case SyntaxKind.CatchClause:
return emitCatchClause(<CatchClause>node);
// Property assignments
case SyntaxKind.PropertyAssignment:
return emitPropertyAssignment(<PropertyAssignment>node);
case SyntaxKind.ShorthandPropertyAssignment:
return emitShorthandPropertyAssignment(<ShorthandPropertyAssignment>node);
case SyntaxKind.SpreadAssignment:
return emitSpreadAssignment(node as SpreadAssignment);
// Enum
case SyntaxKind.EnumMember:
return emitEnumMember(<EnumMember>node);
// JSDoc nodes (ignored)
// Transformation nodes (ignored)
}
// If the node is an expression, try to emit it as an expression with
// substitution.
if (isExpression(node)) {
return pipelineEmitExpression(trySubstituteNode(EmitHint.Expression, node));
}
if (isToken(node)) {
writeTokenNode(node);
return;
}
}
function pipelineEmitExpression(node: Node): void {
const kind = node.kind;
switch (kind) {
// Literals
case SyntaxKind.NumericLiteral:
return emitNumericLiteral(<NumericLiteral>node);
case SyntaxKind.StringLiteral:
case SyntaxKind.RegularExpressionLiteral:
case SyntaxKind.NoSubstitutionTemplateLiteral:
return emitLiteral(<LiteralExpression>node);
// Identifiers
case SyntaxKind.Identifier:
return emitIdentifier(<Identifier>node);
// Reserved words
case SyntaxKind.FalseKeyword:
case SyntaxKind.NullKeyword:
case SyntaxKind.SuperKeyword:
case SyntaxKind.TrueKeyword:
case SyntaxKind.ThisKeyword:
case SyntaxKind.ImportKeyword:
writeTokenNode(node);
return;
// Expressions
case SyntaxKind.ArrayLiteralExpression:
return emitArrayLiteralExpression(<ArrayLiteralExpression>node);
case SyntaxKind.ObjectLiteralExpression:
return emitObjectLiteralExpression(<ObjectLiteralExpression>node);
case SyntaxKind.PropertyAccessExpression:
return emitPropertyAccessExpression(<PropertyAccessExpression>node);
case SyntaxKind.ElementAccessExpression:
return emitElementAccessExpression(<ElementAccessExpression>node);
case SyntaxKind.CallExpression:
return emitCallExpression(<CallExpression>node);
case SyntaxKind.NewExpression:
return emitNewExpression(<NewExpression>node);
case SyntaxKind.TaggedTemplateExpression:
return emitTaggedTemplateExpression(<TaggedTemplateExpression>node);
case SyntaxKind.TypeAssertionExpression:
return emitTypeAssertionExpression(<TypeAssertion>node);
case SyntaxKind.ParenthesizedExpression:
return emitParenthesizedExpression(<ParenthesizedExpression>node);
case SyntaxKind.FunctionExpression:
return emitFunctionExpression(<FunctionExpression>node);
case SyntaxKind.ArrowFunction:
return emitArrowFunction(<ArrowFunction>node);
case SyntaxKind.DeleteExpression:
return emitDeleteExpression(<DeleteExpression>node);
case SyntaxKind.TypeOfExpression:
return emitTypeOfExpression(<TypeOfExpression>node);
case SyntaxKind.VoidExpression:
return emitVoidExpression(<VoidExpression>node);
case SyntaxKind.AwaitExpression:
return emitAwaitExpression(<AwaitExpression>node);
case SyntaxKind.PrefixUnaryExpression:
return emitPrefixUnaryExpression(<PrefixUnaryExpression>node);
case SyntaxKind.PostfixUnaryExpression:
return emitPostfixUnaryExpression(<PostfixUnaryExpression>node);
case SyntaxKind.BinaryExpression:
return emitBinaryExpression(<BinaryExpression>node);
case SyntaxKind.ConditionalExpression:
return emitConditionalExpression(<ConditionalExpression>node);
case SyntaxKind.TemplateExpression:
return emitTemplateExpression(<TemplateExpression>node);
case SyntaxKind.YieldExpression:
return emitYieldExpression(<YieldExpression>node);
case SyntaxKind.SpreadElement:
return emitSpreadExpression(<SpreadElement>node);
case SyntaxKind.ClassExpression:
return emitClassExpression(<ClassExpression>node);
case SyntaxKind.OmittedExpression:
return;
case SyntaxKind.AsExpression:
return emitAsExpression(<AsExpression>node);
case SyntaxKind.NonNullExpression:
return emitNonNullExpression(<NonNullExpression>node);
case SyntaxKind.MetaProperty:
return emitMetaProperty(<MetaProperty>node);
// JSX
case SyntaxKind.JsxElement:
return emitJsxElement(<JsxElement>node);
case SyntaxKind.JsxSelfClosingElement:
return emitJsxSelfClosingElement(<JsxSelfClosingElement>node);
// Transformation nodes
case SyntaxKind.PartiallyEmittedExpression:
return emitPartiallyEmittedExpression(<PartiallyEmittedExpression>node);
case SyntaxKind.CommaListExpression:
return emitCommaList(<CommaListExpression>node);
}
}
function trySubstituteNode(hint: EmitHint, node: Node) {
return node && substituteNode && substituteNode(hint, node) || node;
}
function emitHelpersIndirect(node: Node) {
if (onEmitHelpers) {
onEmitHelpers(node, writeLines);
}
}
//
// Literals/Pseudo-literals
//
// SyntaxKind.NumericLiteral
function emitNumericLiteral(node: NumericLiteral) {
emitLiteral(node);
}
// SyntaxKind.StringLiteral
// SyntaxKind.RegularExpressionLiteral
// SyntaxKind.NoSubstitutionTemplateLiteral
// SyntaxKind.TemplateHead
// SyntaxKind.TemplateMiddle
// SyntaxKind.TemplateTail
function emitLiteral(node: LiteralLikeNode) {
const text = getLiteralTextOfNode(node);
if ((printerOptions.sourceMap || printerOptions.inlineSourceMap)
&& (node.kind === SyntaxKind.StringLiteral || isTemplateLiteralKind(node.kind))) {
writer.writeLiteral(text);
}
else {
write(text);
}
}
//
// Identifiers
//
function emitIdentifier(node: Identifier) {
write(getTextOfNode(node, /*includeTrivia*/ false));
emitTypeArguments(node, node.typeArguments);
}
//
// Names
//
function emitQualifiedName(node: QualifiedName) {
emitEntityName(node.left);
write(".");
emit(node.right);
}
function emitEntityName(node: EntityName) {
if (node.kind === SyntaxKind.Identifier) {
emitExpression(<Identifier>node);
}
else {
emit(node);
}
}
function emitComputedPropertyName(node: ComputedPropertyName) {
write("[");
emitExpression(node.expression);
write("]");
}
//
// Signature elements
//
function emitTypeParameter(node: TypeParameterDeclaration) {
emit(node.name);
emitWithPrefix(" extends ", node.constraint);
emitWithPrefix(" = ", node.default);
}
function emitParameter(node: ParameterDeclaration) {
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
writeIfPresent(node.dotDotDotToken, "...");
emit(node.name);
writeIfPresent(node.questionToken, "?");
emitWithPrefix(": ", node.type);
emitExpressionWithPrefix(" = ", node.initializer);
}
function emitDecorator(decorator: Decorator) {
write("@");
emitExpression(decorator.expression);
}
//
// Type members
//
function emitPropertySignature(node: PropertySignature) {
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
emit(node.name);
writeIfPresent(node.questionToken, "?");
emitWithPrefix(": ", node.type);
write(";");
}
function emitPropertyDeclaration(node: PropertyDeclaration) {
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
emit(node.name);
writeIfPresent(node.questionToken, "?");
emitWithPrefix(": ", node.type);
emitExpressionWithPrefix(" = ", node.initializer);
write(";");
}
function emitMethodSignature(node: MethodSignature) {
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
emit(node.name);
writeIfPresent(node.questionToken, "?");
emitTypeParameters(node, node.typeParameters);
emitParameters(node, node.parameters);
emitWithPrefix(": ", node.type);
write(";");
}
function emitMethodDeclaration(node: MethodDeclaration) {
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
writeIfPresent(node.asteriskToken, "*");
emit(node.name);
writeIfPresent(node.questionToken, "?");
emitSignatureAndBody(node, emitSignatureHead);
}
function emitConstructor(node: ConstructorDeclaration) {
emitModifiers(node, node.modifiers);
write("constructor");
emitSignatureAndBody(node, emitSignatureHead);
}
function emitAccessorDeclaration(node: AccessorDeclaration) {
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
write(node.kind === SyntaxKind.GetAccessor ? "get " : "set ");
emit(node.name);
emitSignatureAndBody(node, emitSignatureHead);
}
function emitCallSignature(node: CallSignatureDeclaration) {
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
emitTypeParameters(node, node.typeParameters);
emitParameters(node, node.parameters);
emitWithPrefix(": ", node.type);
write(";");
}
function emitConstructSignature(node: ConstructSignatureDeclaration) {
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
write("new ");
emitTypeParameters(node, node.typeParameters);
emitParameters(node, node.parameters);
emitWithPrefix(": ", node.type);
write(";");
}
function emitIndexSignature(node: IndexSignatureDeclaration) {
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
emitParametersForIndexSignature(node, node.parameters);
emitWithPrefix(": ", node.type);
write(";");
}
function emitSemicolonClassElement() {
write(";");
}
//
// Types
//
function emitTypePredicate(node: TypePredicateNode) {
emit(node.parameterName);
write(" is ");
emit(node.type);
}
function emitTypeReference(node: TypeReferenceNode) {
emit(node.typeName);
emitTypeArguments(node, node.typeArguments);
}
function emitFunctionType(node: FunctionTypeNode) {
emitTypeParameters(node, node.typeParameters);
emitParametersForArrow(node, node.parameters);
write(" => ");
emit(node.type);
}
function emitConstructorType(node: ConstructorTypeNode) {
write("new ");
emitTypeParameters(node, node.typeParameters);
emitParameters(node, node.parameters);
write(" => ");
emit(node.type);
}
function emitTypeQuery(node: TypeQueryNode) {
write("typeof ");
emit(node.exprName);
}
function emitTypeLiteral(node: TypeLiteralNode) {
write("{");
// If the literal is empty, do not add spaces between braces.
if (node.members.length > 0) {
emitList(node, node.members, getEmitFlags(node) & EmitFlags.SingleLine ? ListFormat.SingleLineTypeLiteralMembers : ListFormat.MultiLineTypeLiteralMembers);
}
write("}");
}
function emitArrayType(node: ArrayTypeNode) {
emit(node.elementType);
write("[]");
}
function emitTupleType(node: TupleTypeNode) {
write("[");
emitList(node, node.elementTypes, ListFormat.TupleTypeElements);
write("]");
}
function emitUnionType(node: UnionTypeNode) {
emitList(node, node.types, ListFormat.UnionTypeConstituents);
}
function emitIntersectionType(node: IntersectionTypeNode) {
emitList(node, node.types, ListFormat.IntersectionTypeConstituents);
}
function emitParenthesizedType(node: ParenthesizedTypeNode) {