forked from swiftwasm/JavaScriptKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImportTS.swift
More file actions
484 lines (446 loc) · 20.2 KB
/
ImportTS.swift
File metadata and controls
484 lines (446 loc) · 20.2 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
import SwiftBasicFormat
import SwiftSyntax
import SwiftSyntaxBuilder
#if canImport(BridgeJSSkeleton)
import BridgeJSSkeleton
#endif
#if canImport(BridgeJSUtilities)
import BridgeJSUtilities
#endif
/// Imports TypeScript declarations and generates Swift bridge code
///
/// This struct processes TypeScript definition files (.d.ts) and generates:
/// 1. Swift code to call the JavaScript functions from Swift
/// 2. Skeleton files that define the structure of the imported APIs
///
/// The generated skeletons will be used by ``BridgeJSLink`` to generate
/// JavaScript glue code and TypeScript definitions.
public struct ImportTS {
public let progress: ProgressReporting
public private(set) var skeleton: ImportedModuleSkeleton
private var moduleName: String {
skeleton.moduleName
}
public init(progress: ProgressReporting, moduleName: String) {
self.progress = progress
self.skeleton = ImportedModuleSkeleton(moduleName: moduleName, children: [])
}
/// Adds a skeleton to the importer's state
public mutating func addSkeleton(_ skeleton: ImportedFileSkeleton) {
self.skeleton.children.append(skeleton)
}
/// Finalizes the import process and generates Swift code
public func finalize() throws -> String? {
var decls: [DeclSyntax] = []
for skeleton in self.skeleton.children {
for function in skeleton.functions {
let thunkDecls = try renderSwiftThunk(function, topLevelDecls: &decls)
decls.append(contentsOf: thunkDecls)
}
for type in skeleton.types {
let typeDecls = try renderSwiftType(type, topLevelDecls: &decls)
decls.append(contentsOf: typeDecls)
}
}
if decls.isEmpty {
// No declarations to import
return nil
}
let format = BasicFormat()
let allDecls: [DeclSyntax] = [Self.prelude] + decls
return allDecls.map { $0.formatted(using: format).description }.joined(separator: "\n\n")
}
class ImportedThunkBuilder {
let abiName: String
let moduleName: String
var body: [CodeBlockItemSyntax] = []
var abiParameterForwardings: [LabeledExprSyntax] = []
var abiParameterSignatures: [(name: String, type: WasmCoreType)] = []
var abiReturnType: WasmCoreType?
init(moduleName: String, abiName: String) {
self.moduleName = moduleName
self.abiName = abiName
}
func lowerParameter(param: Parameter) throws {
let loweringInfo = try param.type.loweringParameterInfo()
assert(
loweringInfo.loweredParameters.count == 1,
"For now, we require a single parameter to be lowered to a single Wasm core type"
)
let (_, type) = loweringInfo.loweredParameters[0]
abiParameterForwardings.append(
LabeledExprSyntax(
label: param.label,
expression: ExprSyntax("\(raw: param.name).bridgeJSLowerParameter()")
)
)
abiParameterSignatures.append((param.name, type))
}
func call(returnType: BridgeType) {
let call: ExprSyntax =
"\(raw: abiName)(\(raw: abiParameterForwardings.map { $0.description }.joined(separator: ", ")))"
if returnType == .void {
body.append("\(raw: call)")
} else {
body.append("let ret = \(raw: call)")
}
body.append("if let error = _swift_js_take_exception() { throw error }")
}
func liftReturnValue(returnType: BridgeType) throws {
let liftingInfo = try returnType.liftingReturnInfo()
abiReturnType = liftingInfo.valueToLift
if returnType == .void {
return
}
body.append("return \(raw: returnType.swiftType).bridgeJSLiftReturn(ret)")
}
func assignThis(returnType: BridgeType) {
guard case .jsObject = returnType else {
preconditionFailure("assignThis can only be called with a jsObject return type")
}
abiReturnType = .i32
body.append("self.jsObject = JSObject(id: UInt32(bitPattern: ret))")
}
func renderImportDecl() -> DeclSyntax {
let baseDecl = FunctionDeclSyntax(
funcKeyword: .keyword(.func).with(\.trailingTrivia, .space),
name: .identifier(abiName),
signature: FunctionSignatureSyntax(
parameterClause: FunctionParameterClauseSyntax(parametersBuilder: {
for param in abiParameterSignatures {
FunctionParameterSyntax(
firstName: .wildcardToken().with(\.trailingTrivia, .space),
secondName: .identifier(param.name),
type: IdentifierTypeSyntax(name: .identifier(param.type.swiftType))
)
}
}),
returnClause: ReturnClauseSyntax(
arrow: .arrowToken(),
type: IdentifierTypeSyntax(name: .identifier(abiReturnType.map { $0.swiftType } ?? "Void"))
)
)
)
var externDecl = baseDecl
externDecl.attributes = AttributeListSyntax(itemsBuilder: {
"@_extern(wasm, module: \"\(raw: moduleName)\", name: \"\(raw: abiName)\")"
}).with(\.trailingTrivia, .newline)
var stubDecl = baseDecl
stubDecl.body = CodeBlockSyntax {
"""
fatalError("Only available on WebAssembly")
"""
}
return """
#if arch(wasm32)
\(externDecl)
#else
\(stubDecl)
#endif
"""
}
func renderThunkDecl(name: String, parameters: [Parameter], returnType: BridgeType) -> DeclSyntax {
return DeclSyntax(
FunctionDeclSyntax(
name: .identifier(name.backtickIfNeeded()),
signature: FunctionSignatureSyntax(
parameterClause: FunctionParameterClauseSyntax(parametersBuilder: {
for param in parameters {
FunctionParameterSyntax(
firstName: .wildcardToken(),
secondName: .identifier(param.name),
colon: .colonToken(),
type: IdentifierTypeSyntax(name: .identifier(param.type.swiftType))
)
}
}),
effectSpecifiers: ImportTS.buildFunctionEffect(throws: true, async: false),
returnClause: ReturnClauseSyntax(
arrow: .arrowToken(),
type: IdentifierTypeSyntax(name: .identifier(returnType.swiftType))
)
),
body: CodeBlockSyntax {
self.renderImportDecl()
body
}
)
)
}
func renderConstructorDecl(parameters: [Parameter]) -> DeclSyntax {
return DeclSyntax(
InitializerDeclSyntax(
signature: FunctionSignatureSyntax(
parameterClause: FunctionParameterClauseSyntax(
parametersBuilder: {
for param in parameters {
FunctionParameterSyntax(
firstName: .wildcardToken(),
secondName: .identifier(param.name),
type: IdentifierTypeSyntax(name: .identifier(param.type.swiftType))
)
}
}
),
effectSpecifiers: ImportTS.buildFunctionEffect(throws: true, async: false)
),
bodyBuilder: {
self.renderImportDecl()
body
}
)
)
}
}
static let prelude: DeclSyntax = """
// 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(BridgeJS) import JavaScriptKit
"""
func renderSwiftThunk(
_ function: ImportedFunctionSkeleton,
topLevelDecls: inout [DeclSyntax]
) throws -> [DeclSyntax] {
let builder = ImportedThunkBuilder(moduleName: moduleName, abiName: function.abiName(context: nil))
for param in function.parameters {
try builder.lowerParameter(param: param)
}
builder.call(returnType: function.returnType)
try builder.liftReturnValue(returnType: function.returnType)
return [
builder.renderThunkDecl(
name: function.name,
parameters: function.parameters,
returnType: function.returnType
)
.with(\.leadingTrivia, Self.renderDocumentation(documentation: function.documentation))
]
}
func renderSwiftType(_ type: ImportedTypeSkeleton, topLevelDecls: inout [DeclSyntax]) throws -> [DeclSyntax] {
let name = type.name
func renderMethod(method: ImportedFunctionSkeleton) throws -> [DeclSyntax] {
let builder = ImportedThunkBuilder(moduleName: moduleName, abiName: method.abiName(context: type))
try builder.lowerParameter(param: Parameter(label: nil, name: "self", type: .jsObject(name)))
for param in method.parameters {
try builder.lowerParameter(param: param)
}
builder.call(returnType: method.returnType)
try builder.liftReturnValue(returnType: method.returnType)
return [
builder.renderThunkDecl(
name: method.name,
parameters: method.parameters,
returnType: method.returnType
)
.with(\.leadingTrivia, Self.renderDocumentation(documentation: method.documentation))
]
}
func renderConstructorDecl(constructor: ImportedConstructorSkeleton) throws -> [DeclSyntax] {
let builder = ImportedThunkBuilder(moduleName: moduleName, abiName: constructor.abiName(context: type))
for param in constructor.parameters {
try builder.lowerParameter(param: param)
}
builder.call(returnType: .jsObject(name))
builder.assignThis(returnType: .jsObject(name))
return [
builder.renderConstructorDecl(parameters: constructor.parameters)
]
}
func renderGetterDecl(property: ImportedPropertySkeleton) throws -> AccessorDeclSyntax {
let builder = ImportedThunkBuilder(
moduleName: moduleName,
abiName: property.getterAbiName(context: type)
)
try builder.lowerParameter(param: Parameter(label: nil, name: "self", type: .jsObject(name)))
builder.call(returnType: property.type)
try builder.liftReturnValue(returnType: property.type)
return AccessorDeclSyntax(
accessorSpecifier: .keyword(.get),
effectSpecifiers: Self.buildAccessorEffect(throws: true, async: false),
body: CodeBlockSyntax {
builder.renderImportDecl()
builder.body
}
)
}
func renderSetterDecl(property: ImportedPropertySkeleton) throws -> DeclSyntax {
let builder = ImportedThunkBuilder(
moduleName: moduleName,
abiName: property.setterAbiName(context: type)
)
let newValue = Parameter(label: nil, name: "newValue", type: property.type)
try builder.lowerParameter(param: Parameter(label: nil, name: "self", type: .jsObject(name)))
try builder.lowerParameter(param: newValue)
builder.call(returnType: .void)
return builder.renderThunkDecl(
name: "set\(property.name.capitalizedFirstLetter)",
parameters: [newValue],
returnType: .void
)
}
func renderPropertyDecl(property: ImportedPropertySkeleton) throws -> [DeclSyntax] {
let accessorDecls: [AccessorDeclSyntax] = [try renderGetterDecl(property: property)]
var decls: [DeclSyntax] = [
DeclSyntax(
VariableDeclSyntax(
leadingTrivia: Self.renderDocumentation(documentation: property.documentation),
bindingSpecifier: .keyword(.var),
bindingsBuilder: {
PatternBindingListSyntax {
PatternBindingSyntax(
pattern: IdentifierPatternSyntax(
identifier: .identifier(property.name.backtickIfNeeded())
),
typeAnnotation: TypeAnnotationSyntax(
type: IdentifierTypeSyntax(name: .identifier(property.type.swiftType))
),
accessorBlock: AccessorBlockSyntax(
accessors: .accessors(
AccessorDeclListSyntax(accessorDecls)
)
)
)
}
}
)
)
]
if !property.isReadonly {
decls.append(try renderSetterDecl(property: property))
}
return decls
}
let classDecl = try StructDeclSyntax(
leadingTrivia: Self.renderDocumentation(documentation: type.documentation),
name: .identifier(name),
inheritanceClause: InheritanceClauseSyntax(
inheritedTypesBuilder: {
InheritedTypeSyntax(type: TypeSyntax("_JSBridgedClass"))
}
),
memberBlockBuilder: {
DeclSyntax(
"""
let jsObject: JSObject
"""
).with(\.trailingTrivia, .newlines(2))
DeclSyntax(
"""
init(unsafelyWrapping jsObject: JSObject) {
self.jsObject = jsObject
}
"""
).with(\.trailingTrivia, .newlines(2))
if let constructor = type.constructor {
try renderConstructorDecl(constructor: constructor).map { $0.with(\.trailingTrivia, .newlines(2)) }
}
for property in type.properties {
try renderPropertyDecl(property: property).map { $0.with(\.trailingTrivia, .newlines(2)) }
}
for method in type.methods {
try renderMethod(method: method).map { $0.with(\.trailingTrivia, .newlines(2)) }
}
}
)
return [DeclSyntax(classDecl)]
}
static func renderDocumentation(documentation: String?) -> Trivia {
guard let documentation = documentation else {
return Trivia()
}
let lines = documentation.split { $0.isNewline }
return Trivia(pieces: lines.flatMap { [TriviaPiece.docLineComment("/// \($0)"), .newlines(1)] })
}
static func buildFunctionEffect(throws: Bool, async: Bool) -> FunctionEffectSpecifiersSyntax {
return FunctionEffectSpecifiersSyntax(
asyncSpecifier: `async` ? .keyword(.async) : nil,
throwsClause: `throws`
? ThrowsClauseSyntax(
throwsSpecifier: .keyword(.throws),
leftParen: .leftParenToken(),
type: IdentifierTypeSyntax(name: .identifier("JSException")),
rightParen: .rightParenToken()
) : nil
)
}
static func buildAccessorEffect(throws: Bool, async: Bool) -> AccessorEffectSpecifiersSyntax {
return AccessorEffectSpecifiersSyntax(
asyncSpecifier: `async` ? .keyword(.async) : nil,
throwsClause: `throws`
? ThrowsClauseSyntax(
throwsSpecifier: .keyword(.throws),
leftParen: .leftParenToken(),
type: IdentifierTypeSyntax(name: .identifier("JSException")),
rightParen: .rightParenToken()
) : nil
)
}
}
extension BridgeType {
struct LoweringParameterInfo {
let loweredParameters: [(name: String, type: WasmCoreType)]
static let bool = LoweringParameterInfo(loweredParameters: [("value", .i32)])
static let int = LoweringParameterInfo(loweredParameters: [("value", .i32)])
static let float = LoweringParameterInfo(loweredParameters: [("value", .f32)])
static let double = LoweringParameterInfo(loweredParameters: [("value", .f64)])
static let string = LoweringParameterInfo(loweredParameters: [("value", .i32)])
static let jsObject = LoweringParameterInfo(loweredParameters: [("value", .i32)])
static let void = LoweringParameterInfo(loweredParameters: [])
}
func loweringParameterInfo() throws -> LoweringParameterInfo {
switch self {
case .bool: return .bool
case .int: return .int
case .float: return .float
case .double: return .double
case .string: return .string
case .jsObject: return .jsObject
case .void: return .void
case .swiftHeapObject:
throw BridgeJSCoreError("swiftHeapObject is not supported in imported signatures")
case .swiftProtocol:
throw BridgeJSCoreError("swiftProtocol is not supported in imported signatures")
case .caseEnum, .rawValueEnum, .associatedValueEnum, .namespaceEnum:
throw BridgeJSCoreError("Enum types are not yet supported in TypeScript imports")
case .optional:
throw BridgeJSCoreError("Optional types are not yet supported in TypeScript imports")
}
}
struct LiftingReturnInfo {
let valueToLift: WasmCoreType?
static let bool = LiftingReturnInfo(valueToLift: .i32)
static let int = LiftingReturnInfo(valueToLift: .i32)
static let float = LiftingReturnInfo(valueToLift: .f32)
static let double = LiftingReturnInfo(valueToLift: .f64)
static let string = LiftingReturnInfo(valueToLift: .i32)
static let jsObject = LiftingReturnInfo(valueToLift: .i32)
static let void = LiftingReturnInfo(valueToLift: nil)
}
func liftingReturnInfo() throws -> LiftingReturnInfo {
switch self {
case .bool: return .bool
case .int: return .int
case .float: return .float
case .double: return .double
case .string: return .string
case .jsObject: return .jsObject
case .void: return .void
case .swiftHeapObject:
throw BridgeJSCoreError("swiftHeapObject is not supported in imported signatures")
case .swiftProtocol:
throw BridgeJSCoreError("swiftProtocol is not supported in imported signatures")
case .caseEnum, .rawValueEnum, .associatedValueEnum, .namespaceEnum:
throw BridgeJSCoreError("Enum types are not yet supported in TypeScript imports")
case .optional:
throw BridgeJSCoreError("Optional types are not yet supported in TypeScript imports")
}
}
}
extension String {
func backtickIfNeeded() -> String {
return self.isValidSwiftIdentifier(for: .variableName) ? self : "`\(self)`"
}
}