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
|
import WIT
/// A type responsible for lifting a core value representation of WasmKit to a Swift value
struct HostStaticCanonicalLifting: StaticCanonicalLifting {
typealias Operand = StaticMetaOperand
typealias Pointer = StaticMetaPointer
let printer: SourcePrinter
let builder: SwiftFunctionBuilder
let context: StaticMetaCanonicalCallContext
let definitionMapping: DefinitionMapping
func liftUInt(_ value: Operand, bitWidth: Int) -> Operand {
.call("UInt\(bitWidth)", arguments: [value])
}
func liftInt(_ value: Operand, bitWidth: Int) -> Operand {
let sourceBiWidth = bitWidth == 64 ? 64 : 32
return .call(
"Int\(bitWidth)",
arguments: [
.call("Int\(sourceBiWidth)", arguments: [("bitPattern", value)])
])
}
func liftPointer(_ value: Operand, pointeeTypeName: String) -> Operand {
return .call(
"UnsafeGuestPointer<\(pointeeTypeName)>",
arguments: [
("memorySpace", .accessField(.variable(context.contextVar), name: "guestMemory")),
("offset", value),
])
}
func liftBufferPointer(_ value: Operand, length: Operand) -> Operand {
.call(
"UnsafeGuestBufferPointer",
arguments: [
("baseAddress", value), ("count", length),
])
}
func liftList(
pointer: Operand, length: Operand,
element: WITType, loadElement: (Pointer) throws -> Operand
) throws -> Operand {
let loadElementVar = builder.variable("loadElement")
try printer.write(line: "let \(loadElementVar): (UnsafeGuestRawPointer) throws -> \(element.qualifiedSwiftName(mapping: definitionMapping)) = {")
try printer.indent {
// NOTE: `loadElement` can print statements
let loaded = try loadElement(.init(basePointerVar: "$0", offset: 0))
printer.write(line: "return \(loaded)")
}
printer.write(line: "}")
return .call(
"try CanonicalLifting.liftList",
arguments: [
("pointer", pointer),
("length", length),
("elementSize", .literal(CanonicalABI.size(type: element).description)),
("loadElement", .variable(loadElementVar)),
("context", .variable(context.contextVar)),
])
}
}
/// A type responsible for lowering a Swift value to a core value representation of WasmKit
struct HostStaticCanonicalLowering: StaticCanonicalLowering {
typealias Operand = StaticMetaOperand
typealias Pointer = StaticMetaPointer
let printer: SourcePrinter
let builder: SwiftFunctionBuilder
let context: StaticMetaCanonicalCallContext
let definitionMapping: DefinitionMapping
func lowerString(_ value: Operand, encoding: String) throws -> (pointer: Operand, length: Operand) {
let lowered = Operand.call(
"try CanonicalLowering.lowerString",
arguments: [
(nil, value), ("context", .variable(context.contextVar)),
])
let loweredVar = StaticMetaOperand.variable(builder.variable("stringLowered"))
printer.write(line: "let \(loweredVar) = \(lowered)")
return (
lowerUInt32(.accessField(loweredVar, name: "pointer")),
lowerUInt32(.accessField(loweredVar, name: "length"))
)
}
func lowerList(
_ value: Operand, element: WIT.WITType,
storeElement: (Pointer, Operand) throws -> Void
) throws -> (pointer: Operand, length: Operand) {
let storeElementVar = builder.variable("storeElement")
try printer.write(line: "let \(storeElementVar): (\(element.qualifiedSwiftName(mapping: definitionMapping)), UnsafeGuestRawPointer) throws -> Void = {")
try printer.indent {
try storeElement(Pointer(basePointerVar: "$1", offset: 0), .variable("$0"))
}
printer.write(line: "}")
let lowered = Operand.call(
"try CanonicalLowering.lowerList",
arguments: [
(nil, value),
("elementSize", .literal(CanonicalABI.size(type: element).description)),
("elementAlignment", .literal(CanonicalABI.alignment(type: element).description)),
("storeElement", .variable(storeElementVar)),
("context", .variable(context.contextVar)),
])
let loweredVar = StaticMetaOperand.variable(builder.variable("listLowered"))
printer.write(line: "let \(loweredVar) = \(lowered)")
return (
lowerUInt32(.accessField(loweredVar, name: "pointer")),
lowerUInt32(.accessField(loweredVar, name: "length"))
)
}
}
/// A type representing a function that wraps an exported function from a WebAssembly module
/// callable from host environment.
struct HostExportFunction {
let function: FunctionSyntax
let name: CanonicalFunctionName
let signatureTranslation: SignatureTranslation
let builder = SwiftFunctionBuilder()
let context: StaticMetaCanonicalCallContext
let definitionMapping: DefinitionMapping
init(
function: FunctionSyntax,
name: CanonicalFunctionName,
signatureTranslation: SignatureTranslation,
definitionMapping: DefinitionMapping
) {
self.function = function
self.name = name
self.signatureTranslation = signatureTranslation
self.definitionMapping = definitionMapping
// Reserve variables used in the function
self.context = StaticMetaCanonicalCallContext(contextVar: builder.variable("context"))
}
private func printLowerArguments(
parameterNames: some Sequence<String>,
coreSignature: CanonicalABI.CoreSignature,
typeResolver: (TypeReprSyntax) throws -> WITType,
printer: SourcePrinter
) throws -> [StaticMetaOperand] {
// TODO: Support indirect parameters
var loweredArguments: [StaticMetaOperand] = []
var coreParameters = coreSignature.parameters.makeIterator()
var lowering = HostStaticCanonicalLowering(printer: printer, builder: builder, context: context, definitionMapping: definitionMapping)
var storing = StaticCanonicalStoring(printer: printer, builder: builder, definitionMapping: definitionMapping)
for (parameter, parameterName) in zip(function.parameters, parameterNames) {
let type = try typeResolver(parameter.type)
let loweredValues = try CanonicalABI.lower(
type: type, value: StaticMetaOperand.variable(parameterName), lowering: &lowering, storing: &storing
)
for lowered in loweredValues {
let loweredVar = builder.variable(parameterName + "Lowered")
guard let coreType = coreParameters.next() else {
fatalError("insufficient number of core types!?")
}
printer.write(line: "let \(loweredVar) = \(WasmKitSourcePrinter().printNewValue(lowered, type: coreType.type))")
loweredArguments.append(.variable(loweredVar))
}
}
return loweredArguments
}
private func printReturnIndirectResult(
call: String,
typeResolver: (TypeReprSyntax) throws -> WITType,
printer: SourcePrinter
) throws {
let resultPtrVar = builder.variable("resultPtr")
var loading = StaticCanonicalLoading(printer: printer, builder: builder)
printer.write(line: "let \(resultPtrVar) = \(call)[0].i32")
var lifting = HostStaticCanonicalLifting(
printer: printer, builder: builder, context: context,
definitionMapping: definitionMapping
)
let hostPointerVar = builder.variable("guestPointer")
printer.write(
line: "let \(hostPointerVar) = UnsafeGuestRawPointer(memorySpace: \(context.contextVar).guestMemory, offset: \(resultPtrVar))"
)
var loadedResults: [StaticMetaOperand] = []
for resultType in function.results.types {
let resolvedResultType = try typeResolver(resultType)
let loaded = try CanonicalABI.load(
loading: &loading, lifting: &lifting,
type: resolvedResultType, pointer: StaticMetaPointer(basePointerVar: hostPointerVar, offset: 0)
)
loadedResults.append(loaded)
}
printer.write(line: "return (\(loadedResults.map(\.description).joined(separator: ", ")))")
}
private func printReturnDirectResult(
call: String, coreSignature: CanonicalABI.CoreSignature,
typeResolver: (TypeReprSyntax) throws -> WITType,
printer: SourcePrinter
) throws {
let resultVar = builder.variable("result")
printer.write(line: "let \(resultVar) = \(call)")
if coreSignature.results.isEmpty {
// Suppress unused variable warning
printer.write(line: "_ = \(resultVar)")
}
var resultCoreValues: [StaticMetaOperand] = []
for (idx, result) in coreSignature.results.enumerated() {
let resultElementVar = builder.variable("resultElement")
printer.write(line: "let \(resultElementVar) = \(resultVar)[\(idx)].\(result.type)")
resultCoreValues.append(.variable(resultElementVar))
}
var resultCoreValuesIterator = resultCoreValues.makeIterator()
var liftedResults: [StaticMetaOperand] = []
var lifting = HostStaticCanonicalLifting(
printer: printer, builder: builder, context: context,
definitionMapping: definitionMapping
)
var loading = StaticCanonicalLoading(printer: printer, builder: builder)
for resultType in function.results.types {
let resolvedResultType = try typeResolver(resultType)
let lifted = try WIT.CanonicalABI.lift(
type: resolvedResultType, coreValues: &resultCoreValuesIterator,
lifting: &lifting, loading: &loading
)
liftedResults.append(lifted)
}
printer.write(line: "return (\(liftedResults.map(\.description).joined(separator: ", ")))")
}
/// Prints a Swift source code of the function
///
/// - Parameters:
/// - typeResolver: A function that resolves a WIT type from a type representation syntax
/// - printer: A printer to print the source code
func print(
typeResolver: (TypeReprSyntax) throws -> WITType,
printer: SourcePrinter
) throws {
let coreSignature = try CanonicalABI.flattenSignature(
function: function,
typeResolver: typeResolver
)
var signature = try signatureTranslation.signature(function: function, name: ConvertCase.camelCase(kebab: name.apiSwiftName))
let witParameters = signature.parameters.map(\.label)
signature.parameters.insert(("runtime", "Runtime"), at: 0)
signature.hasThrows = true
printer.write(line: signature.description + " {")
try printer.indent {
let optionsVar = builder.variable("options")
printer.write(line: "let \(optionsVar) = CanonicalOptions._derive(from: moduleInstance, exportName: \"\(name.abiName)\")")
printer.write(line: "let \(context.contextVar) = CanonicalCallContext(options: \(optionsVar), moduleInstance: moduleInstance, runtime: runtime)")
// Supress unused variable warning for "context"
printer.write(line: "_ = \(context.contextVar)")
let arguments = try printLowerArguments(
parameterNames: witParameters, coreSignature: coreSignature,
typeResolver: typeResolver, printer: printer
)
var call = "try runtime.invoke(moduleInstance, function: \"\(name.abiName)\""
if !arguments.isEmpty {
call += ", with: [\(arguments.map(\.description).joined(separator: ", "))]"
}
call += ")"
if coreSignature.isIndirectResult {
try printReturnIndirectResult(call: call, typeResolver: typeResolver, printer: printer)
} else {
try printReturnDirectResult(
call: call, coreSignature: coreSignature,
typeResolver: typeResolver, printer: printer)
}
}
printer.write(line: "}")
}
}
|