-
-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathprocessor.js
More file actions
1230 lines (1109 loc) · 44.1 KB
/
processor.js
File metadata and controls
1230 lines (1109 loc) · 44.1 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
/**
* TypeScript type processing functionality
* @module processor
*/
// @ts-check
import ts from 'typescript';
/** @typedef {import('./index.d.ts').Parameter} Parameter */
/**
* @typedef {{
* print: (level: "warning" | "error", message: string, node?: ts.Node) => void,
* }} DiagnosticEngine
*/
/**
* TypeScript type processor class
*/
export class TypeProcessor {
/**
* Create a TypeScript program from a d.ts file
* @param {string[]} filePaths - Paths to the d.ts file
* @param {ts.CompilerOptions} options - Compiler options
* @returns {ts.Program} TypeScript program object
*/
static createProgram(filePaths, options) {
const host = ts.createCompilerHost(options);
return ts.createProgram(filePaths, {
...options,
noCheck: true,
skipLibCheck: true,
}, host);
}
/**
* @param {ts.TypeChecker} checker - TypeScript type checker
* @param {DiagnosticEngine} diagnosticEngine - Diagnostic engine
*/
constructor(checker, diagnosticEngine, options = {
defaultImportFromGlobal: false,
}) {
this.checker = checker;
this.diagnosticEngine = diagnosticEngine;
this.options = options;
/** @type {Map<ts.Type, string>} */
this.processedTypes = new Map();
/** @type {Map<ts.Type, ts.Node>} Seen position by type */
this.seenTypes = new Map();
/** @type {string[]} Collected Swift code lines */
this.swiftLines = [];
/** @type {Set<string>} */
this.emittedEnumNames = new Set();
/** @type {Set<string>} */
this.emittedStructuredTypeNames = new Set();
/** @type {Set<string>} */
this.visitedDeclarationKeys = new Set();
/** @type {Map<string, string>} */
this.swiftTypeNameByJSTypeName = new Map();
/** @type {boolean} */
this.defaultImportFromGlobal = options.defaultImportFromGlobal ?? false;
}
/**
* Escape a string for a Swift string literal inside macro arguments.
* @param {string} value
* @returns {string}
* @private
*/
escapeForSwiftStringLiteral(value) {
return value.replaceAll("\\", "\\\\").replaceAll("\"", "\\\\\"");
}
/**
* Render a `jsName:` macro argument if the JS name differs from the default.
* @param {string} jsName
* @param {string} defaultName
* @returns {string | null}
* @private
*/
renderOptionalJSNameArg(jsName, defaultName) {
if (jsName === defaultName) return null;
return `jsName: "${this.escapeForSwiftStringLiteral(jsName)}"`;
}
/**
* Render a macro annotation with optional labeled arguments.
* @param {string} macroName
* @param {string[]} args
* @returns {string}
* @private
*/
renderMacroAnnotation(macroName, args) {
if (!args.length) return `@${macroName}`;
return `@${macroName}(${args.join(", ")})`;
}
/**
* Convert a TypeScript type name to a valid Swift type identifier.
* @param {string} jsTypeName
* @returns {string}
* @private
*/
swiftTypeName(jsTypeName) {
const cached = this.swiftTypeNameByJSTypeName.get(jsTypeName);
if (cached) return cached;
const swiftName = isValidSwiftDeclName(jsTypeName) ? jsTypeName : makeValidSwiftIdentifier(jsTypeName, { emptyFallback: "_" });
this.swiftTypeNameByJSTypeName.set(jsTypeName, swiftName);
return swiftName;
}
/**
* Render a Swift type identifier from a TypeScript type name.
* @param {string} jsTypeName
* @returns {string}
* @private
*/
renderTypeIdentifier(jsTypeName) {
return this.renderIdentifier(this.swiftTypeName(jsTypeName));
}
/**
* Process type declarations from a TypeScript program and render Swift code
* @param {ts.Program} program - TypeScript program
* @param {string} inputFilePath - Path to the input file
* @returns {{ content: string, hasAny: boolean }} Rendered Swift code
*/
processTypeDeclarations(program, inputFilePath) {
const sourceFiles = program.getSourceFiles().filter(
sf => !sf.isDeclarationFile || sf.fileName === inputFilePath
);
for (const sourceFile of sourceFiles) {
if (sourceFile.fileName.includes('node_modules/typescript/lib')) continue;
Error.stackTraceLimit = 100;
try {
sourceFile.forEachChild(node => {
this.visitNode(node);
for (const [type, node] of this.seenTypes) {
this.seenTypes.delete(type);
if (this.isEnumType(type)) {
this.visitEnumType(type, node);
continue;
}
const members = type.getProperties();
if (members) {
this.visitStructuredType(type, node, members);
}
}
});
} catch (/** @type {unknown} */ error) {
if (error instanceof Error) {
this.diagnosticEngine.print("error", `Error processing ${sourceFile.fileName}: ${error.message}`);
} else {
this.diagnosticEngine.print("error", `Error processing ${sourceFile.fileName}: ${String(error)}`);
}
}
}
const content = this.swiftLines.join("\n").trimEnd() + "\n";
const hasAny = content.trim().length > 0;
return { content, hasAny };
}
/**
* Visit a node and process it
* @param {ts.Node} node - The node to visit
*/
visitNode(node) {
if (ts.isFunctionDeclaration(node)) {
this.visitFunctionDeclaration(node);
} else if (ts.isClassDeclaration(node)) {
this.visitClassDecl(node);
} else if (ts.isVariableStatement(node)) {
this.visitVariableStatement(node);
} else if (ts.isEnumDeclaration(node)) {
this.visitEnumDeclaration(node);
} else if (ts.isExportDeclaration(node)) {
this.visitExportDeclaration(node);
}
}
/**
* Visit an export declaration and process re-exports like:
* - export { Thing } from "./module";
* - export { Thing as Alias } from "./module";
* - export * from "./module";
* @param {ts.ExportDeclaration} node
*/
visitExportDeclaration(node) {
if (!node.moduleSpecifier) return;
const moduleSymbol = this.checker.getSymbolAtLocation(node.moduleSpecifier);
if (!moduleSymbol) {
this.diagnosticEngine.print("warning", "Failed to resolve module for export declaration", node);
return;
}
/** @type {ts.Symbol[]} */
let targetSymbols = [];
if (!node.exportClause) {
// export * from "..."
targetSymbols = this.checker.getExportsOfModule(moduleSymbol);
} else if (ts.isNamedExports(node.exportClause)) {
const moduleExports = this.checker.getExportsOfModule(moduleSymbol);
for (const element of node.exportClause.elements) {
const originalName = element.propertyName?.text ?? element.name.text;
const match = moduleExports.find(s => s.name === originalName);
if (match) {
targetSymbols.push(match);
continue;
}
// Fallback for unusual bindings/resolution failures.
const fallback = this.checker.getSymbolAtLocation(element.propertyName ?? element.name);
if (fallback) {
targetSymbols.push(fallback);
continue;
}
this.diagnosticEngine.print("warning", `Failed to resolve re-exported symbol '${originalName}'`, node);
}
} else {
// export * as ns from "..." is not currently supported by BridgeJS imports.
return;
}
for (const symbol of targetSymbols) {
const declarations = symbol.getDeclarations() ?? [];
for (const declaration of declarations) {
// Avoid duplicate emission when the same declaration is reached via multiple re-exports.
const sourceFile = declaration.getSourceFile();
const key = `${sourceFile.fileName}:${declaration.pos}:${declaration.end}`;
if (this.visitedDeclarationKeys.has(key)) continue;
this.visitedDeclarationKeys.add(key);
this.visitNode(declaration);
}
}
}
/**
* Visit an exported variable statement and render Swift global getter(s).
* Supports simple `export const foo: T` / `export let foo: T` declarations.
*
* @param {ts.VariableStatement} node
* @private
*/
visitVariableStatement(node) {
const isExported = node.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword) ?? false;
if (!isExported) return;
const fromArg = this.renderDefaultJSImportFromArgument();
for (const decl of node.declarationList.declarations) {
if (!ts.isIdentifier(decl.name)) continue;
const jsName = decl.name.text;
const swiftName = this.swiftTypeName(jsName);
const swiftVarName = this.renderIdentifier(swiftName);
const type = this.checker.getTypeAtLocation(decl);
const swiftType = this.visitType(type, decl);
/** @type {string[]} */
const args = [];
const jsNameArg = this.renderOptionalJSNameArg(jsName, swiftName);
if (jsNameArg) args.push(jsNameArg);
if (fromArg) args.push(fromArg);
const annotation = this.renderMacroAnnotation("JSGetter", args);
this.emitDocComment(decl, { indent: "" });
this.swiftLines.push(`${annotation} var ${swiftVarName}: ${swiftType}`);
this.swiftLines.push("");
}
}
/**
* @param {ts.Type} type
* @returns {boolean}
* @private
*/
isEnumType(type) {
const symbol = type.getSymbol() ?? type.aliasSymbol;
if (!symbol) return false;
return (symbol.flags & ts.SymbolFlags.Enum) !== 0;
}
/**
* @param {ts.EnumDeclaration} node
* @private
*/
visitEnumDeclaration(node) {
const name = node.name?.text;
if (!name) return;
this.emitEnumFromDeclaration(name, node, node);
}
/**
* @param {ts.Type} type
* @param {ts.Node} node
* @private
*/
visitEnumType(type, node) {
const symbol = type.getSymbol() ?? type.aliasSymbol;
const name = symbol?.name;
if (!name) return;
const decl = symbol?.getDeclarations()?.find(d => ts.isEnumDeclaration(d));
if (!decl || !ts.isEnumDeclaration(decl)) {
this.diagnosticEngine.print("warning", `Enum declaration not found for type: ${name}`, node);
return;
}
this.emitEnumFromDeclaration(name, decl, node);
}
/**
* @param {string} enumName
* @param {ts.EnumDeclaration} decl
* @param {ts.Node} diagnosticNode
* @private
*/
emitEnumFromDeclaration(enumName, decl, diagnosticNode) {
if (this.emittedEnumNames.has(enumName)) return;
this.emittedEnumNames.add(enumName);
const members = decl.members ?? [];
this.emitDocComment(decl, { indent: "" });
if (members.length === 0) {
this.diagnosticEngine.print("warning", `Empty enum is not supported: ${enumName}`, diagnosticNode);
this.swiftLines.push(`typealias ${this.renderIdentifier(enumName)} = String`);
this.swiftLines.push("");
return;
}
/** @type {{ name: string, raw: string }[]} */
const stringMembers = [];
/** @type {{ name: string, raw: number }[]} */
const intMembers = [];
let canBeStringEnum = true;
let canBeIntEnum = true;
let nextAutoValue = 0;
for (const member of members) {
const rawMemberName = member.name.getText();
const unquotedName = rawMemberName.replace(/^["']|["']$/g, "");
const swiftCaseNameBase = makeValidSwiftIdentifier(unquotedName, { emptyFallback: "_case" });
if (member.initializer && ts.isStringLiteral(member.initializer)) {
stringMembers.push({ name: swiftCaseNameBase, raw: member.initializer.text });
canBeIntEnum = false;
continue;
}
if (member.initializer && ts.isNumericLiteral(member.initializer)) {
const rawValue = Number(member.initializer.text);
if (!Number.isInteger(rawValue)) {
canBeIntEnum = false;
} else {
intMembers.push({ name: swiftCaseNameBase, raw: rawValue });
nextAutoValue = rawValue + 1;
canBeStringEnum = false;
continue;
}
}
if (!member.initializer) {
intMembers.push({ name: swiftCaseNameBase, raw: nextAutoValue });
nextAutoValue += 1;
canBeStringEnum = false;
continue;
}
canBeStringEnum = false;
canBeIntEnum = false;
}
const swiftEnumName = this.renderTypeIdentifier(enumName);
const dedupeNames = (/** @type {{ name: string, raw: string | number }[]} */ items) => {
const seen = new Map();
return items.map(item => {
const count = seen.get(item.name) ?? 0;
seen.set(item.name, count + 1);
if (count === 0) return item;
return { ...item, name: `${item.name}_${count + 1}` };
});
};
if (canBeStringEnum && stringMembers.length > 0) {
this.swiftLines.push(`enum ${swiftEnumName}: String {`);
for (const { name, raw } of dedupeNames(stringMembers)) {
if (typeof raw !== "string") {
this.diagnosticEngine.print("warning", `Invalid string literal: ${raw}`, diagnosticNode);
continue;
}
this.swiftLines.push(` case ${this.renderIdentifier(name)} = "${raw.replaceAll("\"", "\\\\\"")}"`);
}
this.swiftLines.push("}");
this.swiftLines.push(`extension ${swiftEnumName}: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum {}`);
this.swiftLines.push("");
return;
}
if (canBeIntEnum && intMembers.length > 0) {
this.swiftLines.push(`enum ${swiftEnumName}: Int {`);
for (const { name, raw } of dedupeNames(intMembers)) {
this.swiftLines.push(` case ${this.renderIdentifier(name)} = ${raw}`);
}
this.swiftLines.push("}");
this.swiftLines.push(`extension ${swiftEnumName}: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum {}`);
this.swiftLines.push("");
return;
}
this.diagnosticEngine.print(
"warning",
`Unsupported enum (only string or int enums are supported): ${enumName}`,
diagnosticNode
);
this.swiftLines.push(`typealias ${swiftEnumName} = String`);
this.swiftLines.push("");
}
/**
* Visit a function declaration and render Swift code
* @param {ts.FunctionDeclaration} node - The function node
* @private
*/
visitFunctionDeclaration(node) {
if (!node.name) return;
const jsName = node.name.text;
const swiftName = this.swiftTypeName(jsName);
const fromArg = this.renderDefaultJSImportFromArgument();
/** @type {string[]} */
const args = [];
const jsNameArg = this.renderOptionalJSNameArg(jsName, swiftName);
if (jsNameArg) args.push(jsNameArg);
if (fromArg) args.push(fromArg);
const annotation = this.renderMacroAnnotation("JSFunction", args);
const signature = this.checker.getSignatureFromDeclaration(node);
if (!signature) return;
const parameters = signature.getParameters();
const parameterNameMap = this.buildParameterNameMap(parameters);
const params = this.renderParameters(parameters, node);
const returnType = this.visitType(signature.getReturnType(), node);
const effects = this.renderEffects({ isAsync: false });
const swiftFuncName = this.renderIdentifier(swiftName);
this.emitDocComment(node, { parameterNameMap });
this.swiftLines.push(`${annotation} func ${swiftFuncName}(${params}) ${effects} -> ${returnType}`);
this.swiftLines.push("");
}
/**
* Convert a JSDoc comment node content to plain text.
* @param {string | ts.NodeArray<ts.JSDocComment> | undefined} comment
* @returns {string}
* @private
*/
renderJSDocText(comment) {
if (!comment) return "";
if (typeof comment === "string") return comment;
let result = "";
for (const part of comment) {
if (typeof part === "string") {
result += part;
continue;
}
// JSDocText/JSDocLink both have a `text` field
// https://github.com/microsoft/TypeScript/blob/main/src/compiler/types.ts
// @ts-ignore
if (typeof part.text === "string") {
// @ts-ignore
result += part.text;
continue;
}
if (typeof part.getText === "function") {
result += part.getText();
}
}
return result;
}
/**
* Split documentation text into lines suitable for DocC rendering.
* @param {string} text
* @returns {string[]}
* @private
*/
splitDocumentationText(text) {
if (!text) return [];
return text.split(/\r?\n/).map(line => line.trimEnd());
}
/**
* @param {string[]} lines
* @returns {boolean}
* @private
*/
hasMeaningfulLine(lines) {
return lines.some(line => line.trim().length > 0);
}
/**
* Render Swift doc comments from a node's JSDoc, including parameter/return tags.
* @param {ts.Node} node
* @param {{ indent?: string, parameterNameMap?: Map<string, string> }} options
* @private
*/
emitDocComment(node, options = {}) {
const indent = options.indent ?? "";
const parameterNameMap = options.parameterNameMap ?? new Map();
/** @type {string[]} */
const descriptionLines = [];
for (const doc of ts.getJSDocCommentsAndTags(node)) {
if (!ts.isJSDoc(doc)) continue;
const text = this.renderJSDocText(doc.comment);
if (text) {
descriptionLines.push(...this.splitDocumentationText(text));
}
}
/** @type {Array<{ name: string, lines: string[] }>} */
const parameterDocs = [];
const supportsParameters = (
ts.isFunctionLike(node) ||
ts.isMethodSignature(node) ||
ts.isCallSignatureDeclaration(node) ||
ts.isConstructSignatureDeclaration(node)
);
/** @type {ts.JSDocReturnTag | undefined} */
let returnTag = undefined;
if (supportsParameters) {
for (const tag of ts.getJSDocTags(node)) {
if (ts.isJSDocParameterTag(tag)) {
const tsName = tag.name.getText();
const name = parameterNameMap.get(tsName) ?? this.renderIdentifier(tsName);
const text = this.renderJSDocText(tag.comment);
const lines = this.splitDocumentationText(text);
parameterDocs.push({ name, lines });
} else if (!returnTag && ts.isJSDocReturnTag(tag)) {
returnTag = tag;
}
}
}
const returnLines = returnTag ? this.splitDocumentationText(this.renderJSDocText(returnTag.comment)) : [];
const hasDescription = this.hasMeaningfulLine(descriptionLines);
const hasParameters = parameterDocs.length > 0;
const hasReturns = returnTag !== undefined;
if (!hasDescription && !hasParameters && !hasReturns) {
return;
}
/** @type {string[]} */
const docLines = [];
if (hasDescription) {
docLines.push(...descriptionLines);
}
if (hasDescription && (hasParameters || hasReturns)) {
docLines.push("");
}
if (hasParameters) {
docLines.push("- Parameters:");
for (const param of parameterDocs) {
const hasParamDescription = this.hasMeaningfulLine(param.lines);
const [firstParamLine, ...restParamLines] = param.lines;
if (hasParamDescription) {
docLines.push(` - ${param.name}: ${firstParamLine}`);
for (const line of restParamLines) {
docLines.push(` ${line}`);
}
} else {
docLines.push(` - ${param.name}:`);
}
}
}
if (hasReturns) {
const hasReturnDescription = this.hasMeaningfulLine(returnLines);
const [firstReturnLine, ...restReturnLines] = returnLines;
if (hasReturnDescription) {
docLines.push(`- Returns: ${firstReturnLine}`);
for (const line of restReturnLines) {
docLines.push(` ${line}`);
}
} else {
docLines.push("- Returns:");
}
}
const prefix = `${indent}///`;
for (const line of docLines) {
if (line.length === 0) {
this.swiftLines.push(prefix);
} else {
this.swiftLines.push(`${prefix} ${line}`);
}
}
}
/**
* Build a map from TypeScript parameter names to rendered Swift identifiers.
* @param {ts.Symbol[]} parameters
* @returns {Map<string, string>}
* @private
*/
buildParameterNameMap(parameters) {
const map = new Map();
for (const parameter of parameters) {
map.set(parameter.name, this.renderIdentifier(parameter.name));
}
return map;
}
/** @returns {string} */
renderDefaultJSImportFromArgument() {
if (this.defaultImportFromGlobal) return "from: .global";
return "";
}
/**
* Visit a property declaration and extract metadata
* @param {ts.PropertyDeclaration | ts.PropertySignature} node
* @returns {{ jsName: string, swiftName: string, type: string, isReadonly: boolean, isStatic: boolean } | null}
*/
visitPropertyDecl(node) {
if (!node.name) return null;
/** @type {string | null} */
let jsName = null;
if (ts.isIdentifier(node.name)) {
jsName = node.name.text;
} else if (ts.isStringLiteral(node.name) || ts.isNumericLiteral(node.name)) {
jsName = node.name.text;
} else {
// Computed property names like `[Symbol.iterator]` are not supported yet.
return null;
}
const swiftName = isValidSwiftDeclName(jsName) ? jsName : makeValidSwiftIdentifier(jsName, { emptyFallback: "_" });
const type = this.checker.getTypeAtLocation(node)
const swiftType = this.visitType(type, node);
const isReadonly = node.modifiers?.some(m => m.kind === ts.SyntaxKind.ReadonlyKeyword) ?? false;
const isStatic = node.modifiers?.some(m => m.kind === ts.SyntaxKind.StaticKeyword) ?? false;
return { jsName, swiftName, type: swiftType, isReadonly, isStatic };
}
/**
* @param {ts.Symbol} symbol
* @param {ts.Node} node
* @returns {Parameter}
*/
visitSignatureParameter(symbol, node) {
const type = this.checker.getTypeOfSymbolAtLocation(symbol, node);
const swiftType = this.visitType(type, node);
return { name: symbol.name, type: swiftType };
}
/**
* Visit a class declaration and render Swift code
* @param {ts.ClassDeclaration} node
* @private
*/
visitClassDecl(node) {
if (!node.name) return;
const jsName = node.name.text;
if (this.emittedStructuredTypeNames.has(jsName)) return;
this.emittedStructuredTypeNames.add(jsName);
const swiftName = this.swiftTypeName(jsName);
const fromArg = this.renderDefaultJSImportFromArgument();
/** @type {string[]} */
const args = [];
const jsNameArg = this.renderOptionalJSNameArg(jsName, swiftName);
if (jsNameArg) args.push(jsNameArg);
if (fromArg) args.push(fromArg);
const annotation = this.renderMacroAnnotation("JSClass", args);
const className = this.renderIdentifier(swiftName);
this.emitDocComment(node, { indent: "" });
this.swiftLines.push(`${annotation} struct ${className} {`);
// Process members in declaration order
for (const member of node.members) {
if (ts.isPropertyDeclaration(member)) {
this.renderProperty(member);
} else if (ts.isMethodDeclaration(member)) {
this.renderMethod(member);
} else if (ts.isConstructorDeclaration(member)) {
this.renderConstructor(member);
}
}
this.swiftLines.push("}");
this.swiftLines.push("");
}
/**
* @param {ts.SymbolFlags} flags
* @returns {string[]}
*/
debugSymbolFlags(flags) {
const result = [];
for (const key in ts.SymbolFlags) {
const val = (ts.SymbolFlags)[key];
if (typeof val === "number" && (flags & val) !== 0) {
result.push(key);
}
}
return result;
}
/**
* @param {ts.TypeFlags} flags
* @returns {string[]}
*/
debugTypeFlags(flags) {
const result = [];
for (const key in ts.TypeFlags) {
const val = (ts.TypeFlags)[key];
if (typeof val === "number" && (flags & val) !== 0) {
result.push(key);
}
}
return result;
}
/**
* Visit a structured type (interface) and render Swift code
* @param {ts.Type} type
* @param {ts.Node} diagnosticNode
* @param {ts.Symbol[]} members
* @private
*/
visitStructuredType(type, diagnosticNode, members) {
const symbol = type.aliasSymbol ?? type.getSymbol();
const name = type.aliasSymbol?.name ?? symbol?.name ?? this.checker.typeToString(type);
if (!name) return;
if (this.emittedStructuredTypeNames.has(name)) return;
this.emittedStructuredTypeNames.add(name);
const swiftName = this.swiftTypeName(name);
/** @type {string[]} */
const args = [];
const jsNameArg = this.renderOptionalJSNameArg(name, swiftName);
if (jsNameArg) args.push(jsNameArg);
const annotation = this.renderMacroAnnotation("JSClass", args);
const typeName = this.renderIdentifier(swiftName);
const docNode = type.aliasSymbol?.getDeclarations()?.[0] ?? symbol?.getDeclarations()?.[0] ?? diagnosticNode;
if (docNode) {
this.emitDocComment(docNode, { indent: "" });
}
this.swiftLines.push(`${annotation} struct ${typeName} {`);
// Collect all declarations with their positions to preserve order
/** @type {Array<{ decl: ts.Node, symbol: ts.Symbol, position: number }>} */
const allDecls = [];
const typeMembers = members ?? type.getProperties() ?? [];
for (const memberSymbol of typeMembers) {
for (const decl of memberSymbol.getDeclarations() ?? []) {
const sourceFile = decl.getSourceFile();
const pos = sourceFile ? decl.getStart() : 0;
allDecls.push({ decl, symbol: memberSymbol, position: pos });
}
}
// Sort by position to preserve declaration order
allDecls.sort((a, b) => a.position - b.position);
// Process declarations in order
for (const { decl, symbol } of allDecls) {
if (symbol.flags & ts.SymbolFlags.Property) {
if (ts.isPropertyDeclaration(decl) || ts.isPropertySignature(decl)) {
this.renderProperty(decl);
} else if (ts.isMethodSignature(decl)) {
this.renderMethodSignature(decl);
}
} else if (symbol.flags & ts.SymbolFlags.Method) {
if (ts.isMethodSignature(decl)) {
this.renderMethodSignature(decl);
}
} else if (symbol.flags & ts.SymbolFlags.Constructor) {
if (ts.isConstructorDeclaration(decl)) {
this.renderConstructor(decl);
}
}
}
this.swiftLines.push("}");
this.swiftLines.push("");
}
/**
* Convert TypeScript type to Swift type string
* @param {ts.Type} type - TypeScript type
* @param {ts.Node} node - Node
* @returns {string} Swift type string
* @private
*/
visitType(type, node) {
const typeArguments = this.getTypeArguments(type);
if (this.checker.isArrayType(type)) {
const typeArgs = this.checker.getTypeArguments(/** @type {ts.TypeReference} */ (type));
if (typeArgs && typeArgs.length > 0) {
const elementType = this.visitType(typeArgs[0], node);
return `[${elementType}]`;
}
return "[JSObject]";
}
const recordType = this.convertRecordType(type, typeArguments, node);
if (recordType) {
return recordType;
}
// Treat A<B> and A<C> as the same type
if (isTypeReference(type)) {
type = type.target;
}
const maybeProcessed = this.processedTypes.get(type);
if (maybeProcessed) {
return maybeProcessed;
}
/**
* @param {ts.Type} type
* @returns {string}
*/
const convert = (type) => {
// Handle nullable/undefined unions (e.g. T | null, T | undefined)
const isUnionType = (type.flags & ts.TypeFlags.Union) !== 0;
if (isUnionType) {
/** @type {ts.UnionType} */
// @ts-ignore
const unionType = type;
const unionTypes = unionType.types;
const hasNull = unionTypes.some(t => (t.flags & ts.TypeFlags.Null) !== 0);
const hasUndefined = unionTypes.some(t => (t.flags & ts.TypeFlags.Undefined) !== 0);
const nonNullableTypes = unionTypes.filter(
t => (t.flags & ts.TypeFlags.Null) === 0 && (t.flags & ts.TypeFlags.Undefined) === 0
);
if (nonNullableTypes.length === 1 && (hasNull || hasUndefined)) {
const wrapped = this.visitType(nonNullableTypes[0], node);
if (hasNull && hasUndefined) {
return "JSObject";
}
if (hasNull) {
return `Optional<${wrapped}>`;
}
return `JSUndefinedOr<${wrapped}>`;
}
}
/** @type {Record<string, string>} */
const typeMap = {
"number": "Double",
"string": "String",
"boolean": "Bool",
"void": "Void",
"any": "JSValue",
"unknown": "JSValue",
"null": "Void",
"undefined": "Void",
"bigint": "Int",
"object": "JSObject",
"symbol": "JSObject",
"never": "Void",
"Promise": "JSPromise",
};
const symbol = type.getSymbol() ?? type.aliasSymbol;
const typeString = symbol?.name ?? this.checker.typeToString(type);
if (typeMap[typeString]) {
return typeMap[typeString];
}
if (symbol && (symbol.flags & ts.SymbolFlags.Enum) !== 0) {
const typeName = symbol.name;
this.seenTypes.set(type, node);
return this.renderTypeIdentifier(typeName);
}
if (this.checker.isTupleType(type) || type.getCallSignatures().length > 0) {
return "JSObject";
}
// "a" | "b" -> string
if (this.checker.isTypeAssignableTo(type, this.checker.getStringType())) {
return "String";
}
if (type.isTypeParameter()) {
return "JSObject";
}
const typeName = this.deriveTypeName(type);
if (!typeName) {
this.diagnosticEngine.print("warning", `Unknown non-nominal type: ${typeString}`, node);
return "JSObject";
}
this.seenTypes.set(type, node);
return this.renderTypeIdentifier(typeName);
}
const swiftType = convert(type);
this.processedTypes.set(type, swiftType);
return swiftType;
}
/**
* Convert a `Record<string, T>` TypeScript type into a Swift dictionary type.
* Falls back to `JSObject` when keys are not string-compatible or type arguments are missing.
* @param {ts.Type} type
* @param {readonly ts.Type[]} typeArguments
* @param {ts.Node} node
* @returns {string | null}
* @private
*/
convertRecordType(type, typeArguments, node) {
const symbol = type.aliasSymbol ?? type.getSymbol();
if (!symbol || symbol.name !== "Record") {
return null;
}
if (typeArguments.length !== 2) {
this.diagnosticEngine.print("warning", "Record expects two type arguments", node);
return "JSObject";
}
const [keyType, valueType] = typeArguments;
const stringType = this.checker.getStringType();
if (!this.checker.isTypeAssignableTo(keyType, stringType)) {
this.diagnosticEngine.print(
"warning",
`Record key type must be assignable to string: ${this.checker.typeToString(keyType)}`,
node
);
return "JSObject";
}
const valueSwiftType = this.visitType(valueType, node);
return `[String: ${valueSwiftType}]`;
}
/**
* Retrieve type arguments for a given type, including type alias instantiations.
* @param {ts.Type} type
* @returns {readonly ts.Type[]}
* @private
*/
getTypeArguments(type) {
if (isTypeReference(type)) {
return this.checker.getTypeArguments(type);
}
// Non-TypeReference alias instantiations store type arguments separately.
// @ts-ignore: `aliasTypeArguments` is intentionally accessed for alias instantiations.
return type.aliasTypeArguments ?? [];
}
/**
* Derive the type name from a type
* @param {ts.Type} type - TypeScript type
* @returns {string | undefined} Type name
* @private
*/
deriveTypeName(type) {
const aliasSymbol = type.aliasSymbol;
if (aliasSymbol) {
return aliasSymbol.name;
}
const typeSymbol = type.getSymbol();
if (typeSymbol) {
return typeSymbol.name;
}
return undefined;
}
/**
* Render a property declaration
* @param {ts.PropertyDeclaration | ts.PropertySignature} node
* @private
*/
renderProperty(node) {
const property = this.visitPropertyDecl(node);
if (!property) return;
const type = property.type;
const swiftName = this.renderIdentifier(property.swiftName);
const isStatic = property.isStatic;
const needsJSGetterName = property.jsName !== property.swiftName;
// Note: `from: .global` is only meaningful for top-level imports and constructors.
// Instance member access always comes from the JS object itself.