forked from swiftwasm/JavaScriptKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocessor.js
More file actions
651 lines (579 loc) · 21.6 KB
/
processor.js
File metadata and controls
651 lines (579 loc) · 21.6 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
/**
* TypeScript type processing functionality
* @module processor
*/
// @ts-check
import ts from 'typescript';
/** @typedef {import('./index.d.ts').Parameter} Parameter */
/** @typedef {import('./index.d.ts').BridgeType} BridgeType */
/**
* @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} filePath - Path to the d.ts file
* @param {ts.CompilerOptions} options - Compiler options
* @returns {ts.Program} TypeScript program object
*/
static createProgram(filePath, options) {
const host = ts.createCompilerHost(options);
return ts.createProgram([filePath], options, host);
}
/**
* @param {ts.TypeChecker} checker - TypeScript type checker
* @param {DiagnosticEngine} diagnosticEngine - Diagnostic engine
*/
constructor(checker, diagnosticEngine, options = {
inheritIterable: true,
inheritArraylike: true,
inheritPromiselike: true,
addAllParentMembersToClass: true,
replaceAliasToFunction: true,
replaceRankNFunction: true,
replaceNewableFunction: true,
noExtendsInTyprm: false,
}) {
this.checker = checker;
this.diagnosticEngine = diagnosticEngine;
this.options = options;
/** @type {Map<ts.Type, BridgeType>} */
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.visitedDeclarationKeys = new Set();
}
/**
* 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
);
// Add prelude
this.swiftLines.push(
"// NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit,",
"// DO NOT EDIT.",
"//",
"// To update this file, just rebuild your project or run",
"// `swift package bridge-js`.",
"",
"@_spi(Experimental) import JavaScriptKit",
""
);
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);
const typeString = this.checker.typeToString(type);
const members = type.getProperties();
if (members) {
this.visitStructuredType(typeString, members);
}
}
});
} catch (error) {
this.diagnosticEngine.print("error", `Error processing ${sourceFile.fileName}: ${error.message}`);
}
}
const content = this.swiftLines.join("\n").trimEnd() + "\n";
const hasAny = this.swiftLines.length > 9; // More than just the prelude
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.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 a function declaration and render Swift code
* @param {ts.FunctionDeclaration} node - The function node
* @private
*/
visitFunctionDeclaration(node) {
if (!node.name) return;
const name = node.name.getText();
if (!isValidSwiftDeclName(name)) {
return;
}
const signature = this.checker.getSignatureFromDeclaration(node);
if (!signature) return;
const params = this.renderParameters(signature.getParameters(), node);
const returnType = this.renderBridgeType(this.visitType(signature.getReturnType(), node), node);
const effects = this.renderEffects({ isAsync: false });
const swiftName = this.renderIdentifier(name);
this.swiftLines.push(`@JSFunction func ${swiftName}(${params}) ${effects} -> ${returnType}`);
this.swiftLines.push("");
}
/**
* Get the full JSDoc text from a node
* @param {ts.Node} node - The node to get the JSDoc text from
* @returns {string | undefined} The full JSDoc text
*/
getFullJSDocText(node) {
const docs = ts.getJSDocCommentsAndTags(node);
const parts = [];
for (const doc of docs) {
if (ts.isJSDoc(doc)) {
parts.push(doc.comment ?? "");
}
}
if (parts.length === 0) return undefined;
return parts.join("\n");
}
/**
* Render constructor parameters
* @param {ts.ConstructorDeclaration} node
* @returns {string} Rendered parameters
* @private
*/
renderConstructorParameters(node) {
const signature = this.checker.getSignatureFromDeclaration(node);
if (!signature) return "";
return this.renderParameters(signature.getParameters(), node);
}
/**
* @param {ts.PropertyDeclaration | ts.PropertySignature} node
* @returns {{ name: string, type: BridgeType, isReadonly: boolean, documentation: string | undefined } | null}
*/
visitPropertyDecl(node) {
if (!node.name) return null;
const propertyName = node.name.getText();
if (!isValidSwiftDeclName(propertyName)) {
return null;
}
const type = this.checker.getTypeAtLocation(node)
const bridgeType = this.visitType(type, node);
const isReadonly = node.modifiers?.some(m => m.kind === ts.SyntaxKind.ReadonlyKeyword) ?? false;
const documentation = this.getFullJSDocText(node);
return { name: propertyName, type: bridgeType, isReadonly, documentation };
}
/**
* @param {ts.Symbol} symbol
* @param {ts.Node} node
* @returns {Parameter}
*/
visitSignatureParameter(symbol, node) {
const type = this.checker.getTypeOfSymbolAtLocation(symbol, node);
const bridgeType = this.visitType(type, node);
return { name: symbol.name, type: bridgeType };
}
/**
* Visit a class declaration and render Swift code
* @param {ts.ClassDeclaration} node
* @private
*/
visitClassDecl(node) {
if (!node.name) return;
const className = this.renderIdentifier(node.name.text);
this.swiftLines.push(`@JSClass 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 {string} name
* @param {ts.Symbol[]} members
* @private
*/
visitStructuredType(name, members) {
const typeName = this.renderIdentifier(name);
this.swiftLines.push(`@JSClass struct ${typeName} {`);
// Collect all declarations with their positions to preserve order
/** @type {Array<{ decl: ts.Node, symbol: ts.Symbol, position: number }>} */
const allDecls = [];
for (const symbol of members) {
for (const decl of symbol.getDeclarations() ?? []) {
const sourceFile = decl.getSourceFile();
const pos = sourceFile ? decl.getStart() : 0;
allDecls.push({ decl, symbol, 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 string to BridgeType
* @param {ts.Type} type - TypeScript type string
* @param {ts.Node} node - Node
* @returns {BridgeType} Bridge type
* @private
*/
visitType(type, node) {
// 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 {BridgeType}
*/
const convert = (type) => {
/** @type {Record<string, BridgeType>} */
const typeMap = {
"number": { "double": {} },
"string": { "string": {} },
"boolean": { "bool": {} },
"void": { "void": {} },
"any": { "jsObject": {} },
"unknown": { "jsObject": {} },
"null": { "void": {} },
"undefined": { "void": {} },
"bigint": { "int": {} },
"object": { "jsObject": {} },
"symbol": { "jsObject": {} },
"never": { "void": {} },
"Promise": {
"jsObject": {
"_0": "JSPromise"
}
},
};
const typeString = type.getSymbol()?.name ?? this.checker.typeToString(type);
if (typeMap[typeString]) {
return typeMap[typeString];
}
if (this.checker.isArrayType(type) || 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 { "jsObject": { "_0": typeName } };
}
const bridgeType = convert(type);
this.processedTypes.set(type, bridgeType);
return bridgeType;
}
/**
* 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 = this.renderBridgeType(property.type, node);
const name = this.renderIdentifier(property.name);
// Always render getter
this.swiftLines.push(` @JSGetter var ${name}: ${type}`);
// Render setter if not readonly
if (!property.isReadonly) {
const capitalizedName = property.name.charAt(0).toUpperCase() + property.name.slice(1);
const needsJSNameField = property.name.charAt(0) != capitalizedName.charAt(0).toLowerCase();
const setterName = `set${capitalizedName}`;
const annotation = needsJSNameField ? `@JSSetter(jsName: "${property.name}")` : "@JSSetter";
this.swiftLines.push(` ${annotation} func ${this.renderIdentifier(setterName)}(_ value: ${type}) ${this.renderEffects({ isAsync: false })}`);
}
}
/**
* Render a method declaration
* @param {ts.MethodDeclaration | ts.MethodSignature} node
* @private
*/
renderMethod(node) {
if (!node.name) return;
const name = node.name.getText();
if (!isValidSwiftDeclName(name)) return;
const signature = this.checker.getSignatureFromDeclaration(node);
if (!signature) return;
const params = this.renderParameters(signature.getParameters(), node);
const returnType = this.renderBridgeType(this.visitType(signature.getReturnType(), node), node);
const effects = this.renderEffects({ isAsync: false });
const swiftName = this.renderIdentifier(name);
this.swiftLines.push(` @JSFunction func ${swiftName}(${params}) ${effects} -> ${returnType}`);
}
/**
* Render a method signature (from interface)
* @param {ts.MethodSignature} node
* @private
*/
renderMethodSignature(node) {
this.renderMethod(node);
}
/**
* Render a constructor declaration
* @param {ts.ConstructorDeclaration} node
* @private
*/
renderConstructor(node) {
const params = this.renderConstructorParameters(node);
const effects = this.renderEffects({ isAsync: false });
this.swiftLines.push(` @JSFunction init(${params}) ${effects}`);
}
/**
* Render function parameters
* @param {ts.Symbol[]} parameters
* @param {ts.Node} node
* @returns {string}
* @private
*/
renderParameters(parameters, node) {
const params = [];
for (const p of parameters) {
const bridgeType = this.visitSignatureParameter(p, node);
const paramName = this.renderIdentifier(p.name);
const type = this.renderBridgeType(bridgeType.type, node);
params.push(`_ ${paramName}: ${type}`);
}
return params.join(", ");
}
/**
* Render bridge type to Swift type
* @param {BridgeType} bridgeType
* @param {ts.Node} node
* @returns {string}
* @private
*/
renderBridgeType(bridgeType, node) {
if ("int" in bridgeType) return "Int";
if ("float" in bridgeType) return "Float";
if ("double" in bridgeType) return "Double";
if ("string" in bridgeType) return "String";
if ("bool" in bridgeType) return "Bool";
if ("void" in bridgeType) return "Void";
if ("jsObject" in bridgeType) {
const name = "_0" in bridgeType.jsObject ? bridgeType.jsObject._0 : undefined;
return name ? this.renderIdentifier(name) : "JSObject";
}
return "JSObject";
}
/**
* Render effects (async/throws)
* @param {{ isAsync: boolean }} effects
* @returns {string}
* @private
*/
renderEffects(effects) {
const parts = [];
if (effects?.isAsync) {
parts.push("async");
}
parts.push("throws (JSException)");
return parts.join(" ");
}
/**
* Render identifier with backticks if needed
* @param {string} name
* @returns {string}
* @private
*/
renderIdentifier(name) {
if (!name) return name;
if (!isValidSwiftDeclName(name) || isSwiftKeyword(name)) {
return `\`${name}\``;
}
return name;
}
}
const SWIFT_KEYWORDS = new Set([
"associatedtype", "class", "deinit", "enum", "extension", "fileprivate",
"func", "import", "init", "inout", "internal", "let", "open", "operator",
"private", "protocol", "public", "static", "struct", "subscript", "typealias",
"var", "break", "case", "continue", "default", "defer", "do", "else",
"fallthrough", "for", "guard", "if", "in", "repeat", "return", "switch",
"where", "while", "as", "Any", "catch", "false", "is", "nil", "rethrows",
"super", "self", "Self", "throw", "throws", "true", "try",
"prefix", "postfix", "infix" // Contextual keywords for operator declarations
]);
/**
* @param {string} name
* @returns {boolean}
*/
function isSwiftKeyword(name) {
return SWIFT_KEYWORDS.has(name);
}
/**
* @param {ts.Type} type
* @returns {type is ts.ObjectType}
*/
function isObjectType(type) {
// @ts-ignore
return typeof type.objectFlags === "number";
}
/**
*
* @param {ts.Type} type
* @returns {type is ts.TypeReference}
*/
function isTypeReference(type) {
return (
isObjectType(type) &&
(type.objectFlags & ts.ObjectFlags.Reference) !== 0
);
}
/**
* Check if a declaration name is valid for Swift generation
* @param {string} name - Declaration name to check
* @returns {boolean} True if the name is valid for Swift
* @private
*/
export function isValidSwiftDeclName(name) {
// https://docs.swift.org/swift-book/documentation/the-swift-programming-language/lexicalstructure/
const swiftIdentifierRegex = /^[_\p{ID_Start}][\p{ID_Continue}\u{200C}\u{200D}]*$/u;
return swiftIdentifierRegex.test(name);
}