forked from microsoft/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeclarationEmitter.ts
More file actions
1777 lines (1585 loc) · 80.4 KB
/
Copy pathdeclarationEmitter.ts
File metadata and controls
1777 lines (1585 loc) · 80.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
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"/>
/* @internal */
namespace ts {
interface NodeLinks {
visibleChildren?: Node[];
visited?: boolean;
collected?: boolean;
hasExportDeclarations?: boolean;
errorReported?: boolean;
isInternal?: boolean;
}
interface PreprocessResults {
sourceFiles: SourceFile[];
nodeLinks: NodeLinks[];
resolver: EmitResolver;
}
const emptyHandler = () => { };
function writeDeclarations(outputFileName: string, preprocessResults: PreprocessResults, host: EmitHost, diagnostics: Diagnostic[]): void {
let newLine = host.getNewLine();
let compilerOptions = host.getCompilerOptions();
let enclosingDeclaration: Node;
let currentSourceFile: SourceFile;
let resolver = preprocessResults.resolver;
let nodeLinks = preprocessResults.nodeLinks;
// setup the writer
let writer = createNewTextWriterWithSymbolWriter();
let write = writer.write;
let writeTextOfNode = writer.writeTextOfNode;
let writeLine = writer.writeLine;
let increaseIndent = writer.increaseIndent;
let decreaseIndent = writer.decreaseIndent;
// Emit any triple-slash references
emitTripleSlashReferences(preprocessResults.sourceFiles);
for (let sourceFile of preprocessResults.sourceFiles) {
// emit the declarations from this file
emitSourceFile(sourceFile);
}
// write the output to disk
writeFile(host, diagnostics, outputFileName, writer.getText(), compilerOptions.emitBOM);
return;
function getNodeLinks(node: Node): NodeLinks {
let nodeId = getNodeId(node);
return nodeLinks[nodeId] || (nodeLinks[nodeId] = {});
}
function emitTripleSlashReferences(sourceFiles: SourceFile[]) {
if (compilerOptions.noResolve) {
// Nothing to do
return;
}
let emittedReferencedFiles: SourceFile[] = [];
let addedGlobalFileReference = false;
// Emit references corresponding to this file
for (let sourceFile of sourceFiles) {
emitTripleSlashReferncesInFile(sourceFile);
}
return;
function emitTripleSlashReferncesInFile(sourceFile: SourceFile): void {
forEach(sourceFile.referencedFiles, fileReference => {
let referencedFile = tryResolveScriptReference(host, sourceFile, fileReference);
// Could not find the file, or has been already emitted
if (!referencedFile || contains(emittedReferencedFiles, referencedFile)) {
return false;
}
let shouldEmitRefrence: boolean
if (isDeclarationFile(referencedFile) || shouldEmitToOwnFile(referencedFile, compilerOptions)) {
// If the reference file is a declaration file or an external module,
// we know there is going to be a .d.ts file matching it. Emit that reference
shouldEmitRefrence = true;
}
else if ((compilerOptions.out || compilerOptions.outFile) && !addedGlobalFileReference && isExternalModule(sourceFile)) {
// This is a reference to a file in the global island, since out is on, all files
// in the global island will be merged into one. so keep only one of these references
addedGlobalFileReference = true;
shouldEmitRefrence = true;
}
if (shouldEmitRefrence) {
emitReferencePath(referencedFile);
emittedReferencedFiles.push(referencedFile);
}
});
}
function emitReferencePath(referencedFile: SourceFile) {
let declFileName = referencedFile.flags & NodeFlags.DeclarationFile
? referencedFile.fileName // Declaration file, use declaration file name
: shouldEmitToOwnFile(referencedFile, compilerOptions)
? getOwnEmitOutputFilePath(referencedFile, host, ".d.ts") // Own output file so get the .d.ts file
: removeFileExtension(compilerOptions.outFile || compilerOptions.out) + ".d.ts"; // Global out file
declFileName = getRelativePathToDirectoryOrUrl(
getDirectoryPath(normalizeSlashes(outputFileName)),
declFileName,
host.getCurrentDirectory(),
host.getCanonicalFileName,
/*isAbsolutePathAnUrl*/ false);
write(`/// <reference path="${ declFileName }" />`);
writeLine();
}
}
function createNewTextWriterWithSymbolWriter(): EmitTextWriter & SymbolWriter {
let writer = <EmitTextWriter & SymbolWriter>createTextWriter(newLine);
writer.writeKeyword = writer.write;
writer.writeOperator = writer.write;
writer.writePunctuation = writer.write;
writer.writeSpace = writer.write;
writer.writeStringLiteral = writer.writeLiteral;
writer.writeParameter = writer.write;
writer.writeSymbol = writer.write;
return writer;
}
function emitTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration, type: TypeNode) {
write(": ");
if (type) {
// Write the type
emitType(type);
}
else {
resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, TypeFormatFlags.UseTypeOfFunction, writer);
}
}
function emitReturnTypeAtSignature(signature: SignatureDeclaration) {
write(": ");
if (signature.type) {
// Write the type
emitType(signature.type);
}
else {
resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, TypeFormatFlags.UseTypeOfFunction, writer);
}
}
function emitSeparatedList(nodes: Node[], separator: string, eachNodeEmitFn: (node: Node) => void) {
let currentWriterPos = writer.getTextPos();
for (let node of nodes) {
if (currentWriterPos !== writer.getTextPos()) {
write(separator);
}
currentWriterPos = writer.getTextPos();
eachNodeEmitFn(node);
}
}
function emitCommaList(nodes: Node[], eachNodeEmitFn: (node: Node) => void) {
emitSeparatedList(nodes, ", ", eachNodeEmitFn);
}
function emitJsDocComments(declaration: Node) {
if (!compilerOptions.removeComments) {
if (declaration) {
let jsDocComments = getJsDocComments(declaration, currentSourceFile);
emitNewLineBeforeLeadingComments(currentSourceFile, writer, declaration, jsDocComments);
// jsDoc comments are emitted at /*leading comment1 */space/*leading comment*/space
emitComments(currentSourceFile, writer, jsDocComments, /*trailingSeparator*/ true, newLine, writeCommentRange);
}
}
}
function emitType(type: TypeNode | Identifier | QualifiedName) {
switch (type.kind) {
case SyntaxKind.AnyKeyword:
case SyntaxKind.StringKeyword:
case SyntaxKind.NumberKeyword:
case SyntaxKind.BooleanKeyword:
case SyntaxKind.SymbolKeyword:
case SyntaxKind.VoidKeyword:
case SyntaxKind.StringLiteral:
return writeTextOfNode(currentSourceFile, type);
case SyntaxKind.ExpressionWithTypeArguments:
return emitExpressionWithTypeArguments(<ExpressionWithTypeArguments>type);
case SyntaxKind.TypeReference:
return emitTypeReference(<TypeReferenceNode>type);
case SyntaxKind.TypeQuery:
return emitTypeQuery(<TypeQueryNode>type);
case SyntaxKind.ArrayType:
return emitArrayType(<ArrayTypeNode>type);
case SyntaxKind.TupleType:
return emitTupleType(<TupleTypeNode>type);
case SyntaxKind.UnionType:
return emitUnionType(<UnionTypeNode>type);
case SyntaxKind.IntersectionType:
return emitIntersectionType(<IntersectionTypeNode>type);
case SyntaxKind.ParenthesizedType:
return emitParenType(<ParenthesizedTypeNode>type);
case SyntaxKind.FunctionType:
case SyntaxKind.ConstructorType:
return emitSignatureDeclarationWithJsDocComments(<FunctionOrConstructorTypeNode>type);
case SyntaxKind.TypeLiteral:
return emitTypeLiteral(<TypeLiteralNode>type);
case SyntaxKind.Identifier:
return emitEntityName(<Identifier>type);
case SyntaxKind.QualifiedName:
return emitEntityName(<QualifiedName>type);
case SyntaxKind.TypePredicate:
return emitTypePredicate(<TypePredicateNode>type);
}
function writeEntityName(entityName: EntityName | Expression) {
if (entityName.kind === SyntaxKind.Identifier) {
writeTextOfNode(currentSourceFile, entityName);
}
else {
let left = entityName.kind === SyntaxKind.QualifiedName ? (<QualifiedName>entityName).left : (<PropertyAccessExpression>entityName).expression;
let right = entityName.kind === SyntaxKind.QualifiedName ? (<QualifiedName>entityName).right : (<PropertyAccessExpression>entityName).name;
writeEntityName(left);
write(".");
writeTextOfNode(currentSourceFile, right);
}
}
function emitEntityName(entityName: EntityName | Expression) {
if (entityName.kind === SyntaxKind.Identifier) {
writeTextOfNode(currentSourceFile, entityName);
}
else {
let left = entityName.kind === SyntaxKind.QualifiedName ? (<QualifiedName>entityName).left : (<PropertyAccessExpression>entityName).expression;
let right = entityName.kind === SyntaxKind.QualifiedName ? (<QualifiedName>entityName).right : (<PropertyAccessExpression>entityName).name;
emitEntityName(left);
write(".");
writeTextOfNode(currentSourceFile, right);
}
}
function emitExpressionWithTypeArguments(node: ExpressionWithTypeArguments) {
if (isSupportedExpressionWithTypeArguments(node)) {
Debug.assert(node.expression.kind === SyntaxKind.Identifier || node.expression.kind === SyntaxKind.PropertyAccessExpression);
emitEntityName(<Identifier | PropertyAccessExpression>node.expression);
if (node.typeArguments) {
write("<");
emitCommaList(node.typeArguments, emitType);
write(">");
}
}
}
function emitTypeReference(type: TypeReferenceNode) {
emitEntityName(type.typeName);
if (type.typeArguments) {
write("<");
emitCommaList(type.typeArguments, emitType);
write(">");
}
}
function emitTypePredicate(type: TypePredicateNode) {
writeTextOfNode(currentSourceFile, type.parameterName);
write(" is ");
emitType(type.type);
}
function emitTypeQuery(type: TypeQueryNode) {
write("typeof ");
emitEntityName(type.exprName);
}
function emitArrayType(type: ArrayTypeNode) {
emitType(type.elementType);
write("[]");
}
function emitTupleType(type: TupleTypeNode) {
write("[");
emitCommaList(type.elementTypes, emitType);
write("]");
}
function emitUnionType(type: UnionTypeNode) {
emitSeparatedList(type.types, " | ", emitType);
}
function emitIntersectionType(type: IntersectionTypeNode) {
emitSeparatedList(type.types, " & ", emitType);
}
function emitParenType(type: ParenthesizedTypeNode) {
write("(");
emitType(type.type);
write(")");
}
function emitTypeLiteral(type: TypeLiteralNode) {
write("{");
if (type.members.length) {
writeLine();
increaseIndent();
// write members
forEach(type.members, emitNode);
decreaseIndent();
}
write("}");
}
}
// Return a temp variable name to be used in `export default` statements.
// The temp name will be of the form _default_counter.
// Note that export default is only allowed at most once in a module, so we
// do not need to keep track of created temp names.
function getExportDefaultTempVariableName(): string {
let baseName = "_default";
if (!hasProperty(currentSourceFile.identifiers, baseName)) {
return baseName;
}
let count = 0;
while (true) {
let name = baseName + "_" + (++count);
if (!hasProperty(currentSourceFile.identifiers, name)) {
return name;
}
}
}
function emitExportAssignment(node: ExportAssignment) {
if (node.expression.kind === SyntaxKind.Identifier) {
write(node.isExportEquals ? "export = " : "export default ");
writeTextOfNode(currentSourceFile, node.expression);
}
else {
// Expression
let tempVarName = getExportDefaultTempVariableName();
write("declare var ");
write(tempVarName);
write(": ");
resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, TypeFormatFlags.UseTypeOfFunction, writer);
write(";");
writeLine();
write(node.isExportEquals ? "export = " : "export default ");
write(tempVarName);
}
write(";");
writeLine();
}
function emitModuleElementDeclarationFlags(node: Node) {
// If the node is parented in the current source file we need to emit export declare or just export
if (node.parent === currentSourceFile) {
// If the node is exported
if (node.flags & NodeFlags.Export) {
write("export ");
}
if (node.flags & NodeFlags.Default) {
write("default ");
}
else if (node.kind !== SyntaxKind.InterfaceDeclaration) {
write("declare ");
}
}
}
function emitClassMemberDeclarationFlags(node: Declaration) {
if (node.flags & NodeFlags.Private) {
write("private ");
}
else if (node.flags & NodeFlags.Protected) {
write("protected ");
}
if (node.flags & NodeFlags.Static) {
write("static ");
}
if (node.flags & NodeFlags.Abstract) {
write("abstract ");
}
}
function emitImportEqualsDeclaration(node: ImportEqualsDeclaration) {
// note usage of writer. methods instead of aliases created, just to make sure we are using
// correct writer especially to handle asynchronous alias writing
emitJsDocComments(node);
if (node.flags & NodeFlags.Export) {
write("export ");
}
write("import ");
writeTextOfNode(currentSourceFile, node.name);
write(" = ");
if (isInternalModuleImportEqualsDeclaration(node)) {
emitType(<EntityName>node.moduleReference);
write(";");
}
else {
write("require(");
writeTextOfNode(currentSourceFile, getExternalModuleImportEqualsDeclarationExpression(node));
write(");");
}
writer.writeLine();
}
function emitImportDeclaration(node: ImportDeclaration) {
var children = sortDeclarations(getNodeLinks(node).visibleChildren);
if (!children) {
return;
}
emitJsDocComments(node);
write("import ");
let index: number;
if ((index = indexOf(children, node.importClause)) === 0) {
children.shift(); // remove it
writeTextOfNode(currentSourceFile, node.importClause.name);
if (children.length) {
// If the default binding was emitted, write the separated
write(", ");
}
}
if (node.importClause.namedBindings) {
if (node.importClause.namedBindings.kind === SyntaxKind.NamespaceImport &&
indexOf(children, node.importClause.namedBindings) >= 0) {
write("* as ");
writeTextOfNode(currentSourceFile, (<NamespaceImport>node.importClause.namedBindings).name);
}
else if (children.length) {
write("{ ");
emitCommaList(children, emitImportOrExportSpecifier);
write(" }");
}
}
write(" from ");
writeTextOfNode(currentSourceFile, node.moduleSpecifier);
write(";");
writer.writeLine();
}
function emitImportOrExportSpecifier(node: ImportOrExportSpecifier) {
if (node.propertyName) {
writeTextOfNode(currentSourceFile, node.propertyName);
write(" as ");
}
writeTextOfNode(currentSourceFile, node.name);
}
function emitExportSpecifier(node: ExportSpecifier) {
emitImportOrExportSpecifier(node);
}
function emitExportDeclaration(node: ExportDeclaration) {
emitJsDocComments(node);
write("export ");
if (node.exportClause) {
write("{ ");
emitCommaList(node.exportClause.elements, emitExportSpecifier);
write(" }");
}
else {
write("*");
}
if (node.moduleSpecifier) {
write(" from ");
writeTextOfNode(currentSourceFile, node.moduleSpecifier);
}
write(";");
writer.writeLine();
}
function emitModuleDeclaration(node: ModuleDeclaration) {
emitJsDocComments(node);
emitModuleElementDeclarationFlags(node);
if (node.flags & NodeFlags.Namespace) {
write("namespace ");
}
else {
write("module ");
}
writeTextOfNode(currentSourceFile, node.name);
while (node.body.kind !== SyntaxKind.ModuleBlock) {
node = <ModuleDeclaration>node.body;
write(".");
writeTextOfNode(currentSourceFile, node.name);
}
let prevEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = node;
write(" {");
writeLine();
increaseIndent();
//emitLines((<ModuleBlock>node.body).statements);
writeChildDeclarations(node);
decreaseIndent();
write("}");
writeLine();
enclosingDeclaration = prevEnclosingDeclaration;
}
function emitTypeAliasDeclaration(node: TypeAliasDeclaration) {
let prevEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = node;
emitJsDocComments(node);
emitModuleElementDeclarationFlags(node);
write("type ");
writeTextOfNode(currentSourceFile, node.name);
emitTypeParameters(node.typeParameters);
write(" = ");
emitType(node.type);
write(";");
writeLine();
enclosingDeclaration = prevEnclosingDeclaration;
}
function emitEnumDeclaration(node: EnumDeclaration) {
emitJsDocComments(node);
emitModuleElementDeclarationFlags(node);
if (isConst(node)) {
write("const ");
}
write("enum ");
writeTextOfNode(currentSourceFile, node.name);
write(" {");
writeLine();
increaseIndent();
//emitLines(node.members);
writeChildDeclarations(node);
decreaseIndent();
write("}");
writeLine();
}
function emitEnumMemberDeclaration(node: EnumMember) {
emitJsDocComments(node);
writeTextOfNode(currentSourceFile, node.name);
let enumMemberValue = resolver.getConstantValue(node);
if (enumMemberValue !== undefined) {
write(" = ");
write(enumMemberValue.toString());
}
write(",");
writeLine();
}
function isPrivateMethodTypeParameter(node: TypeParameterDeclaration) {
return node.parent.kind === SyntaxKind.MethodDeclaration && (node.parent.flags & NodeFlags.Private);
}
function emitTypeParameters(typeParameters: TypeParameterDeclaration[]) {
function emitTypeParameter(node: TypeParameterDeclaration) {
increaseIndent();
emitJsDocComments(node);
decreaseIndent();
writeTextOfNode(currentSourceFile, node.name);
// If there is constraint present and this is not a type parameter of the private method emit the constraint
if (node.constraint && !isPrivateMethodTypeParameter(node)) {
write(" extends ");
emitType(node.constraint);
}
}
if (typeParameters) {
write("<");
emitCommaList(typeParameters, emitTypeParameter);
write(">");
}
}
function emitHeritageClause(typeReferences: ExpressionWithTypeArguments[], isImplementsList: boolean) {
if (typeReferences) {
write(isImplementsList ? " implements " : " extends ");
emitCommaList(typeReferences, emitTypeOfTypeReference);
}
function emitTypeOfTypeReference(node: ExpressionWithTypeArguments) {
if (isSupportedExpressionWithTypeArguments(node)) {
emitType(node);
}
else if (!isImplementsList && node.expression.kind === SyntaxKind.NullKeyword) {
write("null");
}
else {
resolver.writeBaseConstructorTypeOfClass(<ClassLikeDeclaration>enclosingDeclaration, enclosingDeclaration, TypeFormatFlags.UseTypeOfFunction, writer);
}
}
}
function emitClassDeclaration(node: ClassDeclaration) {
function emitParameterProperties(constructorDeclaration: ConstructorDeclaration) {
if (constructorDeclaration) {
forEach(constructorDeclaration.parameters, param => {
if (param.flags & NodeFlags.AccessibilityModifier) {
emitPropertyDeclaration(param);
}
});
}
}
emitJsDocComments(node);
emitModuleElementDeclarationFlags(node);
if (node.flags & NodeFlags.Abstract) {
write("abstract ");
}
write("class ");
writeTextOfNode(currentSourceFile, node.name);
let prevEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = node;
emitTypeParameters(node.typeParameters);
let baseTypeNode = getClassExtendsHeritageClauseElement(node);
if (baseTypeNode) {
emitHeritageClause([baseTypeNode], /*isImplementsList*/ false);
}
emitHeritageClause(getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true);
write(" {");
writeLine();
increaseIndent();
emitParameterProperties(getFirstConstructorWithBody(node));
//emitLines(node.members);
writeChildDeclarations(node);
decreaseIndent();
write("}");
writeLine();
enclosingDeclaration = prevEnclosingDeclaration;
}
function emitInterfaceDeclaration(node: InterfaceDeclaration) {
emitJsDocComments(node);
emitModuleElementDeclarationFlags(node);
write("interface ");
writeTextOfNode(currentSourceFile, node.name);
let prevEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = node;
emitTypeParameters(node.typeParameters);
emitHeritageClause(getInterfaceBaseTypeNodes(node), /*isImplementsList*/ false);
write(" {");
writeLine();
increaseIndent();
//emitLines(node.members);
writeChildDeclarations(node);
decreaseIndent();
write("}");
writeLine();
enclosingDeclaration = prevEnclosingDeclaration;
}
function emitPropertyDeclaration(node: Declaration) {
if (hasDynamicName(node)) {
return;
}
emitJsDocComments(node);
emitClassMemberDeclarationFlags(node);
emitVariableDeclaration(<VariableDeclaration>node);
write(";");
writeLine();
}
function emitVariableDeclaration(node: VariableDeclaration) {
// If we are emitting property it isn't moduleElement and hence we already know it needs to be emitted
// so there is no check needed to see if declaration is visible
//if (node.kind !== SyntaxKind.VariableDeclaration) {
if (isBindingPattern(node.name)) {
emitBindingPattern(<BindingPattern>node.name);
}
else {
// If this node is a computed name, it can only be a symbol, because we've already skipped
// it if it's not a well known symbol. In that case, the text of the name will be exactly
// what we want, namely the name expression enclosed in brackets.
writeTextOfNode(currentSourceFile, node.name);
// If optional property emit ?
if ((node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature) && hasQuestionToken(node)) {
write("?");
}
if ((node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature) && node.parent.kind === SyntaxKind.TypeLiteral) {
emitTypeOfVariableDeclarationFromTypeLiteral(node);
}
else if (!(node.flags & NodeFlags.Private)) {
emitTypeOfDeclaration(node, node.type);
}
}
//}
function emitBindingPattern(bindingPattern: BindingPattern) {
// Only select non-omitted expression from the bindingPattern's elements.
// We have to do this to avoid emitting trailing commas.
// For example:
// original: var [, c,,] = [ 2,3,4]
// emitted: declare var c: number; // instead of declare var c:number, ;
let elements: Node[] = [];
for (let element of bindingPattern.elements) {
if (element.kind !== SyntaxKind.OmittedExpression) {
elements.push(element);
}
}
emitCommaList(elements, emitBindingElement);
}
function emitBindingElement(bindingElement: BindingElement) {
if (bindingElement.name) {
if (isBindingPattern(bindingElement.name)) {
emitBindingPattern(<BindingPattern>bindingElement.name);
}
else {
writeTextOfNode(currentSourceFile, bindingElement.name);
emitTypeOfDeclaration(bindingElement, /*type*/ undefined);
}
}
}
}
function emitTypeOfVariableDeclarationFromTypeLiteral(node: VariableLikeDeclaration) {
// if this is property of type literal,
// or is parameter of method/call/construct/index signature of type literal
// emit only if type is specified
if (node.type) {
write(": ");
emitType(node.type);
}
}
function hasChildDeclaration(node: VariableStatement): boolean {
return forEach(<VariableDeclaration[]>getNodeLinks(node).visibleChildren, child => {
if (isBindingPattern(child.name)) {
return forEach((<BindingPattern>child.name).elements, e => {
return e.kind !== SyntaxKind.OmittedExpression;
});
}
return true;
});
}
function emitVariableStatement(node: VariableStatement) {
let children = sortDeclarations(getNodeLinks(node).visibleChildren);
if (hasChildDeclaration(node)) {
emitJsDocComments(node);
emitModuleElementDeclarationFlags(node);
if (isLet(node.declarationList)) {
write("let ");
}
else if (isConst(node.declarationList)) {
write("const ");
}
else {
write("var ");
}
emitCommaList(children, emitVariableDeclaration);
write(";");
writeLine();
}
}
function emitAccessorDeclaration(node: AccessorDeclaration) {
if (hasDynamicName(node)) {
return;
}
let accessors = getAllAccessorDeclarations((<ClassDeclaration>node.parent).members, node);
if (node === accessors.firstAccessor) {
emitJsDocComments(accessors.getAccessor);
emitJsDocComments(accessors.setAccessor);
emitClassMemberDeclarationFlags(node);
writeTextOfNode(currentSourceFile, node.name);
if (!(node.flags & NodeFlags.Private)) {
let type = getTypeAnnotationFromAccessor(accessors.getAccessor, accessors.setAccessor);
emitTypeOfDeclaration(node, type);
}
write(";");
writeLine();
}
}
function emitFunctionDeclaration(node: FunctionLikeDeclaration) {
if (hasDynamicName(node)) {
return;
}
// If we are emitting Method/Constructor it isn't moduleElement and hence already determined to be emitting
// so no need to verify if the declaration is visible
if (!resolver.isImplementationOfOverload(node)) {
emitJsDocComments(node);
if (node.kind === SyntaxKind.FunctionDeclaration) {
emitModuleElementDeclarationFlags(node);
}
else if (node.kind === SyntaxKind.MethodDeclaration) {
emitClassMemberDeclarationFlags(node);
}
if (node.kind === SyntaxKind.FunctionDeclaration) {
write("function ");
writeTextOfNode(currentSourceFile, node.name);
}
else if (node.kind === SyntaxKind.Constructor) {
write("constructor");
}
else {
writeTextOfNode(currentSourceFile, node.name);
if (hasQuestionToken(node)) {
write("?");
}
}
emitSignatureDeclaration(node);
}
}
function emitSignatureDeclarationWithJsDocComments(node: SignatureDeclaration) {
emitJsDocComments(node);
emitSignatureDeclaration(node);
}
function emitSignatureDeclaration(node: SignatureDeclaration) {
// Construct signature or constructor type write new Signature
if (node.kind === SyntaxKind.ConstructSignature || node.kind === SyntaxKind.ConstructorType) {
write("new ");
}
emitTypeParameters(node.typeParameters);
if (node.kind === SyntaxKind.IndexSignature) {
write("[");
}
else {
write("(");
}
let prevEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = node;
// Parameters
emitCommaList(node.parameters, emitParameterDeclaration);
if (node.kind === SyntaxKind.IndexSignature) {
write("]");
}
else {
write(")");
}
// If this is not a constructor and is not private, emit the return type
let isFunctionTypeOrConstructorType = node.kind === SyntaxKind.FunctionType || node.kind === SyntaxKind.ConstructorType;
if (isFunctionTypeOrConstructorType || node.parent.kind === SyntaxKind.TypeLiteral) {
// Emit type literal signature return type only if specified
if (node.type) {
write(isFunctionTypeOrConstructorType ? " => " : ": ");
emitType(node.type);
}
}
else if (node.kind !== SyntaxKind.Constructor && !(node.flags & NodeFlags.Private)) {
emitReturnTypeAtSignature(node);
}
enclosingDeclaration = prevEnclosingDeclaration;
if (!isFunctionTypeOrConstructorType) {
write(";");
writeLine();
}
}
function emitParameterDeclaration(node: ParameterDeclaration) {
increaseIndent();
emitJsDocComments(node);
if (node.dotDotDotToken) {
write("...");
}
if (isBindingPattern(node.name)) {
// For bindingPattern, we can't simply writeTextOfNode from the source file
// because we want to omit the initializer and using writeTextOfNode will result in initializer get emitted.
// Therefore, we will have to recursively emit each element in the bindingPattern.
emitBindingPattern(<BindingPattern>node.name);
}
else {
writeTextOfNode(currentSourceFile, node.name);
}
if (resolver.isOptionalParameter(node)) {
write("?");
}
decreaseIndent();
if (node.parent.kind === SyntaxKind.FunctionType ||
node.parent.kind === SyntaxKind.ConstructorType ||
node.parent.parent.kind === SyntaxKind.TypeLiteral) {
emitTypeOfVariableDeclarationFromTypeLiteral(node);
}
else if (!(node.parent.flags & NodeFlags.Private)) {
emitTypeOfDeclaration(node, node.type);
}
function emitBindingPattern(bindingPattern: BindingPattern) {
// We have to explicitly emit square bracket and bracket because these tokens are not store inside the node.
if (bindingPattern.kind === SyntaxKind.ObjectBindingPattern) {
write("{");
emitCommaList(bindingPattern.elements, emitBindingElement);
write("}");
}
else if (bindingPattern.kind === SyntaxKind.ArrayBindingPattern) {
write("[");
let elements = bindingPattern.elements;
emitCommaList(elements, emitBindingElement);
if (elements && elements.hasTrailingComma) {
write(", ");
}
write("]");
}
}
function emitBindingElement(bindingElement: BindingElement) {
if (bindingElement.kind === SyntaxKind.OmittedExpression) {
// If bindingElement is an omittedExpression (i.e. containing elision),
// we will emit blank space (although this may differ from users' original code,
// it allows emitSeparatedList to write separator appropriately)
// Example:
// original: function foo([, x, ,]) {}
// emit : function foo([ , x, , ]) {}
write(" ");
}
else if (bindingElement.kind === SyntaxKind.BindingElement) {
if (bindingElement.propertyName) {
// bindingElement has propertyName property in the following case:
// { y: [a,b,c] ...} -> bindingPattern will have a property called propertyName for "y"
// We have to explicitly emit the propertyName before descending into its binding elements.
// Example:
// original: function foo({y: [a,b,c]}) {}
// emit : declare function foo({y: [a, b, c]}: { y: [any, any, any] }) void;
writeTextOfNode(currentSourceFile, bindingElement.propertyName);
write(": ");
}
if (bindingElement.name) {
if (isBindingPattern(bindingElement.name)) {
// If it is a nested binding pattern, we will recursively descend into each element and emit each one separately.
// In the case of rest element, we will omit rest element.
// Example:
// original: function foo([a, [[b]], c] = [1,[["string"]], 3]) {}
// emit : declare function foo([a, [[b]], c]: [number, [[string]], number]): void;
// original with rest: function foo([a, ...c]) {}
// emit : declare function foo([a, ...c]): void;
emitBindingPattern(<BindingPattern>bindingElement.name);
}
else {
Debug.assert(bindingElement.name.kind === SyntaxKind.Identifier);
// If the node is just an identifier, we will simply emit the text associated with the node's name
// Example:
// original: function foo({y = 10, x}) {}
// emit : declare function foo({y, x}: {number, any}): void;
if (bindingElement.dotDotDotToken) {
write("...");
}
writeTextOfNode(currentSourceFile, bindingElement.name);
}
}
}
}
}
function emitNode(node: Node) {
switch (node.kind) {
case SyntaxKind.FunctionDeclaration:
return emitFunctionDeclaration(<FunctionLikeDeclaration>node);
case SyntaxKind.VariableStatement:
return emitVariableStatement(<VariableStatement>node);
case SyntaxKind.InterfaceDeclaration:
return emitInterfaceDeclaration(<InterfaceDeclaration>node);
case SyntaxKind.ClassDeclaration:
return emitClassDeclaration(<ClassDeclaration>node);
case SyntaxKind.TypeAliasDeclaration:
return emitTypeAliasDeclaration(<TypeAliasDeclaration>node);
case SyntaxKind.EnumDeclaration:
return emitEnumDeclaration(<EnumDeclaration>node);
case SyntaxKind.ModuleDeclaration:
return emitModuleDeclaration(<ModuleDeclaration>node);
case SyntaxKind.ImportEqualsDeclaration:
return emitImportEqualsDeclaration(<ImportEqualsDeclaration>node);
case SyntaxKind.ImportDeclaration:
return emitImportDeclaration(<ImportDeclaration>node);
case SyntaxKind.ExportDeclaration:
return emitExportDeclaration(<ExportDeclaration>node);
case SyntaxKind.Constructor:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
return emitFunctionDeclaration(<FunctionLikeDeclaration>node);
case SyntaxKind.ConstructSignature:
case SyntaxKind.CallSignature:
case SyntaxKind.IndexSignature:
return emitSignatureDeclarationWithJsDocComments(<SignatureDeclaration>node);
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
return emitAccessorDeclaration(<AccessorDeclaration>node);
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.PropertySignature:
return emitPropertyDeclaration(<PropertyDeclaration>node);
case SyntaxKind.EnumMember:
return emitEnumMemberDeclaration(<EnumMember>node);