-
Notifications
You must be signed in to change notification settings - Fork 12.8k
/
Copy pathprinter.ts
2421 lines (2091 loc) · 102 KB
/
printer.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" />
/* @internal */
namespace ts {
const delimiters = createDelimiterMap();
const brackets = createBracketsMap();
// Flags enum to track count of temp variables and a few dedicated names
const enum TempFlags {
Auto = 0x00000000, // No preferred name
CountMask = 0x0FFFFFFF, // Temp variable counter
_i = 0x10000000, // Use/preference flag for '_i'
}
// targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
export function printFiles(resolver: EmitResolver, host: EmitHost, targetSourceFile: SourceFile): EmitResult {
// emit output for the __extends helper function
const extendsHelper = `
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};`;
// emit output for the __decorate helper function
const decorateHelper = `
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};`;
// emit output for the __metadata helper function
const metadataHelper = `
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};`;
// emit output for the __param helper function
const paramHelper = `
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};`;
// emit output for the __awaiter helper function
const awaiterHelper = `
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments)).next());
});
};`;
// emit output for the __export helper function
const exportStarHelper = `
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}`;
// emit output for the UMD helper function.
const umdHelper = `
(function (dependencies, factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
var v = factory(require, exports); if (v !== undefined) module.exports = v;
}
else if (typeof define === 'function' && define.amd) {
define(dependencies, factory);
}
})`;
const compilerOptions = host.getCompilerOptions();
const languageVersion = getLanguageVersion(compilerOptions);
const moduleKind = getModuleKind(compilerOptions);
const sourceMapDataList: SourceMapData[] = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined;
const emitterDiagnostics = createDiagnosticCollection();
let emitSkipped = false;
const newLine = host.getNewLine();
const printFile = createFilePrinter();
forEachExpectedEmitFile(host, emitFile, targetSourceFile);
return {
emitSkipped,
diagnostics: emitterDiagnostics.getDiagnostics(),
sourceMaps: sourceMapDataList
};
function emitFile({ jsFilePath, sourceMapFilePath, declarationFilePath}: EmitFileNames, sourceFiles: SourceFile[], isBundledEmit: boolean) {
// Make sure not to write js file and source map file if any of them cannot be written
if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) {
printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit);
}
else {
emitSkipped = true;
}
if (declarationFilePath) {
emitSkipped = writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped;
}
}
function createFilePrinter() {
const transformers = getTransformers(compilerOptions).concat(initializePrinter);
const writer = createTextWriter(newLine);
const { write, writeTextOfNode, writeLine, increaseIndent, decreaseIndent } = writer;
const sourceMap = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? createSourceMapWriter(host, writer) : getNullSourceMapWriter();
const { emitStart, emitEnd, emitPos } = sourceMap;
const comments = createCommentWriter(host, writer, sourceMap);
const { emitDetachedComments, emitLeadingComments, emitTrailingComments, getLeadingCommentsToEmit, getTrailingCommentsToEmit } = comments;
let context: TransformationContext;
let startLexicalEnvironment: () => void;
let endLexicalEnvironment: () => Statement[];
let getNodeEmitFlags: (node: Node) => NodeEmitFlags;
let expressionSubstitution: (node: Expression) => Expression;
let identifierSubstitution: (node: Identifier) => Identifier;
let isUniqueName: (name: string) => boolean;
let temporaryVariables: string[] = [];
let tempFlags: TempFlags;
let currentSourceFile: SourceFile;
let currentText: string;
let extendsEmitted: boolean;
let decorateEmitted: boolean;
let paramEmitted: boolean;
let awaiterEmitted: boolean;
let isOwnFileEmit: boolean;
return doPrint;
function doPrint(jsFilePath: string, sourceMapFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean) {
sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit);
isOwnFileEmit = !isBundledEmit;
// Emit helpers from all the files
if (isBundledEmit && moduleKind) {
forEach(sourceFiles, emitEmitHelpers);
}
// Transform and print the source files
transformFiles(resolver, host, sourceFiles, transformers);
writeLine();
const sourceMappingURL = sourceMap.getSourceMappingURL();
if (sourceMappingURL) {
write(`//# sourceMappingURL=${sourceMappingURL}`);
}
// Write the source map
if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) {
writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), compilerOptions.emitBOM);
}
// 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);
// Reset state
sourceMap.reset();
comments.reset();
writer.reset();
startLexicalEnvironment = undefined;
endLexicalEnvironment = undefined;
getNodeEmitFlags = undefined;
expressionSubstitution = undefined;
identifierSubstitution = undefined;
isUniqueName = undefined;
temporaryVariables = undefined;
tempFlags = 0;
currentSourceFile = undefined;
currentText = undefined;
extendsEmitted = false;
decorateEmitted = false;
paramEmitted = false;
awaiterEmitted = false;
isOwnFileEmit = false;
}
function initializePrinter(_context: TransformationContext) {
context = _context;
startLexicalEnvironment = context.startLexicalEnvironment;
endLexicalEnvironment = context.endLexicalEnvironment;
getNodeEmitFlags = context.getNodeEmitFlags;
expressionSubstitution = context.expressionSubstitution;
identifierSubstitution = context.identifierSubstitution;
isUniqueName = context.isUniqueName;
return printSourceFile;
}
function printSourceFile(node: SourceFile) {
currentSourceFile = node;
currentText = node.text;
sourceMap.setSourceFile(node);
comments.setSourceFile(node);
emitWorker(node);
return node;
}
function emit(node: Node) {
if (node) {
const leadingComments = getLeadingCommentsToEmit(node);
const trailingComments = getTrailingCommentsToEmit(node);
emitLeadingComments(node, leadingComments);
emitStart(node);
emitWorker(node);
emitEnd(node);
emitTrailingComments(node, trailingComments);
}
}
function emitWorker(node: Node) {
const kind = node.kind;
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, identifierSubstitution);
// Reserved words
case SyntaxKind.ConstKeyword:
case SyntaxKind.DefaultKeyword:
case SyntaxKind.ExportKeyword:
case SyntaxKind.VoidKeyword:
// Strict mode reserved words
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
case SyntaxKind.PublicKeyword:
case SyntaxKind.StaticKeyword:
// Contextual keywords
case SyntaxKind.AbstractKeyword:
case SyntaxKind.AnyKeyword:
case SyntaxKind.AsyncKeyword:
case SyntaxKind.BooleanKeyword:
case SyntaxKind.DeclareKeyword:
case SyntaxKind.NumberKeyword:
case SyntaxKind.ReadonlyKeyword:
case SyntaxKind.StringKeyword:
case SyntaxKind.SymbolKeyword:
case SyntaxKind.GlobalKeyword:
return writeTokenNode(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 write("this");
case SyntaxKind.StringLiteralType:
return emitLiteral(<StringLiteralTypeNode>node);
// Binding patterns
case SyntaxKind.ObjectBindingPattern:
return emitObjectBindingPattern(<BindingPattern>node);
case SyntaxKind.ArrayBindingPattern:
return emitArrayBindingPattern(<BindingPattern>node);
case SyntaxKind.BindingElement:
return emitBindingElement(<BindingElement>node);
// Misc
case SyntaxKind.TemplateSpan:
return emitTemplateSpan(<TemplateSpan>node);
case SyntaxKind.SemicolonClassElement:
return write(";");
// Statements
case SyntaxKind.Block:
return emitBlock(<Block>node);
case SyntaxKind.VariableStatement:
return emitVariableStatement(<VariableStatement>node);
case SyntaxKind.EmptyStatement:
return write(";");
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(<Block>node);
case SyntaxKind.CaseBlock:
return emitCaseBlock(<CaseBlock>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.JsxClosingElement:
return emitJsxClosingElement(<JsxClosingElement>node);
case SyntaxKind.JsxAttribute:
return emitJsxAttribute(<JsxAttribute>node);
case SyntaxKind.JsxSpreadAttribute:
return emitJsxSpreadAttribute(<JsxSpreadAttribute>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);
// Enum
case SyntaxKind.EnumMember:
return emitEnumMember(<EnumMember>node);
// Top-level nodes
case SyntaxKind.SourceFile:
return emitSourceFile(<SourceFile>node);
// JSDoc nodes (ignored)
}
if (isExpressionKind(kind)) {
return emitExpressionWorker(node);
}
}
function emitExpression(node: Expression) {
if (node) {
const leadingComments = getLeadingCommentsToEmit(node);
const trailingComments = getTrailingCommentsToEmit(node);
emitLeadingComments(node, leadingComments);
emitStart(node);
emitExpressionWorker(node);
emitEnd(node);
emitTrailingComments(node, trailingComments);
}
}
function emitExpressionWorker(node: Node) {
const kind = node.kind;
switch (kind) {
// Literals
case SyntaxKind.NumericLiteral:
case SyntaxKind.StringLiteral:
case SyntaxKind.RegularExpressionLiteral:
case SyntaxKind.NoSubstitutionTemplateLiteral:
return emitLiteral(<LiteralExpression>node);
// Identifiers
case SyntaxKind.Identifier:
return emitIdentifier(<Identifier>node, expressionSubstitution);
// Reserved words
case SyntaxKind.FalseKeyword:
case SyntaxKind.NullKeyword:
case SyntaxKind.SuperKeyword:
case SyntaxKind.TrueKeyword:
return writeTokenNode(node);
case SyntaxKind.ThisKeyword:
return emitThisKeyword(<PrimaryExpression>node);
// 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.SpreadElementExpression:
return emitSpreadElementExpression(<SpreadElementExpression>node);
case SyntaxKind.ClassExpression:
return emitClassExpression(<ClassExpression>node);
case SyntaxKind.OmittedExpression:
return;
case SyntaxKind.AsExpression:
return emitAsExpression(<AsExpression>node);
// JSX
case SyntaxKind.JsxElement:
return emitJsxElement(<JsxElement>node);
case SyntaxKind.JsxSelfClosingElement:
return emitJsxSelfClosingElement(<JsxSelfClosingElement>node);
case SyntaxKind.JsxOpeningElement:
return emitJsxOpeningElement(<JsxOpeningElement>node);
case SyntaxKind.JsxExpression:
return emitJsxExpression(<JsxExpression>node);
}
}
//
// Literals/Pseudo-literals
//
// SyntaxKind.NumericLiteral
// SyntaxKind.StringLiteral
// SyntaxKind.RegularExpressionLiteral
// SyntaxKind.NoSubstitutionTemplateLiteral
// SyntaxKind.TemplateHead
// SyntaxKind.TemplateMiddle
// SyntaxKind.TemplateTail
function emitLiteral(node: LiteralLikeNode) {
const text = getLiteralText(node, currentSourceFile, languageVersion);
if ((compilerOptions.sourceMap || compilerOptions.inlineSourceMap)
&& (node.kind === SyntaxKind.StringLiteral || isTemplateLiteralKind(node.kind))) {
writer.writeLiteral(text);
}
else {
write(text);
}
}
//
// Identifiers
//
function emitIdentifier(node: Identifier, substitution: (node: Node) => Node) {
if (tryEmitSubstitute(node, substitution)) {
return;
}
else if (node.text === undefined) {
// Emit a temporary variable name for this node.
const nodeId = getOriginalNodeId(node);
const text = temporaryVariables[nodeId] || (temporaryVariables[nodeId] = makeTempVariableName(tempKindToFlags(node.tempKind)));
write(text);
}
else if (nodeIsSynthesized(node)) {
if (getNodeEmitFlags(node) & NodeEmitFlags.UMDDefine) {
writeLines(umdHelper);
}
else {
write(node.text);
}
}
else {
writeTextOfNode(currentText, node);
}
}
function emitThisKeyword(node: PrimaryExpression) {
if (tryEmitSubstitute(node, expressionSubstitution)) {
return;
}
else {
writeTokenNode(node);
}
}
//
// 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);
}
function emitParameter(node: ParameterDeclaration) {
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
writeIfPresent(node.dotDotDotToken, "...");
emit(node.name);
writeIfPresent(node.questionToken, "?");
emitExpressionWithPrefix(" = ", node.initializer);
emitWithPrefix(": ", node.type);
}
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);
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);
emitSignatureAndBody(node);
}
function emitConstructor(node: ConstructorDeclaration) {
emitModifiers(node, node.modifiers);
write("constructor");
emitSignatureAndBody(node);
}
function emitAccessorDeclaration(node: AccessorDeclaration) {
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
write(node.kind === SyntaxKind.GetAccessor ? "get " : "set ");
emit(node.name);
emitSignatureAndBody(node);
}
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(";");
}
//
// 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);
emitParametersForArrow(node, node.parameters);
write(" => ");
emit(node.type);
}
function emitTypeQuery(node: TypeQueryNode) {
write("typeof ");
emit(node.exprName);
}
function emitTypeLiteral(node: TypeLiteralNode) {
write("{");
emitList(node, node.members, ListFormat.TypeLiteralMembers);
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) {
write("(");
emit(node.type);
write(")");
}
//
// Binding patterns
//
function emitObjectBindingPattern(node: ObjectBindingPattern) {
const elements = node.elements;
if (elements.length === 0) {
write("{}");
}
else {
write("{");
emitList(node, elements, ListFormat.ObjectBindingPatternElements);
write("}");
}
}
function emitArrayBindingPattern(node: ArrayBindingPattern) {
const elements = node.elements;
if (elements.length === 0) {
write("[]");
}
else {
write("[");
emitList(node, node.elements, ListFormat.ArrayBindingPatternElements);
write("]");
}
}
function emitBindingElement(node: BindingElement) {
emitWithSuffix(node.propertyName, ": ");
writeIfPresent(node.dotDotDotToken, "...");
emit(node.name);
emitExpressionWithPrefix(" = ", node.initializer);
}
//
// Expressions
//
function emitArrayLiteralExpression(node: ArrayLiteralExpression) {
const elements = node.elements;
if (elements.length === 0) {
write("[]");
}
else {
const preferNewLine = getNodeEmitFlags(node) & NodeEmitFlags.MultiLine ? ListFormat.PreferNewLine : ListFormat.None;
emitExpressionList(node, elements, ListFormat.ArrayLiteralExpressionElements | preferNewLine);
}
}
function emitObjectLiteralExpression(node: ObjectLiteralExpression) {
const properties = node.properties;
if (properties.length === 0) {
write("{}");
}
else {
const preferNewLine = getNodeEmitFlags(node) & NodeEmitFlags.MultiLine ? ListFormat.PreferNewLine : ListFormat.None;
const allowTrailingComma = languageVersion >= ScriptTarget.ES5 ? ListFormat.AllowTrailingComma : ListFormat.None;
emitList(node, properties, ListFormat.ObjectLiteralExpressionProperties | allowTrailingComma | preferNewLine);
}
}
function emitPropertyAccessExpression(node: PropertyAccessExpression) {
if (tryEmitConstantValue(node)) {
return;
}
const indentBeforeDot = needsIndentation(node, node.expression, node.dotToken);
const indentAfterDot = needsIndentation(node, node.dotToken, node.name);
const shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression);
emitExpression(node.expression);
increaseIndentIf(indentBeforeDot);
write(shouldEmitDotDot ? ".." : ".");
increaseIndentIf(indentAfterDot);
emit(node.name);
decreaseIndentIf(indentBeforeDot, indentAfterDot);
}
// 1..toString is a valid property access, emit a dot after the literal
// Also emit a dot if expression is a integer const enum value - it will appear in generated code as numeric literal
function needsDotDotForPropertyAccess(expression: Expression) {
if (expression.kind === SyntaxKind.NumericLiteral) {
// check if numeric literal was originally written with a dot
const text = getLiteralText(<LiteralExpression>expression, currentSourceFile, languageVersion);
return text.indexOf(tokenToString(SyntaxKind.DotToken)) < 0;
}
else {
// check if constant enum value is integer
const constantValue = tryGetConstEnumValue(expression);
// isFinite handles cases when constantValue is undefined
return isFinite(constantValue) && Math.floor(constantValue) === constantValue;
}
}
function emitElementAccessExpression(node: ElementAccessExpression) {
if (tryEmitConstantValue(node)) {
return;
}
emitExpression(node.expression);
write("[");
emitExpression(node.argumentExpression);
write("]");
}
function emitCallExpression(node: CallExpression) {
emitExpression(node.expression);
emitExpressionList(node, node.arguments, ListFormat.CallExpressionArguments);
}
function emitNewExpression(node: NewExpression) {
write("new ");
emitExpression(node.expression);
if (node.arguments) {
emitExpressionList(node, node.arguments, ListFormat.NewExpressionArguments);
}
}
function emitTaggedTemplateExpression(node: TaggedTemplateExpression) {
emitExpression(node.tag);
emitExpression(node.template);
}
function emitTypeAssertionExpression(node: TypeAssertion) {
if (node.type) {
write("<");
emit(node.type);
write(">");
}
emitExpression(node.expression);
}
function emitParenthesizedExpression(node: ParenthesizedExpression) {
write("(");
emitExpression(node.expression);
write(")");
}
function emitFunctionExpression(node: FunctionExpression) {
emitFunctionDeclarationOrExpression(node);
}
function emitArrowFunction(node: ArrowFunction) {
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
const body = node.body;
if (isBlock(body)) {
const savedTempFlags = tempFlags;
tempFlags = 0;
startLexicalEnvironment();
emitArrowFunctionHead(node);
write(" {");
const startingLine = writer.getLine();
emitBlockFunctionBody(node, body);
const endingLine = writer.getLine();
emitLexicalEnvironment(endLexicalEnvironment(), /*newLine*/ startingLine !== endingLine);
tempFlags = savedTempFlags;
write("}");
}
else {
emitArrowFunctionHead(node);
write(" ");
emitExpression(body);
}
}
function emitArrowFunctionHead(node: ArrowFunction) {
emitTypeParameters(node, node.typeParameters);