forked from swiftwasm/JavaScriptKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClosureCodegen.swift
More file actions
186 lines (157 loc) · 7.99 KB
/
ClosureCodegen.swift
File metadata and controls
186 lines (157 loc) · 7.99 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
import SwiftBasicFormat
import SwiftSyntax
import SwiftSyntaxBuilder
#if canImport(BridgeJSSkeleton)
import BridgeJSSkeleton
#endif
#if canImport(BridgeJSUtilities)
import BridgeJSUtilities
#endif
public struct ClosureCodegen {
public init() {}
private func swiftClosureType(for signature: ClosureSignature) -> String {
let closureParams = signature.parameters.map { "\($0.swiftType)" }.joined(separator: ", ")
let swiftEffects = (signature.isAsync ? " async" : "") + (signature.isThrows ? " throws" : "")
let swiftReturnType = signature.returnType.swiftType
return "(\(closureParams))\(swiftEffects) -> \(swiftReturnType)"
}
func renderClosureHelpers(_ signature: ClosureSignature) throws -> [DeclSyntax] {
let mangledName = signature.mangleName
let helperName = "_BJS_Closure_\(mangledName)"
let swiftClosureType = swiftClosureType(for: signature)
let externName = "invoke_js_callback_\(signature.moduleName)_\(mangledName)"
// Use CallJSEmission to generate the callback invocation
let builder = ImportTS.CallJSEmission(
moduleName: "bjs",
abiName: externName,
context: .exportSwift
)
// Lower the callback parameter
try builder.lowerParameter(param: Parameter(label: nil, name: "callback", type: .jsObject(nil)))
// Lower each closure parameter
for (index, paramType) in signature.parameters.enumerated() {
try builder.lowerParameter(param: Parameter(label: nil, name: "param\(index)", type: paramType))
}
// Generate the call and return value lifting
try builder.call(returnType: signature.returnType)
try builder.liftReturnValue(returnType: signature.returnType)
// Generate extern declaration using CallJSEmission
let externDecl = builder.renderImportDecl()
let makeClosureExternDecl: DeclSyntax = """
#if arch(wasm32)
@_extern(wasm, module: "bjs", name: "make_swift_closure_\(raw: signature.moduleName)_\(raw: signature.mangleName)")
fileprivate func make_swift_closure_\(raw: signature.moduleName)_\(raw: signature.mangleName)(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer<UInt8>, _ line: UInt32) -> Int32
#else
fileprivate func make_swift_closure_\(raw: signature.moduleName)_\(raw: signature.mangleName)(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer<UInt8>, _ line: UInt32) -> Int32 {
fatalError("Only available on WebAssembly")
}
#endif
"""
let helperEnumDeclPrinter = CodeFragmentPrinter()
helperEnumDeclPrinter.write("private enum \(helperName) {")
helperEnumDeclPrinter.indent {
helperEnumDeclPrinter.write("static func bridgeJSLift(_ callbackId: Int32) -> \(swiftClosureType) {")
helperEnumDeclPrinter.indent {
helperEnumDeclPrinter.write("let callback = JSObject.bridgeJSLiftParameter(callbackId)")
let parameters: String
if signature.parameters.isEmpty {
parameters = ""
} else if signature.parameters.count == 1 {
parameters = " param0"
} else {
parameters =
" ("
+ signature.parameters.enumerated().map { index, _ in
"param\(index)"
}.joined(separator: ", ") + ")"
}
helperEnumDeclPrinter.write("return { [callback]\(parameters) in")
helperEnumDeclPrinter.indent {
SwiftCodePattern.buildWasmConditionalCompilation(
printer: helperEnumDeclPrinter,
wasmBody: { printer in
printer.write(lines: builder.body.lines)
}
)
}
helperEnumDeclPrinter.write("}")
}
helperEnumDeclPrinter.write("}")
}
helperEnumDeclPrinter.write("}")
let helperEnumDecl: DeclSyntax = "\(raw: helperEnumDeclPrinter.lines.joined(separator: "\n"))"
let typedClosureExtension: DeclSyntax = """
extension JSTypedClosure where Signature == \(raw: swiftClosureType) {
init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping \(raw: swiftClosureType)) {
self.init(
makeClosure: make_swift_closure_\(raw: signature.moduleName)_\(raw: signature.mangleName),
body: body,
fileID: fileID,
line: line
)
}
}
"""
return [
externDecl, makeClosureExternDecl, helperEnumDecl, typedClosureExtension,
]
}
func renderClosureInvokeHandler(_ signature: ClosureSignature) throws -> DeclSyntax {
let swiftClosureType = swiftClosureType(for: signature)
let boxType = "_BridgeJSTypedClosureBox<\(swiftClosureType)>"
let abiName = "invoke_swift_closure_\(signature.moduleName)_\(signature.mangleName)"
// Build ABI parameters directly with WasmCoreType (no string conversion needed)
var abiParams: [(name: String, type: WasmCoreType)] = [("boxPtr", .pointer)]
var liftedParams: [String] = []
for (index, paramType) in signature.parameters.enumerated() {
let paramName = "param\(index)"
let liftInfo = try paramType.liftParameterInfo()
for (argName, wasmType) in liftInfo.parameters {
let fullName =
liftInfo.parameters.count > 1 ? "\(paramName)\(argName.capitalizedFirstLetter)" : paramName
abiParams.append((fullName, wasmType))
}
let argNames = liftInfo.parameters.map { (argName, _) in
liftInfo.parameters.count > 1 ? "\(paramName)\(argName.capitalizedFirstLetter)" : paramName
}
liftedParams.append("\(paramType.swiftType).bridgeJSLiftParameter(\(argNames.joined(separator: ", ")))")
}
let closureCallExpr = ExprSyntax("closure(\(raw: liftedParams.joined(separator: ", ")))")
let abiReturnWasmType = try signature.returnType.loweringReturnInfo().returnType
// Build signature using SwiftSignatureBuilder
let funcSignature = SwiftSignatureBuilder.buildABIFunctionSignature(
abiParameters: abiParams,
returnType: abiReturnWasmType
)
// Build function declaration using helper
let funcDecl = SwiftCodePattern.buildExposedFunctionDecl(
abiName: abiName,
signature: funcSignature
) { printer in
printer.write("let closure = Unmanaged<\(boxType)>.fromOpaque(boxPtr).takeUnretainedValue().closure")
if signature.returnType == .void {
printer.write(closureCallExpr.description)
} else {
printer.write("let result = \(closureCallExpr)")
printer.write("return result.bridgeJSLowerReturn()")
}
}
return DeclSyntax(funcDecl)
}
public func renderSupport(for skeleton: BridgeJSSkeleton) throws -> String? {
let collector = ClosureSignatureCollectorVisitor()
var walker = BridgeTypeWalker(visitor: collector)
walker.walk(skeleton)
let closureSignatures = walker.visitor.signatures
guard !closureSignatures.isEmpty else { return nil }
var decls: [DeclSyntax] = []
for signature in closureSignatures.sorted(by: { $0.mangleName < $1.mangleName }) {
decls.append(contentsOf: try renderClosureHelpers(signature))
decls.append(try renderClosureInvokeHandler(signature))
}
return withSpan("Format Closure Glue") {
let format = BasicFormat()
return decls.map { $0.formatted(using: format).description }.joined(separator: "\n\n")
}
}
}