-
Notifications
You must be signed in to change notification settings - Fork 4
/
recast.ts
1175 lines (1078 loc) · 51.7 KB
/
recast.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
import ts, { factory } from 'typescript';
import * as rConcepts from './r-concepts';
import { NameResolver } from './name-resolver';
import * as tsUtils from './ts-utils';
export function recastTopLevelModule({
program,
typeChecker,
rModule,
nameResolver,
exportPrivates,
resolveEntity,
registerNonExportedSymbol,
privateJsDocTag,
}: {
program: ts.Program,
typeChecker: ts.TypeChecker,
rModule: rConcepts.ModuleTraits,
nameResolver: NameResolver,
exportPrivates?: boolean,
resolveEntity: (symbol: ts.Symbol) => rConcepts.Entity | undefined,
registerNonExportedSymbol: (symbol: ts.Symbol, currentModule: rConcepts.NamespaceTraits) => {
entity: rConcepts.Entity;
addStatements: (statements: ts.Statement[]) => void;
},
privateJsDocTag?: string,
}) {
const nodeFactor = ts.factory;
const moduleDeclaration = recastRModule(rModule);
return [moduleDeclaration];
function pushIfNonNull<T>(target: T[], source: T | null) {
if (source) {
target.push(source);
}
}
function pushMultiIfNonNull<T>(target: T[], source: T[] | null) {
if (source) {
target.push(...source);
}
}
function tryEmplaceModifier(modifiers: ts.Modifier[], kind: ts.Modifier['kind']) {
if (modifiers.every((m) => m.kind !== kind)) {
modifiers.unshift(nodeFactor.createModifier(kind));
}
}
function recastRModule(rModule: rConcepts.ModuleTraits) {
const statements = recastNamespaceTraits(rModule.entity.namespaceTraits!);
Object.entries(rModule.imports).map(([specifier, detail]) => {
const importSymbols = Object.entries(detail.namedImports);
if (importSymbols.length === 0) {
return;
}
const importSpecifiers = importSymbols.map(([importId, localId]): ts.ImportSpecifier => {
const lId = nodeFactor.createIdentifier(localId);
if (importId === localId) {
return nodeFactor.createImportSpecifier(false, undefined, lId);
} else {
return nodeFactor.createImportSpecifier(false, nodeFactor.createIdentifier(importId), lId);
}
});
statements.push(nodeFactor.createImportDeclaration(
undefined, // modifiers
nodeFactor.createImportClause(
false,
undefined,
nodeFactor.createNamedImports(importSpecifiers),
),
nodeFactor.createStringLiteral(specifier),
));
});
rModule.interopRecord.forEach((interop) => {
if (interop.exports.length !== 0) {
statements.push(nodeFactor.createExportDeclaration(
undefined, // modifiers
false, // isTypeOnly
nodeFactor.createNamedExports(interop.exports.map(({ importName, asName }) => asName === importName ?
nodeFactor.createExportSpecifier(false, undefined, nodeFactor.createIdentifier(importName)):
nodeFactor.createExportSpecifier(false, nodeFactor.createIdentifier(importName), nodeFactor.createIdentifier(asName)))),
nodeFactor.createStringLiteral(interop.specifier),
));
}
if (interop.imports.length !== 0) {
statements.push(nodeFactor.createImportDeclaration(
undefined, // modifiers
nodeFactor.createImportClause(
false,
undefined, // default import name
nodeFactor.createNamedImports(interop.imports.map(({ importName, asName }) => asName === importName ?
nodeFactor.createImportSpecifier(false, undefined, nodeFactor.createIdentifier(importName)):
nodeFactor.createImportSpecifier(false, nodeFactor.createIdentifier(importName), nodeFactor.createIdentifier(asName)))), // namespace import or named imports, or no
),
nodeFactor.createStringLiteral(interop.specifier),
));
}
});
// ts treat all things in .d.ts as public exports
// except it contains at least one `export {}` or `export default`.
// See:
// https://github.com/microsoft/TypeScript/issues/19545
statements.push(nodeFactor.createExportDeclaration(
undefined, // modifiers
false, // isTypeOnly,
nodeFactor.createNamedExports([]),
));
const moduleDeclaration = nodeFactor.createModuleDeclaration(
[nodeFactor.createModifier(ts.SyntaxKind.DeclareKeyword)],
nodeFactor.createStringLiteral(rModule.entity.name),
nodeFactor.createModuleBlock(statements),
);
return moduleDeclaration;
}
function recastREntity(rEntity: rConcepts.Entity) {
if (!rEntity.symbol) {
// For example: the `__private` namespace
return null;
}
const namespaceTraits = rEntity.namespaceTraits;
const declarations = rEntity.symbol.getDeclarations();
if (!declarations || declarations.length === 0) {
return null;
}
const statements: ts.Statement[] = [];
for (const declaration of declarations) {
pushIfNonNull(
statements,
recastDeclaration(declaration, rEntity.name, true),
);
}
if (namespaceTraits) {
const childrenEntityStatements = recastNamespaceTraits(namespaceTraits);
const namespaceDeclaration = nodeFactor.createModuleDeclaration(
[nodeFactor.createModifier(ts.SyntaxKind.ExportKeyword)], // TODO: recastModifiers(moduleDeclaration.modifiers),
nodeFactor.createIdentifier(rEntity.name),
nodeFactor.createModuleBlock(childrenEntityStatements),
ts.NodeFlags.Namespace,
);
const declaration0 = declarations[0];
if (declaration0.kind === ts.SyntaxKind.ModuleDeclaration) {
copyComments(declaration0, namespaceDeclaration);
}
statements.push(namespaceDeclaration);
}
return statements;
}
function recastNamespaceTraits(namespaceTraits: rConcepts.NamespaceTraits) {
const statements: ts.Statement[] = [];
nameResolver.enter(namespaceTraits);
for (const childEntity of namespaceTraits.children) {
pushMultiIfNonNull(
statements,
recastREntity(childEntity),
);
}
namespaceTraits.transformAliasExports();
if (namespaceTraits.selfExports.length !== 0) {
statements.push(nodeFactor.createExportDeclaration(
undefined, // modifiers
false, // isTypeOnly
nodeFactor.createNamedExports(namespaceTraits.selfExports.map(({ importName, asName }) => asName === importName ?
nodeFactor.createExportSpecifier(false, undefined, nodeFactor.createIdentifier(importName)):
nodeFactor.createExportSpecifier(false, nodeFactor.createIdentifier(importName), nodeFactor.createIdentifier(asName)))),
undefined,
));
}
for (const { where, importName, asName } of namespaceTraits.selfExportsFromNamespaces) {
statements.push(nodeFactor.createImportEqualsDeclaration(
[nodeFactor.createModifier(ts.SyntaxKind.ExportKeyword)], // modifiers
false,
nodeFactor.createIdentifier(asName),
nodeFactor.createQualifiedName(tsUtils.createEntityName(where), importName),
));
}
nameResolver.leave();
if (namespaceTraits.neNamespace) {
const neNsDeclaration = nodeFactor.createModuleDeclaration(
[nodeFactor.createModifier(ts.SyntaxKind.ExportKeyword)],
nodeFactor.createIdentifier(namespaceTraits.neNamespace.trait.entity.name),
nodeFactor.createModuleBlock(namespaceTraits.neNamespace.statements),
ts.NodeFlags.Namespace
);
statements.push(neNsDeclaration);
}
return statements;
}
function optimizeModuleSpecifierTo(from: rConcepts.ModuleTraits, to: string): string {
return to;
}
function recastStatement(statement: ts.Statement) {
if (ts.isClassDeclaration(statement)) {
return !statement.name ? null : recastClassDeclaration(statement, statement.name.text, false);
} else if (ts.isFunctionDeclaration(statement)) {
return !statement.name ? null : recastFunctionDeclaration(statement, statement.name.text, false);
} else if (ts.isInterfaceDeclaration(statement)) {
return !statement.name ? null : recastInterfaceDeclaration(statement, statement.name.text, false);
} else if (ts.isEnumDeclaration(statement)) {
return !statement.name ? null : recastEnumDeclaration(statement, statement.name.text, false);
} else if (ts.isTypeAliasDeclaration(statement)) {
return !statement.name ? null : recastTypeAliasDeclaration(statement, statement.name.text, false);
} else if (ts.isVariableStatement(statement)) {
return copyComments(statement, nodeFactor.createVariableStatement(
recastDeclarationModifiers(statement, false),
nodeFactor.createVariableDeclarationList(
statement.declarationList.declarations.map((declaration) =>
recastVariableDeclaration(declaration, declaration.name.getText(), false)),
statement.declarationList.flags,
),
));
} else if (ts.isImportDeclaration(statement)) {
return recastImportDeclaration(statement);
} else {
return null;
}
}
function recastStatements(statements: ts.Statement[] | ts.NodeArray<ts.Statement>): ts.Statement[] {
const result: ts.Statement[] = [];
for (const statement of statements) {
const newStatement = recastStatement(statement);
if (Array.isArray(newStatement)) {
result.push(...newStatement);
} else if (newStatement) {
result.push(newStatement);
}
}
return result;
}
function recastDeclaration(declaration: ts.Declaration, newName: string, forceExport: boolean): ts.Statement | null {
if (ts.isClassDeclaration(declaration)) {
return recastClassDeclaration(declaration, newName, forceExport);
} else if (ts.isFunctionDeclaration(declaration)) {
return recastFunctionDeclaration(declaration, newName, forceExport);
} else if (ts.isInterfaceDeclaration(declaration)) {
return recastInterfaceDeclaration(declaration, newName, forceExport);
} else if (ts.isEnumDeclaration(declaration)) {
return recastEnumDeclaration(declaration, newName, forceExport);
} else if (ts.isTypeAliasDeclaration(declaration)) {
return recastTypeAliasDeclaration(declaration, newName, forceExport);
} else if (ts.isVariableDeclaration(declaration)) {
return copyComments(declaration, nodeFactor.createVariableStatement(
recastDeclarationModifiers(declaration, forceExport),
nodeFactor.createVariableDeclarationList(
[recastVariableDeclaration(declaration, newName, forceExport)],
declaration.parent.flags,
),
));
} else if (ts.isModuleDeclaration(declaration)) {
// return recastModuleDeclaration(declaration, newName);
}
return null;
}
function copyComments<T extends ts.Node>(src: ts.Node, dst: T): T {
if (ts.isVariableDeclaration(src) &&
ts.isVariableDeclarationList(src.parent) &&
ts.isVariableStatement(src.parent.parent)) {
// https://github.com/microsoft/TypeScript/issues/35620
return copyComments(src.parent.parent, dst);
}
const sourceFileText = src.getSourceFile().text;
ts.forEachLeadingCommentRange(sourceFileText, src.pos, (pos, end, kind) => {
let tex = sourceFileText.substring(pos, end);
if (tex.startsWith('/*')) {
tex = tex.substr(2, tex.length - 4);
tex = tex.split('\n').map((line, lineIndex, lines) => {
const noHeadSpace = line.trimLeft();
if (lineIndex === lines.length - 1 && noHeadSpace.length === 0) {
return ' ';
} else if (!noHeadSpace.startsWith('*')) {
return line;
} else if (lineIndex === 0) {
return noHeadSpace;
} else {
return ` ${noHeadSpace}`
}
}).join('\n');
} else if (tex.startsWith('//')) {
tex = tex.substr(2);
}
ts.addSyntheticLeadingComment(dst, kind, tex, true);
});
return dst;
}
function recastSourceFileDeclarationAsNamespaceDeclaration(sourceFile: ts.SourceFile, newName: string) {
const newBody = nodeFactor.createModuleBlock(recastStatements(sourceFile.statements));
return nodeFactor.createModuleDeclaration(
undefined,
nodeFactor.createIdentifier(newName),
newBody,
ts.NodeFlags.Namespace, // TODO: flags. Maybe `ts.NodeFlags.Namespace`?
);
}
function recastModuleDeclarationAsNamespaceDeclaration(moduleDeclaration: ts.ModuleDeclaration, newName: string) {
const body = moduleDeclaration.body;
let newBody: ts.ModuleDeclaration['body'];
if (!body) {
// Fall through
} else if (ts.isIdentifier(body)) {
newBody = nodeFactor.createIdentifier(body.text);
} else if (ts.isModuleBlock(body)) {
newBody = nodeFactor.createModuleBlock(recastStatements(body.statements));
} else {
console.warn(`Unknown module declaration type ${tsUtils.stringifyNode(body)}`);
}
return nodeFactor.createModuleDeclaration(
recastDeclarationModifiers(moduleDeclaration, true),
nodeFactor.createIdentifier(newName),
newBody,
ts.NodeFlags.Namespace, // TODO: flags. Maybe `ts.NodeFlags.Namespace`?
);
}
function recastFunctionDeclaration(functionDeclaration: ts.FunctionDeclaration, newName: string, forceExport: boolean) {
return copyComments(functionDeclaration, nodeFactor.createFunctionDeclaration(
recastModifiers(functionDeclaration.modifiers),
functionDeclaration.asteriskToken,
newName,
recastTypeParameterArray(functionDeclaration.typeParameters),
recastParameterArray(functionDeclaration.parameters), // parameters
recastTypeNode(functionDeclaration.type),
undefined,
));
}
function recastVariableDeclaration(variableDeclaration: ts.VariableDeclaration, newName: string, forceExport: boolean) {
return nodeFactor.createVariableDeclaration(
newName,
recastToken(variableDeclaration.exclamationToken),
recastTypeNode(variableDeclaration.type),
recastExpression(variableDeclaration.initializer),
);
}
function recastPropertySignature(propertySignature: ts.PropertySignature) {
return copyComments(propertySignature, nodeFactor.createPropertySignature(
recastModifiers(propertySignature.modifiers), // modifiers
recastPropertyName(propertySignature.name), // name
recastToken(propertySignature.questionToken), // questionToken
recastTypeNode(propertySignature.type), // type
));
}
function recastMethodSignature(methodSignature: ts.MethodSignature) {
return copyComments(methodSignature, nodeFactor.createMethodSignature(
recastModifiers(methodSignature.modifiers), // modifiers
recastPropertyName(methodSignature.name), // name
recastToken(methodSignature.questionToken), // questionToken
recastTypeParameterArray(methodSignature.typeParameters), // typeParameters
recastParameterArray(methodSignature.parameters), // parameters
recastTypeNode(methodSignature.type), // type
));
}
function recastIndexSignatureDeclaration(indexSignature: ts.IndexSignatureDeclaration) {
return copyComments(indexSignature, nodeFactor.createIndexSignature(
undefined, // decorators
recastModifiers(indexSignature.modifiers), // modifiers
recastParameterArray(indexSignature.parameters), // parameters
recastTypeNode(indexSignature.type) || nodeFactor.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword), // type
));
}
function recastCallSignatureDeclaration(callSignature: ts.CallSignatureDeclaration) {
return copyComments(callSignature, nodeFactor.createCallSignature(
recastTypeParameterArray(callSignature.typeParameters), // typeParameters
recastParameterArray(callSignature.parameters), // parameters
recastTypeNode(callSignature.type), // type
));
}
function recastConstructorSignatureDeclaration(constructSignature: ts.ConstructSignatureDeclaration) {
return copyComments(constructSignature, nodeFactor.createConstructSignature(
recastTypeParameterArray(constructSignature.typeParameters),
recastParameterArray(constructSignature.parameters), // parameters
recastTypeNode(constructSignature.type),
));
}
function recastPropertyDeclaration(propertyDeclaration: ts.PropertyDeclaration) {
return copyComments(propertyDeclaration, nodeFactor.createPropertyDeclaration(
recastModifiers(nodeFactor.createNodeArray(ts.getModifiers(propertyDeclaration))),
recastPropertyName(propertyDeclaration.name),
recastToken(propertyDeclaration.questionToken),
recastTypeNode(propertyDeclaration.type),
recastExpression(propertyDeclaration.initializer),
));
}
function recastMethodDeclaration(methodDeclaration: ts.MethodDeclaration) {
return copyComments(methodDeclaration, (nodeFactor.createMethodDeclaration(
recastModifiers(nodeFactor.createNodeArray(ts.getModifiers(methodDeclaration))),
recastToken(methodDeclaration.asteriskToken),
recastPropertyName(methodDeclaration.name),
recastToken(methodDeclaration.questionToken),
recastTypeParameterArray(methodDeclaration.typeParameters),
recastParameterArray(methodDeclaration.parameters), // parameters
recastTypeNode(methodDeclaration.type),
undefined,
)));
}
function recastConstructorDeclaration(constructorDeclaration: ts.ConstructorDeclaration) {
return copyComments(constructorDeclaration, (nodeFactor.createConstructorDeclaration(
recastModifiers(constructorDeclaration.modifiers),
recastParameterArray(constructorDeclaration.parameters), // parameters
undefined,
)));
}
function recastParameter(parameter: ts.ParameterDeclaration) {
return nodeFactor.createParameterDeclaration(
recastModifiers(nodeFactor.createNodeArray(ts.getModifiers(parameter))),
recastToken(parameter.dotDotDotToken),
parameter.name.getText(),
recastToken(parameter.questionToken),
recastTypeNode(parameter.type),
);
}
function recastParameterArray(parameters: ts.NodeArray<ts.ParameterDeclaration>): ts.ParameterDeclaration[];
function recastParameterArray(parameters?: ts.NodeArray<ts.ParameterDeclaration>): ts.ParameterDeclaration[] | undefined;
function recastParameterArray(parameters?: ts.NodeArray<ts.ParameterDeclaration>) {
const lambda = (p: ts.ParameterDeclaration) => copyComments(p, (recastParameter(p)));
if (parameters) {
return parameters.map(lambda);
} else {
return undefined;
}
}
function recastTypeParameter(typeParameter: ts.TypeParameterDeclaration) {
return nodeFactor.createTypeParameterDeclaration(
undefined,
typeParameter.name.getText(),
recastTypeNode(typeParameter.constraint),
recastTypeNode(typeParameter.default),
);
}
function recastTypeParameterArray(
typeParameters?: ts.NodeArray<ts.TypeParameterDeclaration>) {
const lambda = (tp: ts.TypeParameterDeclaration) => copyComments(tp, (recastTypeParameter(tp)));
if (typeParameters) {
return typeParameters.map(lambda);
} else {
return undefined;
}
}
function recastImportDeclaration(importDeclaration: ts.ImportDeclaration): ts.Statement[] | null {
// if (!ts.isStringLiteral(importDeclaration.moduleSpecifier) ||
// !importDeclaration.importClause) {
// return null;
// }
// const moduleRegistry = this._getOrCreateModuleRegistry(importDeclaration.moduleSpecifier.text);
// const moduleFullName = getModuleRegistryFullNameArray(moduleRegistry);
// const moduleEntity = createEntityName(moduleFullName);
// const { namedBindings } = importDeclaration.importClause;
// if (namedBindings) {
// if (ts.isNamespaceImport(namedBindings)) {
// return [ts.createVariableStatement(
// undefined,
// [ts.createVariableDeclaration(
// ts.createIdentifier(
// namedBindings.name.text,
// ),
// ts.createTypeQueryNode(
// moduleEntity,
// ))])];
// } else {
// for (const element of namedBindings.elements) {
// }
// }
// }
return [];
}
function recastExportDeclaration(exportDeclaration: ts.ExportDeclaration): ts.Statement[] | null {
// if (exportDeclaration.moduleSpecifier) {
// if (!ts.isStringLiteral(exportDeclaration.moduleSpecifier)) {
// return null;
// }
// const moduleRegistry = this._getOrCreateModuleRegistry(exportDeclaration.moduleSpecifier.text);
// const moduleFullName = getModuleRegistryFullNameArray(moduleRegistry);
// const moduleEntity = createEntityName(moduleFullName);
// if (!exportDeclaration.exportClause) {
// }
// }
return null;
}
function recastClassDeclaration(
classDeclaration: ts.ClassDeclaration, newName: string, forceExport: boolean) {
const classElements: ts.ClassElement[] = [];
// console.log(`Dump class ${newName}`);
for (const element of classDeclaration.members) {
if (!exportPrivates && isPrivateMember(element)) {
continue;
}
if (privateJsDocTag) {
const symbol = typeChecker.getSymbolAtLocation(element.name!);
if (symbol && tsUtils.hasJsDocTag(symbol.getJsDocTags(), privateJsDocTag)) {
continue;
}
}
// const name = typeof element.name === 'string' ? typeof element.name :
// (element.name ? element.name.getText() : '');
// console.log(` Dump member ${name}`);
if (ts.isMethodDeclaration(element)) {
classElements.push(recastMethodDeclaration(element));
} else if (ts.isConstructorDeclaration(element)) {
classElements.push(recastConstructorDeclaration(element));
} else if (ts.isPropertyDeclaration(element)) {
classElements.push(recastPropertyDeclaration(element));
} else if (ts.isIndexSignatureDeclaration(element)) {
classElements.push(recastIndexSignatureDeclaration(element));
} else if (ts.isSemicolonClassElement(element)) {
classElements.push(nodeFactor.createSemicolonClassElement());
} else if (ts.isGetAccessor(element)) {
// Since TS 3.7
classElements.push(copyComments(element, nodeFactor.createGetAccessorDeclaration(
recastModifiers(nodeFactor.createNodeArray(ts.getModifiers(element))), // modifiers
recastPropertyName(element.name), // name
recastParameterArray(element.parameters), // parameters
recastTypeNode(element.type), // type
undefined, // body
)));
} else if (ts.isSetAccessor(element)) {
// Since TS 3.7
classElements.push(copyComments(element, nodeFactor.createSetAccessorDeclaration(
recastModifiers(nodeFactor.createNodeArray(ts.getModifiers(element))), // modifiers
recastPropertyName(element.name), // name
recastParameterArray(element.parameters), // parameters
undefined, // body
)));
} else {
console.warn(`Don't know how to handle element ${element.name?.getText()} of class ${newName}`);
}
}
return copyComments(classDeclaration, nodeFactor.createClassDeclaration(
recastDeclarationModifiers(classDeclaration, forceExport),
newName,
recastTypeParameterArray(classDeclaration.typeParameters),
recastHeritageClauses(classDeclaration.heritageClauses),
classElements,
));
}
function isPrivateMember(classElement: ts.ClassElement) {
const modifiers = canHaveModifiers(classElement) ? ts.getModifiers(classElement) : undefined;
if (!modifiers) {
return false;
}
return modifiers.some((modifier) => modifier.kind === ts.SyntaxKind.PrivateKeyword);
}
function recastInterfaceDeclaration(
interfaceDeclaration: ts.InterfaceDeclaration, newName: string, forceExport: boolean) {
return copyComments(interfaceDeclaration, nodeFactor.createInterfaceDeclaration(
recastDeclarationModifiers(interfaceDeclaration, forceExport),
newName,
recastTypeParameterArray(interfaceDeclaration.typeParameters),
recastHeritageClauses(interfaceDeclaration.heritageClauses),
recastTypeElements(interfaceDeclaration.members),
));
}
function recastTypeElement(typeElement: ts.TypeElement) {
if (ts.isMethodSignature(typeElement)) {
return recastMethodSignature(typeElement);
} else if (ts.isPropertySignature(typeElement)) {
return recastPropertySignature(typeElement);
} else if (ts.isIndexSignatureDeclaration(typeElement)) {
return recastIndexSignatureDeclaration(typeElement);
} else if (ts.isCallSignatureDeclaration(typeElement)) {
return recastCallSignatureDeclaration(typeElement);
} else if (ts.isConstructSignatureDeclaration(typeElement)) {
return recastConstructorSignatureDeclaration(typeElement);
}
}
function recastTypeElements(typeElements: ts.NodeArray<ts.TypeElement>) {
const result: ts.TypeElement[] = [];
for (const typeElement of typeElements) {
if (privateJsDocTag) {
const symbol = typeChecker.getSymbolAtLocation(typeElement.name!);
if (symbol && tsUtils.hasJsDocTag(symbol.getJsDocTags(), privateJsDocTag)) {
continue;
}
}
const d = recastTypeElement(typeElement);
if (d) {
result.push(d);
} else {
console.warn(`Don't know how to handle element ${typeElement.name?.getText()} of interface`);
}
}
return result;
}
function recastHeritageClause(heritageClause: ts.HeritageClause) {
const validClauses: ts.ExpressionWithTypeArguments[] = [];
for (const type of heritageClause.types) {
validClauses.push(nodeFactor.createExpressionWithTypeArguments(
recastExpression(type.expression),
type.typeArguments ? type.typeArguments.map((ta) => recastTypeNode(ta)!) : undefined,
));
}
return nodeFactor.createHeritageClause(
heritageClause.token,
validClauses,
);
}
function recastHeritageClauses(heritageClauses?: ts.NodeArray<ts.HeritageClause>) {
if (!heritageClauses) {
return undefined;
}
const lambda = (heritageClause: ts.HeritageClause) => recastHeritageClause(heritageClause);
if (heritageClauses) {
return heritageClauses.map(lambda);
} else {
return undefined;
}
}
function recastEnumDeclaration(enumDeclaration: ts.EnumDeclaration, newName: string, forceExport: boolean) {
return copyComments(enumDeclaration, nodeFactor.createEnumDeclaration(
recastDeclarationModifiers(enumDeclaration, forceExport),
newName,
enumDeclaration.members.map((enumerator) => {
return copyComments(enumerator, nodeFactor.createEnumMember(
enumerator.name.getText(),
recastExpression(enumerator.initializer),
));
}),
));
}
function recastTypeAliasDeclaration(
typeAliasDeclaration: ts.TypeAliasDeclaration, newName: string, forceExport: boolean) {
return copyComments(typeAliasDeclaration, nodeFactor.createTypeAliasDeclaration(
recastDeclarationModifiers(typeAliasDeclaration, forceExport),
newName,
recastTypeParameterArray(typeAliasDeclaration.typeParameters),
recastTypeNode(typeAliasDeclaration.type)!,
));
}
function recastModifiers(modifiers: ts.NodeArray<ts.Modifier>): ts.Modifier[];
function recastModifiers(modifiers?: ts.NodeArray<ts.Modifier>): ts.Modifier[] | undefined
function recastModifiers(modifiers?: ts.NodeArray<ts.Modifier>) {
if (!modifiers) {
return;
}
const result: ts.Modifier[] = [];
for (const modifier of modifiers) {
switch (modifier.kind) {
case ts.SyntaxKind.DefaultKeyword:
case ts.SyntaxKind.DeclareKeyword:
break;
default:
result.push(modifier);
break;
}
}
return result;
}
function canHaveModifiers (node: ts.Node): node is ts.HasModifiers {
// NOTE: `ts.canHaveModifiers` tells that `VariableDeclaration` cannot have modifiers.
// I think it's a bug on its implementation.
return ts.canHaveModifiers(node) || node.kind === ts.SyntaxKind.VariableDeclaration;
}
function recastDeclarationModifiers(declaration: ts.Declaration | ts.VariableStatement, forceExport: boolean): ts.Modifier[] | undefined {
if (!canHaveModifiers(declaration)) {
return [];
}
let modifiers = recastModifiers(nodeFactor.createNodeArray(ts.getModifiers(declaration))).filter((m) => m.kind !== ts.SyntaxKind.DeclareKeyword);
if (forceExport) {
if (!modifiers) {
modifiers = [];
}
tryEmplaceModifier(modifiers, ts.SyntaxKind.ExportKeyword);
}
return modifiers;
}
function recastTypeNode(type: ts.TypeNode): ts.TypeNode;
function recastTypeNode(type?: ts.TypeNode): ts.TypeNode | undefined;
function recastTypeNode(type?: ts.TypeNode): ts.TypeNode | undefined {
if (!type) {
return undefined;
}
const fallthrough = () => {
return nodeFactor.createTypeReferenceNode(type.getText(), undefined);
};
switch (type.kind) {
case ts.SyntaxKind.AnyKeyword:
case ts.SyntaxKind.BigIntKeyword:
case ts.SyntaxKind.BooleanKeyword:
case ts.SyntaxKind.NeverKeyword:
case ts.SyntaxKind.NumberKeyword:
case ts.SyntaxKind.ObjectKeyword:
case ts.SyntaxKind.StringKeyword:
case ts.SyntaxKind.SymbolKeyword:
case ts.SyntaxKind.UndefinedKeyword:
case ts.SyntaxKind.UnknownKeyword:
case ts.SyntaxKind.VoidKeyword:
return nodeFactor.createKeywordTypeNode(type.kind);
}
if (ts.isTypeReferenceNode(type)) {
return recastEntityNameAsTypeNode(
type.typeName,
type.typeArguments ? type.typeArguments.map((ta) => recastTypeNode(ta)) : undefined,
);
} else if (ts.isUnionTypeNode(type)) {
return nodeFactor.createUnionTypeNode(
type.types.map((t) => recastTypeNode(t)!));
} else if (ts.isTypeLiteralNode(type)) {
return nodeFactor.createTypeLiteralNode(recastTypeElements(type.members));
} else if (ts.isArrayTypeNode(type)) {
return nodeFactor.createArrayTypeNode(recastTypeNode(type.elementType));
} else if (ts.isParenthesizedTypeNode(type)) {
return nodeFactor.createParenthesizedType(recastTypeNode(type.type)!);
} else if (ts.isTypeQueryNode(type)) {
// typeof Entity
return nodeFactor.createTypeQueryNode(recastEntityName(type.exprName));
} else if (ts.isTypeOperatorNode(type)) {
return nodeFactor.createTypeOperatorNode(type.operator, recastTypeNode(type.type));
} else if (ts.isFunctionTypeNode(type)) {
return nodeFactor.createFunctionTypeNode(
recastTypeParameterArray(type.typeParameters),
recastParameterArray(type.parameters), // parameters
recastTypeNode(type.type),
);
} else if (ts.isConstructorTypeNode(type)) {
return nodeFactor.createConstructorTypeNode(
undefined,
recastTypeParameterArray(type.typeParameters),
recastParameterArray(type.parameters), // parameters
recastTypeNode(type.type),
);
} else if (ts.isImportTypeNode(type)) {
// import(ImportSpecifier)
const resolvedTypeName = resolveImportTypeOrTypeQueryNode(type);
if (resolvedTypeName) {
if (type.isTypeOf) {
// Note: `typeof import("")` is treated as a single importType with `isTypeOf` set to true
if (type.typeArguments) {
console.error(`Unexpected: typeof import("...") should not have arguments.`);
}
return nodeFactor.createTypeQueryNode(resolvedTypeName);
} else {
return nodeFactor.createTypeReferenceNode(
resolvedTypeName,
type.typeArguments ? type.typeArguments.map((ta) => recastTypeNode(ta)!) : undefined,
);
}
}
} else if (ts.isIntersectionTypeNode(type)) {
return nodeFactor.createIntersectionTypeNode(type.types.map((t) => recastTypeNode(t)));
} else if (ts.isIndexedAccessTypeNode(type)) {
return nodeFactor.createIndexedAccessTypeNode(
recastTypeNode(type.objectType), recastTypeNode(type.indexType));
} else if (ts.isThisTypeNode(type)) {
return nodeFactor.createThisTypeNode();
} else if (ts.isTypePredicateNode(type)) {
return nodeFactor.createTypePredicateNode(
type.assertsModifier ? nodeFactor.createToken(ts.SyntaxKind.AssertsKeyword) : undefined,
ts.isIdentifier(type.parameterName) ?
nodeFactor.createIdentifier(type.parameterName.text) :
nodeFactor.createThisTypeNode(),
recastTypeNode(type.type),
);
} else if (ts.isConditionalTypeNode(type)) {
return nodeFactor.createConditionalTypeNode(
recastTypeNode(type.checkType),
recastTypeNode(type.extendsType),
recastTypeNode(type.trueType),
recastTypeNode(type.falseType),
);
} else if (ts.isTupleTypeNode(type)) {
return nodeFactor.createTupleTypeNode(type.elements.map((elementType) => recastTypeNode(elementType)));
} else if (ts.isLiteralTypeNode(type)) {
const literal = type.literal;
let dumpedLiteral: typeof literal | undefined;
if (ts.isStringLiteral(literal)) {
dumpedLiteral = nodeFactor.createStringLiteral(literal.text);
} else if (literal.kind === ts.SyntaxKind.TrueKeyword) {
dumpedLiteral = nodeFactor.createTrue();
} else if (literal.kind === ts.SyntaxKind.FalseKeyword) {
dumpedLiteral = nodeFactor.createFalse();
} else if (literal.kind === ts.SyntaxKind.NullKeyword) {
dumpedLiteral = nodeFactor.createNull();
} else if (ts.isNumericLiteral(literal)) {
dumpedLiteral = nodeFactor.createNumericLiteral(literal.text);
} else if (ts.isBigIntLiteral(literal)) {
dumpedLiteral = nodeFactor.createBigIntLiteral(literal.text);
} else if (ts.isRegularExpressionLiteral(literal)) {
dumpedLiteral = nodeFactor.createRegularExpressionLiteral(literal.text);
} else if (ts.isNoSubstitutionTemplateLiteral(literal)) {
dumpedLiteral = nodeFactor.createNoSubstitutionTemplateLiteral(literal.text);
} else if (ts.isPrefixUnaryExpression(literal)) {
dumpedLiteral = nodeFactor.createPrefixUnaryExpression(literal.operator, recastExpression(literal.operand));
} else {
console.warn(`Don't know how to handle literal type ${type.getText()}(${tsUtils.stringifyNode(literal)})`);
}
if (dumpedLiteral) {
return nodeFactor.createLiteralTypeNode(dumpedLiteral);
}
} else if (ts.isMappedTypeNode(type)) {
return nodeFactor.createMappedTypeNode(
type.readonlyToken && type.readonlyToken.kind === ts.SyntaxKind.ReadonlyKeyword ?
factory.createModifier(type.readonlyToken.kind):
recastToken(type.readonlyToken),
recastTypeParameter(type.typeParameter),
recastTypeNode(type.nameType),
recastToken(type.questionToken),
recastTypeNode(type.type),
undefined
);
} else if (ts.isInferTypeNode(type)) {
return nodeFactor.createInferTypeNode(
recastTypeParameter(type.typeParameter),
);
} else if (type.kind === ts.SyntaxKind.RestType) {
return nodeFactor.createRestTypeNode(recastTypeNode((type as ts.RestTypeNode).type));
} else if (ts.isOptionalTypeNode(type)) {
return nodeFactor.createOptionalTypeNode(type.type);
} else if (ts.isNamedTupleMember(type)) {
return nodeFactor.createNamedTupleMember(
recastToken(type.dotDotDotToken),
recastIdentifier(type.name),
recastToken(type.questionToken),
recastTypeNode(type.type),
);
} else {
console.warn(`Don't know how to handle type ${type.getText()}(${tsUtils.stringifyNode(type)})`);
}
return type ? nodeFactor.createTypeReferenceNode(type.getText(), undefined) : undefined;
}
function recastToken(token: undefined): undefined;
function recastToken(token: ts.Token<ts.SyntaxKind.SuperKeyword> | undefined): ts.SuperExpression | undefined;
function recastToken(token: ts.Token<ts.SyntaxKind.ThisKeyword> | undefined): ts.ThisExpression | undefined;
function recastToken(token: ts.Token<ts.SyntaxKind.NullKeyword> | undefined): ts.NullLiteral | undefined;
function recastToken(token: ts.Token<ts.SyntaxKind.TrueKeyword> | undefined): ts.TrueLiteral | undefined;
function recastToken(token: ts.Token<ts.SyntaxKind.FalseKeyword> | undefined): ts.FalseLiteral | undefined;
function recastToken<TKind extends ts.PunctuationSyntaxKind>(token: ts.PunctuationToken<TKind> | undefined): ts.PunctuationToken<TKind> | undefined;
function recastToken<TKind extends ts.KeywordTypeSyntaxKind>(token: ts.KeywordTypeNode<TKind> | undefined): ts.KeywordTypeNode<TKind> | undefined;
function recastToken<TKind extends ts.ModifierSyntaxKind>(token: ts.ModifierToken<TKind> | undefined): ts.ModifierToken<TKind> | undefined;
function recastToken<TKind extends ts.KeywordSyntaxKind>(token: ts.KeywordToken<TKind> | undefined): ts.KeywordToken<TKind> | undefined;
function recastToken<TKind extends ts.SyntaxKind.Unknown | ts.SyntaxKind.EndOfFileToken>(token: ts.Token<TKind> | undefined): ts.Token<TKind> | undefined;
function recastToken<TKind extends ts.SyntaxKind>(token?: ts.Token<TKind>): any {
if (!token) {
return undefined;
}
const kind = token.kind as any;
return nodeFactor.createToken(kind);
}
function recastEntityName(name: ts.EntityName) {
const identifiers: ts.Identifier[] = [];
let n = name;
while (ts.isQualifiedName(n)) {
identifiers.unshift(n.right);
n = n.left;
}
identifiers.unshift(n);
let result: ts.EntityName | null = null;
for (let i = identifiers.length - 1; i >= 0; --i) {
const id = identifiers[i];
const resolveResult = resolveIdentifier(id);
if (resolveResult) {
const following = identifiers.slice(i + 1).map((id) => id.text);
// TODO
result = tsUtils.createEntityName(
following,
createEntityNameFromNameResolveResult(resolveResult));
}
}
return result || tsUtils.createEntityName(identifiers.map((id) => id.text));
}
function recastEntityNameAsTypeNode(name: ts.EntityName, typeArguments?: ts.TypeNode[]) {
const { leftmost, rights } = tsUtils.splitLeftmost(name);
const resolved = resolveIdentifier(leftmost);
if (resolved) {
return createTypeNodeFromNameResolveResult(
resolved,
rights.map((right) => right.text),
typeArguments
);
} else {
return nodeFactor.createTypeReferenceNode(
recastEntityNameTrivially(name),
typeArguments,
);
}
}
function recastEntityNameTrivially(name: ts.EntityName): ts.EntityName {
if (ts.isIdentifier(name)) {
return recastIdentifier(name);
} else {
return nodeFactor.createQualifiedName(
recastEntityNameTrivially(name.left),
recastIdentifier(name.right),
);
}
}
function recastIdentifier(id: ts.Identifier) {
return nodeFactor.createIdentifier(id.text);
}
function recastPropertyName(propertyName: ts.PropertyName) {
if (ts.isIdentifier(propertyName)) {
return nodeFactor.createIdentifier(propertyName.text);
} else if (ts.isStringLiteral(propertyName)) {
return nodeFactor.createStringLiteral(propertyName.text);
} else if (ts.isNumericLiteral(propertyName)) {
return nodeFactor.createNumericLiteral(propertyName.text);
} else if (ts.isPrivateIdentifier(propertyName)) {
return nodeFactor.createPrivateIdentifier(propertyName.text);
} else {
return nodeFactor.createComputedPropertyName(recastExpression(propertyName.expression));
}
}
function recastBooleanLiteral(node: ts.BooleanLiteral) {
return nodeFactor.createToken(node.kind);
}
function recastStringLiteral(node: ts.StringLiteral) {
return nodeFactor.createStringLiteral(node.text);
}
function recastExpression(expression: ts.Expression): ts.Expression;
function recastExpression(expression?: ts.Expression): ts.Expression | undefined;
// Only literals are supported
function recastExpression(expression?: ts.Expression): ts.Expression | undefined {
if (!expression) {
return undefined;
}
if (ts.isStringLiteral(expression)) {
return nodeFactor.createStringLiteral(expression.text);
} else if (ts.isNumericLiteral(expression)) {
return nodeFactor.createNumericLiteral(expression.text);
} else if (expression.kind === ts.SyntaxKind.TrueKeyword) {
return nodeFactor.createTrue();
} else if (expression.kind === ts.SyntaxKind.FalseKeyword) {
return nodeFactor.createFalse();
} else if (expression.kind === ts.SyntaxKind.NullKeyword) {
return nodeFactor.createNull();
} else if (ts.isIdentifier(expression)) {
return recastIdExpression(expression);
} else if (ts.isPropertyAccessExpression(expression)) {
return nodeFactor.createPropertyAccessExpression(
recastExpression(expression.expression),
expression.name.text);
} else {