From d1e0f95a1ddee38a699889ba5ceb605e0ed4a6f8 Mon Sep 17 00:00:00 2001 From: Yuta Saito Date: Tue, 2 Jun 2026 01:51:05 +0900 Subject: [PATCH 01/50] Change Data.construct(from uint8Array:) return type from Data? to Data (#752) Make Data typed-array constructor non-optional --- Sources/JavaScriptFoundationCompat/Data+JSValue.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/JavaScriptFoundationCompat/Data+JSValue.swift b/Sources/JavaScriptFoundationCompat/Data+JSValue.swift index 6e74ba266..c4408d8cf 100644 --- a/Sources/JavaScriptFoundationCompat/Data+JSValue.swift +++ b/Sources/JavaScriptFoundationCompat/Data+JSValue.swift @@ -22,7 +22,7 @@ extension Data: ConvertibleToJSValue, ConstructibleFromJSValue { public var jsValue: JSValue { jsTypedArray.jsValue } /// Construct a Data from a JSTypedArray. - public static func construct(from uint8Array: JSTypedArray) -> Data? { + public static func construct(from uint8Array: JSTypedArray) -> Data { // First, allocate the data storage var data = Data(count: uint8Array.lengthInBytes) // Then, copy the byte contents into the Data buffer From 2941cd28fcda99a306188c19eedd8899ec175112 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Mon, 8 Jun 2026 14:08:54 +0200 Subject: [PATCH 02/50] BridgeJS: Support optional @JS struct in imported function signatures Optional @JS structs could not be used as parameters or return values of imported (@JSFunction) signatures: the generator lowered Optional using the non-optional object-id ABI ([isSome, objectId] / a single Int32 return), for which no Optional lowering exists, so the generated thunk did not compile. Bridge optional @JS structs through the stack ABI instead - an isSome discriminator plus the struct fields - exactly like optional arrays and dictionaries. Structs already conform to the stack-based bridging protocols, so the existing _BridgedAsOptional/stack runtime extensions and the JS link's stack handling already support this; only the import-side lowering/lifting in the code generator needed to change. Adds a jsRoundTripOptionalPoint runtime round-trip (some + none) and a SwiftStructImports codegen snapshot. --- .../Sources/BridgeJSCore/ImportTS.swift | 10 +++++- .../MacroSwift/SwiftStructImports.swift | 2 ++ .../SwiftStructImports.json | 34 +++++++++++++++++++ .../SwiftStructImports.swift | 21 ++++++++++++ .../BridgeJSLinkTests/SwiftStructImports.d.ts | 1 + .../BridgeJSLinkTests/SwiftStructImports.js | 19 +++++++++++ .../Generated/BridgeJS.swift | 21 ++++++++++++ .../Generated/JavaScript/BridgeJS.json | 34 +++++++++++++++++++ .../BridgeJSRuntimeTests/ImportAPITests.swift | 7 ++++ .../ImportStructAPIs.swift | 2 ++ Tests/prelude.mjs | 1 + 11 files changed, 151 insertions(+), 1 deletion(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift index d491c4058..8ce91b998 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift @@ -957,6 +957,10 @@ extension BridgeType { } case .namespaceEnum: throw BridgeJSCoreError("Namespace enums cannot be used as parameters") + case .nullable(.swiftStruct, _) where context == .importTS: + // Optional `@JS struct`s bridge through the stack (isSome discriminator + fields), + // like optional arrays/dictionaries, rather than the non-optional object-id ABI. + return LoweringParameterInfo(loweredParameters: [("isSome", .i32)]) case .nullable(let wrappedType, _): let wrappedInfo = try wrappedType.loweringParameterInfo(context: context) var params = [("isSome", WasmCoreType.i32)] @@ -1034,10 +1038,14 @@ extension BridgeType { case .namespaceEnum: throw BridgeJSCoreError("Namespace enums cannot be used as return values") case .nullable(let wrappedType, _): - // jsObject uses stack ABI for optionals — returns void, value goes through stacks + // jsObject and `@JS struct` use the stack ABI for optionals — the thunk returns + // void and the value (plus isSome discriminator) flows through the stacks. if case .jsObject = wrappedType { return LiftingReturnInfo(valueToLift: nil) } + if case .swiftStruct = wrappedType, context == .importTS { + return LiftingReturnInfo(valueToLift: nil) + } let wrappedInfo = try wrappedType.liftingReturnInfo(context: context) return LiftingReturnInfo(valueToLift: wrappedInfo.valueToLift) case .array, .dictionary: diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStructImports.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStructImports.swift index b00fd768a..a1eed686a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStructImports.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStructImports.swift @@ -5,3 +5,5 @@ struct Point { } @JSFunction func translate(_ point: Point, dx: Int, dy: Int) throws(JSException) -> Point + +@JSFunction func roundTripOptional(_ point: Point?) throws(JSException) -> Point? diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.json index fc59471bb..a9b0d22bf 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.json @@ -100,6 +100,40 @@ "_0" : "Point" } } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "roundTripOptional", + "parameters" : [ + { + "name" : "point", + "type" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "Point" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "Point" + } + }, + "_1" : "null" + } + } } ], "types" : [ diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.swift index fe79f786c..cec50ffca 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.swift @@ -67,4 +67,25 @@ func _$translate(_ point: Point, _ dx: Int, _ dy: Int) throws(JSException) -> Po throw error } return Point.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_roundTripOptional") +fileprivate func bjs_roundTripOptional_extern(_ point: Int32) -> Void +#else +fileprivate func bjs_roundTripOptional_extern(_ point: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_roundTripOptional(_ point: Int32) -> Void { + return bjs_roundTripOptional_extern(point) +} + +func _$roundTripOptional(_ point: Optional) throws(JSException) -> Optional { + let pointIsSome = point.bridgeJSLowerParameter() + bjs_roundTripOptional(pointIsSome) + if let error = _swift_js_take_exception() { + throw error + } + return Optional.bridgeJSLiftReturn() } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.d.ts index 3677f1e44..e97b50fda 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.d.ts @@ -12,6 +12,7 @@ export type Exports = { } export type Imports = { translate(point: Point, dx: number, dy: number): Point; + roundTripOptional(point: Point | null): Point | null; } export function createInstantiator(options: { imports: Imports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js index 0197aefe8..17bf086ff 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js @@ -226,6 +226,25 @@ export async function createInstantiator(options, swift) { setException(error); } } + TestModule["bjs_roundTripOptional"] = function bjs_roundTripOptional(point) { + try { + let optResult; + if (point) { + const struct = structHelpers.Point.lift(); + optResult = struct; + } else { + optResult = null; + } + let ret = imports.roundTripOptional(optResult); + const isSome = ret != null; + if (isSome) { + structHelpers.Point.lower(ret); + } + i32Stack.push(isSome ? 1 : 0); + } catch (error) { + setException(error); + } + } }, setInstance: (i) => { instance = i; diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 3fa4eb9d5..4a94431f2 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -13279,6 +13279,27 @@ func _$jsTranslatePoint(_ point: Point, _ dx: Int, _ dy: Int) throws(JSException return Point.bridgeJSLiftReturn(ret) } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripOptionalPoint") +fileprivate func bjs_jsRoundTripOptionalPoint_extern(_ point: Int32) -> Void +#else +fileprivate func bjs_jsRoundTripOptionalPoint_extern(_ point: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsRoundTripOptionalPoint(_ point: Int32) -> Void { + return bjs_jsRoundTripOptionalPoint_extern(point) +} + +func _$jsRoundTripOptionalPoint(_ point: Optional) throws(JSException) -> Optional { + let pointIsSome = point.bridgeJSLowerParameter() + bjs_jsRoundTripOptionalPoint(pointIsSome) + if let error = _swift_js_take_exception() { + throw error + } + return Optional.bridgeJSLiftReturn() +} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_IntegerTypesSupportImports_jsRoundTripInt_static") fileprivate func bjs_IntegerTypesSupportImports_jsRoundTripInt_static_extern(_ v: Int32) -> Int32 diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index 94142f470..9ea12bde7 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -19745,6 +19745,40 @@ "_0" : "Point" } } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsRoundTripOptionalPoint", + "parameters" : [ + { + "name" : "point", + "type" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "Point" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "Point" + } + }, + "_1" : "null" + } + } } ], "types" : [ diff --git a/Tests/BridgeJSRuntimeTests/ImportAPITests.swift b/Tests/BridgeJSRuntimeTests/ImportAPITests.swift index 8f02af2ef..38ff2a205 100644 --- a/Tests/BridgeJSRuntimeTests/ImportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ImportAPITests.swift @@ -59,6 +59,13 @@ class ImportAPITests: XCTestCase { } } + func testRoundTripOptionalStruct() throws { + let p = try jsRoundTripOptionalPoint(Point(x: 3, y: 4)) + XCTAssertEqual(p?.x, 3) + XCTAssertEqual(p?.y, 4) + XCTAssertNil(try jsRoundTripOptionalPoint(nil)) + } + func ensureThrows(_ f: (Bool) throws(JSException) -> T) throws { do { _ = try f(true) diff --git a/Tests/BridgeJSRuntimeTests/ImportStructAPIs.swift b/Tests/BridgeJSRuntimeTests/ImportStructAPIs.swift index 41929772e..f981a5e01 100644 --- a/Tests/BridgeJSRuntimeTests/ImportStructAPIs.swift +++ b/Tests/BridgeJSRuntimeTests/ImportStructAPIs.swift @@ -7,3 +7,5 @@ struct Point { } @JSFunction func jsTranslatePoint(_ point: Point, dx: Int, dy: Int) throws(JSException) -> Point + +@JSFunction func jsRoundTripOptionalPoint(_ point: Point?) throws(JSException) -> Point? diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index 2c922dbe2..f9e2f7727 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -141,6 +141,7 @@ export async function setupOptions(options, context) { jsTranslatePoint: (point, dx, dy) => { return { x: (point.x | 0) + (dx | 0), y: (point.y | 0) + (dy | 0) }; }, + jsRoundTripOptionalPoint: (point) => point, roundTripArrayMembers: (value) => { return value; }, From 7d3faa0db7f370da2f01d674270f5ce9d3ef38ba Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Mon, 8 Jun 2026 15:29:03 +0200 Subject: [PATCH 03/50] BridgeJS: Support case enums as imported function parameters and returns Case enums (enums without raw values or associated values) already bridged across the export boundary as their Int32 tag, but the TypeScript import path rejected them with "Enum types are not yet supported in TypeScript imports". The JS glue already round-trips the tag in both directions, so enable case enums as imported (@JSFunction) parameters and return values by lowering and lifting that Int32 tag in the import context, matching the export side. Adds a CaseEnumImports round-trip test and an EnumCaseImport codegen snapshot. --- .../Sources/BridgeJSCore/ImportTS.swift | 14 +- .../Inputs/MacroSwift/EnumCaseImport.swift | 12 + .../BridgeJSCodegenTests/EnumCaseImport.json | 139 ++++++++++ .../BridgeJSCodegenTests/EnumCaseImport.swift | 97 +++++++ .../BridgeJSLinkTests/EnumCaseImport.d.ts | 33 +++ .../BridgeJSLinkTests/EnumCaseImport.js | 251 ++++++++++++++++++ .../Generated/BridgeJS.swift | 60 +++++ .../Generated/JavaScript/BridgeJS.json | 63 +++++ .../BridgeJSRuntimeTests/ImportAPITests.swift | 14 + Tests/prelude.mjs | 3 + 10 files changed, 674 insertions(+), 12 deletions(-) create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/EnumCaseImport.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCaseImport.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCaseImport.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.d.ts create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift index 8ce91b998..02c623918 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift @@ -928,12 +928,7 @@ extension BridgeType { return LoweringParameterInfo(loweredParameters: [("objectId", .i32)]) } case .caseEnum: - switch context { - case .importTS: - throw BridgeJSCoreError("Enum types are not yet supported in TypeScript imports") - case .exportSwift: - return LoweringParameterInfo(loweredParameters: [("value", .i32)]) - } + return LoweringParameterInfo(loweredParameters: [("value", .i32)]) case .rawValueEnum(_, let rawType): if rawType == .string { return .string @@ -1011,12 +1006,7 @@ extension BridgeType { return LiftingReturnInfo(valueToLift: .i32) } case .caseEnum: - switch context { - case .importTS: - throw BridgeJSCoreError("Enum types are not yet supported in TypeScript imports") - case .exportSwift: - return LiftingReturnInfo(valueToLift: .i32) - } + return LiftingReturnInfo(valueToLift: .i32) case .rawValueEnum(_, let rawType): let wasmType = rawType.wasmCoreType ?? .i32 return LiftingReturnInfo(valueToLift: wasmType) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/EnumCaseImport.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/EnumCaseImport.swift new file mode 100644 index 000000000..a6477be95 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/EnumCaseImport.swift @@ -0,0 +1,12 @@ +@JS enum Signal { + case start + case stop +} + +// Case enums (no raw value) bridge as their `Int32` tag as imported-function +// parameters and return values. +@JSClass struct SignalControls { + @JSFunction func send(_ signal: Signal) throws(JSException) + @JSFunction func current() throws(JSException) -> Signal + @JSFunction static func roundTrip(_ signal: Signal) throws(JSException) -> Signal +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCaseImport.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCaseImport.json new file mode 100644 index 000000000..71bf8679e --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCaseImport.json @@ -0,0 +1,139 @@ +{ + "exported" : { + "classes" : [ + + ], + "enums" : [ + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "start" + }, + { + "associatedValues" : [ + + ], + "name" : "stop" + } + ], + "emitStyle" : "const", + "name" : "Signal", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Signal", + "tsFullPath" : "Signal" + } + ], + "exposeToGlobal" : false, + "functions" : [ + + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "imported" : { + "children" : [ + { + "functions" : [ + + ], + "types" : [ + { + "accessLevel" : "internal", + "getters" : [ + + ], + "methods" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "send", + "parameters" : [ + { + "name" : "signal", + "type" : { + "caseEnum" : { + "_0" : "Signal" + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "current", + "parameters" : [ + + ], + "returnType" : { + "caseEnum" : { + "_0" : "Signal" + } + } + } + ], + "name" : "SignalControls", + "setters" : [ + + ], + "staticMethods" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "roundTrip", + "parameters" : [ + { + "name" : "signal", + "type" : { + "caseEnum" : { + "_0" : "Signal" + } + } + } + ], + "returnType" : { + "caseEnum" : { + "_0" : "Signal" + } + } + } + ] + } + ] + } + ] + }, + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCaseImport.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCaseImport.swift new file mode 100644 index 000000000..3487ad425 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCaseImport.swift @@ -0,0 +1,97 @@ +extension Signal: _BridgedSwiftCaseEnum { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + return bridgeJSRawValue + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> Signal { + return bridgeJSLiftParameter(value) + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> Signal { + return Signal(bridgeJSRawValue: value)! + } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { + return bridgeJSLowerParameter() + } + + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { + switch bridgeJSRawValue { + case 0: + self = .start + case 1: + self = .stop + default: + return nil + } + } + + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { + switch self { + case .start: + return 0 + case .stop: + return 1 + } + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_SignalControls_roundTrip_static") +fileprivate func bjs_SignalControls_roundTrip_static_extern(_ signal: Int32) -> Int32 +#else +fileprivate func bjs_SignalControls_roundTrip_static_extern(_ signal: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_SignalControls_roundTrip_static(_ signal: Int32) -> Int32 { + return bjs_SignalControls_roundTrip_static_extern(signal) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_SignalControls_send") +fileprivate func bjs_SignalControls_send_extern(_ self: Int32, _ signal: Int32) -> Void +#else +fileprivate func bjs_SignalControls_send_extern(_ self: Int32, _ signal: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_SignalControls_send(_ self: Int32, _ signal: Int32) -> Void { + return bjs_SignalControls_send_extern(self, signal) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_SignalControls_current") +fileprivate func bjs_SignalControls_current_extern(_ self: Int32) -> Int32 +#else +fileprivate func bjs_SignalControls_current_extern(_ self: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_SignalControls_current(_ self: Int32) -> Int32 { + return bjs_SignalControls_current_extern(self) +} + +func _$SignalControls_roundTrip(_ signal: Signal) throws(JSException) -> Signal { + let signalValue = signal.bridgeJSLowerParameter() + let ret = bjs_SignalControls_roundTrip_static(signalValue) + if let error = _swift_js_take_exception() { + throw error + } + return Signal.bridgeJSLiftReturn(ret) +} + +func _$SignalControls_send(_ self: JSObject, _ signal: Signal) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + let signalValue = signal.bridgeJSLowerParameter() + bjs_SignalControls_send(selfValue, signalValue) + if let error = _swift_js_take_exception() { + throw error + } +} + +func _$SignalControls_current(_ self: JSObject) throws(JSException) -> Signal { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_SignalControls_current(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return Signal.bridgeJSLiftReturn(ret) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.d.ts new file mode 100644 index 000000000..fe48c9174 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.d.ts @@ -0,0 +1,33 @@ +// 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`. + +export const SignalValues: { + readonly Start: 0; + readonly Stop: 1; +}; +export type SignalTag = typeof SignalValues[keyof typeof SignalValues]; + +export type SignalObject = typeof SignalValues; + +export interface SignalControls { + send(signal: SignalTag): void; + current(): SignalTag; +} +export type Exports = { + Signal: SignalObject +} +export type Imports = { + SignalControls: { + roundTrip(signal: SignalTag): SignalTag; + } +} +export function createInstantiator(options: { + imports: Imports; +}, swift: any): Promise<{ + addImports: (importObject: WebAssembly.Imports) => void; + setInstance: (instance: WebAssembly.Instance) => void; + createExports: (instance: WebAssembly.Instance) => Exports; +}>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js new file mode 100644 index 000000000..e232c7cbb --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js @@ -0,0 +1,251 @@ +// 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`. + +export const SignalValues = { + Start: 0, + Stop: 1, +}; + +export async function createInstantiator(options, swift) { + let instance; + let memory; + let setException; + let decodeString; + const textDecoder = new TextDecoder("utf-8"); + const textEncoder = new TextEncoder("utf-8"); + let tmpRetString; + let tmpRetBytes; + let tmpRetException; + let tmpRetOptionalBool; + let tmpRetOptionalInt; + let tmpRetOptionalFloat; + let tmpRetOptionalDouble; + let tmpRetOptionalHeapObject; + let strStack = []; + let i32Stack = []; + let i64Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; + let taStack = []; + const enumHelpers = {}; + const structHelpers = {}; + + let _exports = null; + let bjs = null; + + return { + /** + * @param {WebAssembly.Imports} importObject + */ + addImports: (importObject, importsContext) => { + bjs = {}; + importObject["bjs"] = bjs; + bjs["swift_js_return_string"] = function(ptr, len) { + tmpRetString = decodeString(ptr, len); + } + bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { + const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); + const bytes = new Uint8Array(memory.buffer, bytesPtr); + bytes.set(source); + } + bjs["swift_js_make_js_string"] = function(ptr, len) { + return swift.memory.retain(decodeString(ptr, len)); + } + bjs["swift_js_init_memory_with_result"] = function(ptr, len) { + const target = new Uint8Array(memory.buffer, ptr, len); + target.set(tmpRetBytes); + tmpRetBytes = undefined; + } + bjs["swift_js_throw"] = function(id) { + tmpRetException = swift.memory.retainByRef(id); + } + bjs["swift_js_retain"] = function(id) { + return swift.memory.retainByRef(id); + } + bjs["swift_js_release"] = function(id) { + swift.memory.release(id); + } + bjs["swift_js_push_i32"] = function(v) { + i32Stack.push(v | 0); + } + bjs["swift_js_push_f32"] = function(v) { + f32Stack.push(Math.fround(v)); + } + bjs["swift_js_push_f64"] = function(v) { + f64Stack.push(v); + } + bjs["swift_js_push_string"] = function(ptr, len) { + const value = decodeString(ptr, len); + strStack.push(value); + } + bjs["swift_js_pop_i32"] = function() { + return i32Stack.pop(); + } + bjs["swift_js_pop_f32"] = function() { + return f32Stack.pop(); + } + bjs["swift_js_pop_f64"] = function() { + return f64Stack.pop(); + } + bjs["swift_js_push_pointer"] = function(pointer) { + ptrStack.push(pointer); + } + bjs["swift_js_pop_pointer"] = function() { + return ptrStack.pop(); + } + bjs["swift_js_push_i64"] = function(v) { + i64Stack.push(v); + } + bjs["swift_js_pop_i64"] = function() { + return i64Stack.pop(); + } + const taCtors = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array]; + bjs["swift_js_push_typed_array"] = function(kind, ptr, count) { + const Ctor = taCtors[kind]; + const byteLen = count * Ctor.BYTES_PER_ELEMENT; + const copy = memory.buffer.slice(ptr, ptr + byteLen); + taStack.push(Array.from(new Ctor(copy))); + } + bjs["swift_js_return_optional_bool"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalBool = null; + } else { + tmpRetOptionalBool = value !== 0; + } + } + bjs["swift_js_return_optional_int"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalInt = null; + } else { + tmpRetOptionalInt = value | 0; + } + } + bjs["swift_js_return_optional_float"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalFloat = null; + } else { + tmpRetOptionalFloat = Math.fround(value); + } + } + bjs["swift_js_return_optional_double"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalDouble = null; + } else { + tmpRetOptionalDouble = value; + } + } + bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = decodeString(ptr, len); + } + } + bjs["swift_js_return_optional_object"] = function(isSome, objectId) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = swift.memory.getObject(objectId); + } + } + bjs["swift_js_return_optional_heap_object"] = function(isSome, pointer) { + if (isSome === 0) { + tmpRetOptionalHeapObject = null; + } else { + tmpRetOptionalHeapObject = pointer; + } + } + bjs["swift_js_get_optional_int_presence"] = function() { + return tmpRetOptionalInt != null ? 1 : 0; + } + bjs["swift_js_get_optional_int_value"] = function() { + const value = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; + return value; + } + bjs["swift_js_get_optional_string"] = function() { + const str = tmpRetString; + tmpRetString = undefined; + if (str == null) { + return -1; + } else { + const bytes = textEncoder.encode(str); + tmpRetBytes = bytes; + return bytes.length; + } + } + bjs["swift_js_get_optional_float_presence"] = function() { + return tmpRetOptionalFloat != null ? 1 : 0; + } + bjs["swift_js_get_optional_float_value"] = function() { + const value = tmpRetOptionalFloat; + tmpRetOptionalFloat = undefined; + return value; + } + bjs["swift_js_get_optional_double_presence"] = function() { + return tmpRetOptionalDouble != null ? 1 : 0; + } + bjs["swift_js_get_optional_double_value"] = function() { + const value = tmpRetOptionalDouble; + tmpRetOptionalDouble = undefined; + return value; + } + bjs["swift_js_get_optional_heap_object_pointer"] = function() { + const pointer = tmpRetOptionalHeapObject; + tmpRetOptionalHeapObject = undefined; + return pointer || 0; + } + bjs["swift_js_closure_unregister"] = function(funcRef) {} + const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; + TestModule["bjs_SignalControls_roundTrip_static"] = function bjs_SignalControls_roundTrip_static(signal) { + try { + let ret = imports.SignalControls.roundTrip(signal); + return ret; + } catch (error) { + setException(error); + return 0 + } + } + TestModule["bjs_SignalControls_send"] = function bjs_SignalControls_send(self, signal) { + try { + swift.memory.getObject(self).send(signal); + } catch (error) { + setException(error); + } + } + TestModule["bjs_SignalControls_current"] = function bjs_SignalControls_current(self) { + try { + let ret = swift.memory.getObject(self).current(); + return ret; + } catch (error) { + setException(error); + return 0 + } + } + }, + setInstance: (i) => { + instance = i; + memory = instance.exports.memory; + + decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + + setException = (error) => { + instance.exports._swift_js_exception.value = swift.memory.retain(error) + } + }, + /** @param {WebAssembly.Instance} instance */ + createExports: (instance) => { + const js = swift.memory.heap; + const exports = { + Signal: SignalValues, + }; + _exports = exports; + return exports; + }, + } +} \ No newline at end of file diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 4a94431f2..e6c2f940b 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -4831,6 +4831,45 @@ public func _bjs_NestedStructGroupB_static_roundtripMetadata() -> Void { #endif } +extension LightColor: _BridgedSwiftCaseEnum { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + return bridgeJSRawValue + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> LightColor { + return bridgeJSLiftParameter(value) + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> LightColor { + return LightColor(bridgeJSRawValue: value)! + } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { + return bridgeJSLowerParameter() + } + + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { + switch bridgeJSRawValue { + case 0: + self = .red + case 1: + self = .yellow + case 2: + self = .green + default: + return nil + } + } + + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { + switch self { + case .red: + return 0 + case .yellow: + return 1 + case .green: + return 2 + } + } +} + @_expose(wasm, "bjs_IntegerTypesSupportExports_static_roundTripInt") @_cdecl("bjs_IntegerTypesSupportExports_static_roundTripInt") public func _bjs_IntegerTypesSupportExports_static_roundTripInt(_ v: Int32) -> Int32 { @@ -13256,6 +13295,27 @@ func _$Animal_getIsCat(_ self: JSObject) throws(JSException) -> Bool { return Bool.bridgeJSLiftReturn(ret) } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripLightColor") +fileprivate func bjs_jsRoundTripLightColor_extern(_ value: Int32) -> Int32 +#else +fileprivate func bjs_jsRoundTripLightColor_extern(_ value: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsRoundTripLightColor(_ value: Int32) -> Int32 { + return bjs_jsRoundTripLightColor_extern(value) +} + +func _$jsRoundTripLightColor(_ value: LightColor) throws(JSException) -> LightColor { + let valueValue = value.bridgeJSLowerParameter() + let ret = bjs_jsRoundTripLightColor(valueValue) + if let error = _swift_js_take_exception() { + throw error + } + return LightColor.bridgeJSLiftReturn(ret) +} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsTranslatePoint") fileprivate func bjs_jsTranslatePoint_extern(_ point: Int32, _ dx: Int32, _ dy: Int32) -> Int32 diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index 9ea12bde7..a28843142 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -9254,6 +9254,38 @@ "swiftCallName" : "NestedStructGroupB", "tsFullPath" : "NestedStructGroupB" }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "red" + }, + { + "associatedValues" : [ + + ], + "name" : "yellow" + }, + { + "associatedValues" : [ + + ], + "name" : "green" + } + ], + "emitStyle" : "const", + "name" : "LightColor", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "LightColor", + "tsFullPath" : "LightColor" + }, { "cases" : [ @@ -19698,6 +19730,37 @@ } ] }, + { + "functions" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsRoundTripLightColor", + "parameters" : [ + { + "name" : "value", + "type" : { + "caseEnum" : { + "_0" : "LightColor" + } + } + } + ], + "returnType" : { + "caseEnum" : { + "_0" : "LightColor" + } + } + } + ], + "types" : [ + + ] + }, { "functions" : [ { diff --git a/Tests/BridgeJSRuntimeTests/ImportAPITests.swift b/Tests/BridgeJSRuntimeTests/ImportAPITests.swift index 38ff2a205..2bb9158b9 100644 --- a/Tests/BridgeJSRuntimeTests/ImportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ImportAPITests.swift @@ -1,6 +1,14 @@ import XCTest import JavaScriptKit +@JS enum LightColor { + case red + case yellow + case green +} + +@JSFunction func jsRoundTripLightColor(_ value: LightColor) throws(JSException) -> LightColor + class ImportAPITests: XCTestCase { func testRoundTripVoid() throws { try jsRoundTripVoid() @@ -66,6 +74,12 @@ class ImportAPITests: XCTestCase { XCTAssertNil(try jsRoundTripOptionalPoint(nil)) } + func testRoundTripCaseEnum() throws { + for v in [LightColor.red, .yellow, .green] { + try XCTAssertEqual(jsRoundTripLightColor(v), v) + } + } + func ensureThrows(_ f: (Bool) throws(JSException) -> T) throws { do { _ = try f(true) diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index f9e2f7727..05956d8d3 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -88,6 +88,9 @@ export async function setupOptions(options, context) { "jsRoundTripFeatureFlag": (flag) => { return flag; }, + "jsRoundTripLightColor": (value) => { + return value; + }, "jsEchoJSValue": (v) => { return v; }, From 7aef830177fa58228fa87de89c980cc965abcfa2 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Mon, 8 Jun 2026 17:08:13 +0200 Subject: [PATCH 04/50] BridgeJS: Use a BigInt zero placeholder for Wasm i64 in generated JS A Wasm i64 parameter or return value is represented as a JavaScript BigInt. The generated JS used a plain 0 as the placeholder for the absent case of an optional i64 parameter (isSome ? v : 0) and for the error-path return of an imported thunk, so calling such an export with null (or an imported i64 function throwing) raised "TypeError: Cannot convert 0 to a BigInt". Emit 0n for i64 in both placeholders (jsZeroLiteral and the imported-thunk return placeholder). This was latent because the optional Int64/UInt64 round-trip tests never exercised the none case; add those assertions. --- Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift | 5 ++++- Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift | 5 ++++- .../__Snapshots__/BridgeJSLinkTests/EnumRawType.js | 4 ++-- .../__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js | 4 ++-- .../BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs | 4 ++++ 5 files changed, 16 insertions(+), 6 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index 03dfa87a2..ce0ba0cb8 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -3704,7 +3704,10 @@ extension BridgeType { extension WasmCoreType { fileprivate var placeholderValue: String { switch self { - case .i32, .i64, .f32, .f64, .pointer: return "0" + // A Wasm `i64` return is a JavaScript `BigInt`, so the error-path placeholder + // must be a BigInt literal rather than a plain number. + case .i64: return "0n" + case .i32, .f32, .f64, .pointer: return "0" } } } diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift index 51ef16b20..388d703bd 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift @@ -2603,7 +2603,10 @@ fileprivate extension WasmCoreType { var jsZeroLiteral: String { switch self { case .f32, .f64: return "0.0" - case .i32, .i64, .pointer: return "0" + // A Wasm `i64` parameter is passed as a JavaScript `BigInt`, so its zero + // placeholder must be a BigInt literal rather than a plain number. + case .i64: return "0n" + case .i32, .pointer: return "0" } } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js index b004e3b74..4e4449e06 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js @@ -440,7 +440,7 @@ export async function createInstantiator(options, swift) { }, roundTripOptionalFileSize: function bjs_roundTripOptionalFileSize(input) { const isSome = input != null; - instance.exports.bjs_roundTripOptionalFileSize(+isSome, isSome ? input : 0); + instance.exports.bjs_roundTripOptionalFileSize(+isSome, isSome ? input : 0n); const isSome1 = i32Stack.pop(); let optResult; if (isSome1) { @@ -488,7 +488,7 @@ export async function createInstantiator(options, swift) { }, roundTripOptionalSessionId: function bjs_roundTripOptionalSessionId(input) { const isSome = input != null; - instance.exports.bjs_roundTripOptionalSessionId(+isSome, isSome ? input : 0); + instance.exports.bjs_roundTripOptionalSessionId(+isSome, isSome ? input : 0n); const isSome1 = i32Stack.pop(); let optResult; if (isSome1) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js index 4aa424d68..211cbefa3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js @@ -258,7 +258,7 @@ export async function createInstantiator(options, swift) { return ret; } catch (error) { setException(error); - return 0 + return 0n } } TestModule["bjs_roundTripUInt64"] = function bjs_roundTripUInt64(v) { @@ -267,7 +267,7 @@ export async function createInstantiator(options, swift) { return ret; } catch (error) { setException(error); - return 0 + return 0n } } }, diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs index 6576876da..ae445d3f4 100644 --- a/Tests/BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs +++ b/Tests/BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs @@ -80,6 +80,10 @@ export function runJsOptionalSupportTests(rootExports) { assert.equal(exports.roundTripOptionalIntRawValueEnum(HttpStatus.Ok), HttpStatusValues.Ok); assert.equal(exports.roundTripOptionalInt64RawValueEnum(FileSize.Tiny), FileSizeValues.Tiny); assert.equal(exports.roundTripOptionalUInt64RawValueEnum(SessionId.Active), SessionIdValues.Active); + // The `none` case lowers the i64/u64 placeholder as a BigInt (`0n`); a plain `0` + // would throw "Cannot convert 0 to a BigInt" when calling the Wasm export. + assert.equal(exports.roundTripOptionalInt64RawValueEnum(null), null); + assert.equal(exports.roundTripOptionalUInt64RawValueEnum(null), null); assert.equal(exports.roundTripOptionalTSEnum(TSDirection.North), TSDirection.North); assert.equal(exports.roundTripOptionalTSStringEnum(TSTheme.Light), TSTheme.Light); assert.equal(exports.roundTripOptionalNamespacedEnum(Networking.API.Method.Get), Networking.API.Method.Get); From c93a0310de03ad55bf40c8cfd2f51b4022bc4dc1 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Wed, 3 Jun 2026 12:56:25 +0200 Subject: [PATCH 05/50] BridgeJS: Support optional @JSClass as exported function parameters --- .../Sources/BridgeJSLink/JSGlueGen.swift | 22 +++++- .../Inputs/MacroSwift/Optionals.swift | 7 ++ .../BridgeJSCodegenTests/Optionals.json | 70 +++++++++++++++++++ .../BridgeJSCodegenTests/Optionals.swift | 22 ++++++ .../BridgeJSLinkTests/Optionals.d.ts | 2 + .../BridgeJSLinkTests/Optionals.js | 42 +++++++++++ .../JavaScriptKit/BridgeJSIntrinsics.swift | 23 ++++++ .../BridgeJSRuntimeTests/ExportAPITests.swift | 4 ++ .../Generated/BridgeJS.swift | 11 +++ .../Generated/JavaScript/BridgeJS.json | 35 ++++++++++ Tests/prelude.mjs | 7 ++ 11 files changed, 243 insertions(+), 2 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift index 51ef16b20..365d3e3bd 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift @@ -762,7 +762,7 @@ struct IntrinsicJSFragment: Sendable { } let innerFragment = - if wrappedType.optionalConvention == .stackABI { + if wrappedType.optionalParameterUsesStackABI { try stackLowerFragment(elementType: wrappedType) } else { try lowerParameter(type: wrappedType) @@ -779,7 +779,7 @@ struct IntrinsicJSFragment: Sendable { kind: JSOptionalKind, innerFragment: IntrinsicJSFragment ) throws -> IntrinsicJSFragment { - let isStackConvention = wrappedType.optionalConvention == .stackABI + let isStackConvention = wrappedType.optionalParameterUsesStackABI return IntrinsicJSFragment( parameters: ["value"], @@ -2696,6 +2696,24 @@ private extension BridgeType { } } + /// Whether an optional of this type pushes its payload onto the bridge stack + /// when passed as a *parameter*. + /// + /// This usually matches `optionalConvention == .stackABI`, but `jsObject` + /// optionals are the exception: their return values travel through the stack + /// while their parameters use the direct `(isSome, objId)` ABI, matching plain + /// `Optional` and exported `@JS class` parameters. + var optionalParameterUsesStackABI: Bool { + switch self { + case .jsObject: + return false + case .nullable(let wrapped, _): + return wrapped.optionalParameterUsesStackABI + default: + return optionalConvention == .stackABI + } + } + var nilSentinel: NilSentinel { switch self { case .swiftProtocol: diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Optionals.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Optionals.swift index 5df48d9c0..ea37f5740 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Optionals.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Optionals.swift @@ -30,6 +30,13 @@ class OptionalPropertyHolder { @JS func testOptionalPropertyRoundtrip(_ holder: OptionalPropertyHolder?) -> OptionalPropertyHolder? +// Exported functions taking an optional jsObject use the direct (isSome, objId) +// parameter ABI; the return value travels through the stack ABI. +@JS func roundTripExportedOptionalJSObject(value: JSObject?) -> JSObject? + +// Exported function taking/returning an optional imported @JSClass (issue #751). +@JS func roundTripExportedOptionalJSClass(value: WithOptionalJSClass?) -> WithOptionalJSClass? + @JS func roundTripString(name: String?) -> String? { return name diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.json index 91291c24e..e9d78cbbc 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.json @@ -239,6 +239,76 @@ } } }, + { + "abiName" : "bjs_roundTripExportedOptionalJSObject", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripExportedOptionalJSObject", + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "jsObject" : { + + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "jsObject" : { + + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_roundTripExportedOptionalJSClass", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripExportedOptionalJSClass", + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "jsObject" : { + "_0" : "WithOptionalJSClass" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "jsObject" : { + "_0" : "WithOptionalJSClass" + } + }, + "_1" : "null" + } + } + }, { "abiName" : "bjs_roundTripString", "effects" : { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.swift index 0a2528340..65380d1e3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.swift @@ -20,6 +20,28 @@ public func _bjs_testOptionalPropertyRoundtrip(_ holderIsSome: Int32, _ holderVa #endif } +@_expose(wasm, "bjs_roundTripExportedOptionalJSObject") +@_cdecl("bjs_roundTripExportedOptionalJSObject") +public func _bjs_roundTripExportedOptionalJSObject(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripExportedOptionalJSObject(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripExportedOptionalJSClass") +@_cdecl("bjs_roundTripExportedOptionalJSClass") +public func _bjs_roundTripExportedOptionalJSClass(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripExportedOptionalJSClass(value: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_roundTripString") @_cdecl("bjs_roundTripString") public func _bjs_roundTripString(_ nameIsSome: Int32, _ nameBytes: Int32, _ nameLength: Int32) -> Void { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.d.ts index fb9d68db7..c4a22ac0c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.d.ts @@ -50,6 +50,8 @@ export type Exports = { } roundTripOptionalClass(value: Greeter | null): Greeter | null; testOptionalPropertyRoundtrip(holder: OptionalPropertyHolder | null): OptionalPropertyHolder | null; + roundTripExportedOptionalJSObject(value: any | null): any | null; + roundTripExportedOptionalJSClass(value: WithOptionalJSClass | null): WithOptionalJSClass | null; roundTripString(name: string | null): string | null; roundTripInt(value: number | null): number | null; roundTripInt8(value: number | null): number | null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js index f376c1b24..58dd88780 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js @@ -725,6 +725,48 @@ export async function createInstantiator(options, swift) { const optResult = pointer === null ? null : OptionalPropertyHolder.__construct(pointer); return optResult; }, + roundTripExportedOptionalJSObject: function bjs_roundTripExportedOptionalJSObject(value) { + const isSome = value != null; + let result; + if (isSome) { + result = swift.memory.retain(value); + } else { + result = 0; + } + instance.exports.bjs_roundTripExportedOptionalJSObject(+isSome, result); + const isSome1 = i32Stack.pop(); + let optResult; + if (isSome1) { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + optResult = obj; + } else { + optResult = null; + } + return optResult; + }, + roundTripExportedOptionalJSClass: function bjs_roundTripExportedOptionalJSClass(value) { + const isSome = value != null; + let result; + if (isSome) { + result = swift.memory.retain(value); + } else { + result = 0; + } + instance.exports.bjs_roundTripExportedOptionalJSClass(+isSome, result); + const isSome1 = i32Stack.pop(); + let optResult; + if (isSome1) { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + optResult = obj; + } else { + optResult = null; + } + return optResult; + }, roundTripString: function bjs_roundTripString(name) { const isSome = name != null; let result, result1; diff --git a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift index ff586b45b..955f31ea9 100644 --- a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift +++ b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift @@ -1826,6 +1826,29 @@ extension _BridgedAsOptional where Wrapped == JSObject { } } +extension _BridgedAsOptional where Wrapped: _JSBridgedClass { + // `@JSClass` wrappers (`_JSBridgedClass`) bridge an underlying `JSObject`, so an + // optional wrapper mirrors `Optional`: parameters use the direct + // (`isSome`, object id) ABI while returns travel through the bridge stack. + // + // Stack push/pop is provided by the generic `Wrapped: _BridgedSwiftStackType` + // extension; only the direct parameter lift and the export return lowering need + // dedicated implementations here. + @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ objectId: Int32) -> Self { + Self( + optional: Optional._bridgeJSLiftParameter( + isSome, + objectId, + liftWrapped: Wrapped.bridgeJSLiftParameter + ) + ) + } + + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { + Wrapped.bridgeJSStackPushAsOptional(asOptional) + } +} + extension _BridgedAsOptional where Wrapped: _BridgedSwiftProtocolWrapper { @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32, _ objectId: Int32) -> Self { Self( diff --git a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift index c6e216203..efad25ca1 100644 --- a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift @@ -75,6 +75,10 @@ func runJsWorks() -> Void return try Foo(value) } +@JS func roundTripOptionalImportedClass(v: Foo?) -> Foo? { + return v +} + struct TestError: Error { let message: String } diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 3fa4eb9d5..944231b28 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -6940,6 +6940,17 @@ public func _bjs_makeImportedFoo(_ valueBytes: Int32, _ valueLength: Int32) -> I #endif } +@_expose(wasm, "bjs_roundTripOptionalImportedClass") +@_cdecl("bjs_roundTripOptionalImportedClass") +public func _bjs_roundTripOptionalImportedClass(_ vIsSome: Int32, _ vValue: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripOptionalImportedClass(v: Optional.bridgeJSLiftParameter(vIsSome, vValue)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_throwsSwiftError") @_cdecl("bjs_throwsSwiftError") public func _bjs_throwsSwiftError(_ shouldThrow: Int32) -> Void { diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index 94142f470..b29321cf1 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -11917,6 +11917,41 @@ } } }, + { + "abiName" : "bjs_roundTripOptionalImportedClass", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalImportedClass", + "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "jsObject" : { + "_0" : "Foo" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "jsObject" : { + "_0" : "Foo" + } + }, + "_1" : "null" + } + } + }, { "abiName" : "bjs_throwsSwiftError", "effects" : { diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index 2c922dbe2..5091b1dd6 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -301,6 +301,13 @@ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { assert.ok(foo instanceof ImportedFoo); assert.equal(foo.value, "hello"); + // Optional @JSClass directly as an exported function parameter/return value (issue #751) + const optFoo = new ImportedFoo("optional-foo"); + const optFooResult = exports.roundTripOptionalImportedClass(optFoo); + assert.ok(optFooResult instanceof ImportedFoo); + assert.equal(optFooResult.value, "optional-foo"); + assert.equal(exports.roundTripOptionalImportedClass(null), null); + // Test PropertyHolder with various types const testObj = { testProp: "test" }; const sibling = new exports.SimplePropertyHolder(999); From 83098c2bc1dbffe851f64303d880d5f024652265 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Tue, 9 Jun 2026 18:30:40 +0200 Subject: [PATCH 06/50] BridgeJS: Pass optional jsObject import parameters via direct ABI --- .../Sources/BridgeJSLink/JSGlueGen.swift | 4 +-- .../BridgeJSLinkTests/Optionals.js | 30 ++++------------ .../Generated/BridgeJS.swift | 21 ++++++++++++ .../Generated/JavaScript/BridgeJS.json | 34 +++++++++++++++++++ .../JavaScript/OptionalSupportTests.mjs | 3 ++ .../OptionalSupportTests.swift | 11 ++++++ 6 files changed, 77 insertions(+), 26 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift index 365d3e3bd..5ee86a57e 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift @@ -669,7 +669,7 @@ struct IntrinsicJSFragment: Sendable { } let innerFragment = - if wrappedType.optionalConvention == .stackABI { + if wrappedType.optionalParameterUsesStackABI { try stackLiftFragment(elementType: wrappedType) } else { try liftParameter(type: wrappedType, context: bridgeContext) @@ -686,7 +686,7 @@ struct IntrinsicJSFragment: Sendable { kind: JSOptionalKind, innerFragment: IntrinsicJSFragment ) -> IntrinsicJSFragment { - let isStackConvention = wrappedType.optionalConvention == .stackABI + let isStackConvention = wrappedType.optionalParameterUsesStackABI let absenceLiteral = kind.absenceLiteral let outerParams: [String] diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js index 58dd88780..d084c8fcf 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js @@ -387,18 +387,9 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_WithOptionalJSClass_childOrNull_set"] = function bjs_WithOptionalJSClass_childOrNull_set(self, newValue) { + TestModule["bjs_WithOptionalJSClass_childOrNull_set"] = function bjs_WithOptionalJSClass_childOrNull_set(self, newValueIsSome, newValueObjectId) { try { - let optResult; - if (newValue) { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - optResult = obj; - } else { - optResult = null; - } - swift.memory.getObject(self).childOrNull = optResult; + swift.memory.getObject(self).childOrNull = newValueIsSome ? swift.memory.getObject(newValueObjectId) : null; } catch (error) { setException(error); } @@ -489,22 +480,13 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_WithOptionalJSClass_roundTripChildOrNull"] = function bjs_WithOptionalJSClass_roundTripChildOrNull(self, value) { + TestModule["bjs_WithOptionalJSClass_roundTripChildOrNull"] = function bjs_WithOptionalJSClass_roundTripChildOrNull(self, valueIsSome, valueObjectId) { try { - let optResult; - if (value) { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - optResult = obj; - } else { - optResult = null; - } - let ret = swift.memory.getObject(self).roundTripChildOrNull(optResult); + let ret = swift.memory.getObject(self).roundTripChildOrNull(valueIsSome ? swift.memory.getObject(valueObjectId) : null); const isSome = ret != null; if (isSome) { - const objId1 = swift.memory.retain(ret); - i32Stack.push(objId1); + const objId = swift.memory.retain(ret); + i32Stack.push(objId); } i32Stack.push(isSome ? 1 : 0); } catch (error) { diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 944231b28..af8308c88 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -14087,6 +14087,18 @@ fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDic return bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryUndefined_static_extern(v) } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_OptionalSupportImports_jsRoundTripOptionalJSObjectNull_static") +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalJSObjectNull_static_extern(_ valueIsSome: Int32, _ valueValue: Int32) -> Void +#else +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalJSObjectNull_static_extern(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalJSObjectNull_static(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { + return bjs_OptionalSupportImports_jsRoundTripOptionalJSObjectNull_static_extern(valueIsSome, valueValue) +} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_OptionalSupportImports_runJsOptionalSupportTests_static") fileprivate func bjs_OptionalSupportImports_runJsOptionalSupportTests_static_extern() -> Void @@ -14173,6 +14185,15 @@ func _$OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryUndefin return JSUndefinedOr<[String: String]>.bridgeJSLiftReturn() } +func _$OptionalSupportImports_jsRoundTripOptionalJSObjectNull(_ value: Optional) throws(JSException) -> Optional { + let (valueIsSome, valueValue) = value.bridgeJSLowerParameter() + bjs_OptionalSupportImports_jsRoundTripOptionalJSObjectNull_static(valueIsSome, valueValue) + if let error = _swift_js_take_exception() { + throw error + } + return Optional.bridgeJSLiftReturn() +} + func _$OptionalSupportImports_runJsOptionalSupportTests() throws(JSException) -> Void { bjs_OptionalSupportImports_runJsOptionalSupportTests_static() if let error = _swift_js_take_exception() { diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index b29321cf1..4f1038b5e 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -21047,6 +21047,40 @@ } } }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsRoundTripOptionalJSObjectNull", + "parameters" : [ + { + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "jsObject" : { + + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "jsObject" : { + + } + }, + "_1" : "null" + } + } + }, { "accessLevel" : "internal", "effects" : { diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs index 6576876da..7c2b991ae 100644 --- a/Tests/BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs +++ b/Tests/BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs @@ -46,6 +46,9 @@ export function getImports(importsContext) { jsRoundTripOptionalStringToStringDictionaryUndefined: (v) => { return v === undefined ? undefined : v; }, + jsRoundTripOptionalJSObjectNull: (v) => { + return v ?? null; + }, runJsOptionalSupportTests: () => { const exports = importsContext.getExports(); if (!exports) { throw new Error("No exports!?"); } diff --git a/Tests/BridgeJSRuntimeTests/OptionalSupportTests.swift b/Tests/BridgeJSRuntimeTests/OptionalSupportTests.swift index 3b06901db..85eaa04c7 100644 --- a/Tests/BridgeJSRuntimeTests/OptionalSupportTests.swift +++ b/Tests/BridgeJSRuntimeTests/OptionalSupportTests.swift @@ -24,6 +24,8 @@ import JavaScriptEventLoop _ v: JSUndefinedOr<[String: String]> ) throws(JSException) -> JSUndefinedOr<[String: String]> + @JSFunction static func jsRoundTripOptionalJSObjectNull(_ value: JSObject?) throws(JSException) -> JSObject? + @JSFunction static func runJsOptionalSupportTests() throws(JSException) } @@ -84,6 +86,15 @@ final class OptionalSupportTests: XCTestCase { func testRoundTripOptionalStringToStringDictionaryUndefined() throws { try roundTripTest(OptionalSupportImports.jsRoundTripOptionalStringToStringDictionaryUndefined, ["key": "value"]) } + + func testRoundTripOptionalJSObjectNull() throws { + try XCTAssertNil(OptionalSupportImports.jsRoundTripOptionalJSObjectNull(nil)) + + let object = JSObject.global.Object.function!.new() + object.testProp = "hello" + let result = try OptionalSupportImports.jsRoundTripOptionalJSObjectNull(object) + XCTAssertEqual(result?.testProp.string, "hello") + } } @JS enum OptionalSupportExports { From 388160c0028ca7c61c6d140b9998a126c70297c4 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Tue, 9 Jun 2026 18:54:56 +0200 Subject: [PATCH 07/50] BridgeJS: Support non-ConvertibleToJSValue async exported return types (#758) --- .../Sources/BridgeJSCore/ExportSwift.swift | 149 +++- .../Sources/BridgeJSLink/BridgeJSLink.swift | 67 ++ .../BridgeJSSkeleton/BridgeJSSkeleton.swift | 43 + .../BridgeJSToolTests/DiagnosticsTests.swift | 50 ++ .../Inputs/MacroSwift/Async.swift | 63 ++ .../BridgeJSCodegenTests/Async.json | 461 ++++++++++ .../BridgeJSCodegenTests/Async.swift | 666 ++++++++++++++- .../BridgeJSLinkTests/ArrayTypes.js | 7 + .../BridgeJSLinkTests/Async.d.ts | 34 + .../__Snapshots__/BridgeJSLinkTests/Async.js | 441 ++++++++++ .../BridgeJSLinkTests/AsyncImport.js | 7 + .../BridgeJSLinkTests/AsyncStaticImport.js | 7 + .../BridgeJSLinkTests/DefaultParameters.js | 7 + .../BridgeJSLinkTests/DictionaryTypes.js | 7 + .../BridgeJSLinkTests/EnumAssociatedValue.js | 7 + .../BridgeJSLinkTests/EnumCase.js | 7 + .../BridgeJSLinkTests/EnumCaseImport.js | 7 + .../BridgeJSLinkTests/EnumNamespace.Global.js | 7 + .../BridgeJSLinkTests/EnumNamespace.js | 7 + .../BridgeJSLinkTests/EnumRawType.js | 7 + .../BridgeJSLinkTests/FixedWidthIntegers.js | 7 + .../BridgeJSLinkTests/GlobalGetter.js | 7 + .../BridgeJSLinkTests/GlobalThisImports.js | 7 + .../IdentityModeClass.ConfigPointer.js | 7 + .../IdentityModeClass.PerClass.js | 7 + .../BridgeJSLinkTests/IdentityModeClass.js | 7 + .../BridgeJSLinkTests/ImportArray.js | 7 + .../ImportedTypeInExportedInterface.js | 7 + .../BridgeJSLinkTests/InvalidPropertyNames.js | 7 + .../BridgeJSLinkTests/JSClass.js | 7 + .../JSClassStaticFunctions.js | 7 + .../BridgeJSLinkTests/JSTypedArrayTypes.js | 7 + .../BridgeJSLinkTests/JSValue.js | 7 + .../BridgeJSLinkTests/MixedGlobal.js | 7 + .../BridgeJSLinkTests/MixedModules.js | 7 + .../BridgeJSLinkTests/MixedPrivate.js | 7 + .../BridgeJSLinkTests/Namespaces.Global.js | 7 + .../BridgeJSLinkTests/Namespaces.js | 7 + .../BridgeJSLinkTests/NestedType.js | 7 + .../BridgeJSLinkTests/Optionals.js | 7 + .../BridgeJSLinkTests/PrimitiveParameters.js | 7 + .../BridgeJSLinkTests/PrimitiveReturn.js | 7 + .../BridgeJSLinkTests/PropertyTypes.js | 7 + .../BridgeJSLinkTests/Protocol.js | 7 + .../BridgeJSLinkTests/ProtocolInClosure.js | 7 + .../StaticFunctions.Global.js | 7 + .../BridgeJSLinkTests/StaticFunctions.js | 7 + .../StaticProperties.Global.js | 7 + .../BridgeJSLinkTests/StaticProperties.js | 7 + .../BridgeJSLinkTests/StringParameter.js | 7 + .../BridgeJSLinkTests/StringReturn.js | 7 + .../BridgeJSLinkTests/SwiftClass.js | 7 + .../BridgeJSLinkTests/SwiftClosure.js | 7 + .../BridgeJSLinkTests/SwiftClosureImports.js | 7 + .../BridgeJSLinkTests/SwiftStruct.js | 7 + .../BridgeJSLinkTests/SwiftStructImports.js | 7 + .../SwiftTypedClosureAccess.js | 7 + .../__Snapshots__/BridgeJSLinkTests/Throws.js | 7 + .../BridgeJSLinkTests/UnsafePointer.js | 7 + .../VoidParameterVoidReturn.js | 7 + Plugins/PackageToJS/Templates/instantiate.js | 1 + .../JavaScriptKit/BridgeJSIntrinsics.swift | 64 ++ .../BridgeJSRuntimeTests/ExportAPITests.swift | 24 + .../Generated/BridgeJS.swift | 800 +++++++++++++++++- .../Generated/JavaScript/BridgeJS.json | 783 +++++++++++++++-- .../JavaScript/AsyncImportTests.mjs | 76 ++ Tests/BridgeJSRuntimeTests/StructAPIs.swift | 35 + 67 files changed, 3939 insertions(+), 175 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift index b649b244d..c9ef1e6f1 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift @@ -90,11 +90,77 @@ public class ExportSwift { decls.append(contentsOf: try renderSingleExportedClass(klass: klass)) } } + + try withSpan("Render Async Promise Helpers") { [self] in + let asyncResolveTypes = skeleton.asyncPromiseResolveReturnTypes + if !asyncResolveTypes.isEmpty { + decls.append(contentsOf: try renderPromiseRejectHelper()) + for type in asyncResolveTypes { + decls.append(contentsOf: try renderPromiseResolveHelper(type)) + } + } + } return withSpan("Format Export Glue") { return decls.map { $0.description }.joined(separator: "\n\n") } } + /// Generates the per-type `Promise_resolve_` settlement helper. + private func renderPromiseResolveHelper(_ type: BridgeType) throws -> [DeclSyntax] { + try renderPromiseSettleHelper( + functionName: "Promise_resolve_\(type.mangleTypeName)", + externName: "promise_resolve_\(moduleName)_\(type.mangleTypeName)", + valueType: type + ) + } + + /// Generates the shared `Promise_reject` settlement helper. + private func renderPromiseRejectHelper() throws -> [DeclSyntax] { + try renderPromiseSettleHelper( + functionName: "Promise_reject", + externName: "promise_reject_\(moduleName)", + valueType: .jsValue + ) + } + + /// Generates a `@JSFunction func (_ promise: JSObject, _ value: T)` and its + /// glue, lowering `value` through the standard imported-parameter ABI. + private func renderPromiseSettleHelper( + functionName: String, + externName: String, + valueType: BridgeType + ) throws -> [DeclSyntax] { + let effects = Effects(isAsync: false, isThrows: true) + // `Void` can't cross the bridge as a parameter, so the void helper takes only the promise. + var parameters = [Parameter(label: nil, name: "promise", type: .jsObject(nil))] + if valueType != .void { + parameters.append(Parameter(label: nil, name: "value", type: valueType)) + } + let builder = try ImportTS.CallJSEmission( + moduleName: "bjs", + abiName: externName, + effects: effects, + returnType: .void, + context: .importTS + ) + for parameter in parameters { + try builder.lowerParameter(param: parameter) + } + try builder.call() + try builder.liftReturnValue() + + let valueParam = valueType == .void ? "" : ", _ value: \(valueType.swiftType)" + let macroDecl: DeclSyntax = + "@JSFunction func \(raw: functionName)(_ promise: JSObject\(raw: valueParam)) throws(JSException)" + let glueDecl = builder.renderThunkDecl( + name: "_$\(functionName)", + parameters: parameters, + returnType: .void, + effects: effects + ) + return [macroDecl, builder.renderImportDecl(), glueDecl] + } + class ExportedThunkBuilder { var body: [CodeBlockItemSyntax] = [] var liftedParameterExprs: [ExprSyntax] = [] @@ -104,8 +170,22 @@ public class ExportSwift { var externDecls: [DeclSyntax] = [] let effects: Effects - init(effects: Effects) { + /// The async return type settled through `_bjs_makePromise`'s `Promise_resolve_` + /// helper. Set for every `async` thunk. + var asyncResolveReturnType: BridgeType? + + /// Stack-using parameter lifts hoisted ahead of the deferred async closure. + var asyncHoistedBindings: [CodeBlockItemSyntax] = [] + + init(effects: Effects, returnType: BridgeType) throws { self.effects = effects + guard effects.isAsync else { return } + guard returnType.isAsyncResolvable else { + throw BridgeJSCoreError( + "Returning '\(returnType.swiftType)' from an async exported function is not yet supported" + ) + } + self.asyncResolveReturnType = returnType } private func append(_ item: CodeBlockItemSyntax) { @@ -200,7 +280,7 @@ public class ExportSwift { } if effects.isAsync, returnType != .void { - return CodeBlockItemSyntax(item: .init(StmtSyntax("return \(raw: callExpr).jsValue"))) + return CodeBlockItemSyntax(item: .init(StmtSyntax("return \(raw: callExpr)"))) } if returnType == .void { @@ -244,6 +324,22 @@ public class ExportSwift { param.type.isStackUsingParameter ? index : nil } + if effects.isAsync { + // Drain stack parameters before the deferred `Task` or the shared stack is corrupted. + for index in stackParamIndices.reversed() { + let param = parameters[index] + let expr = liftedParameterExprs[index] + let varName = "_tmp_\(param.name)" + var binding: CodeBlockItemSyntax = "let \(raw: varName) = \(expr)" + if !asyncHoistedBindings.isEmpty { + binding = binding.with(\.leadingTrivia, .newline) + } + asyncHoistedBindings.append(binding) + liftedParameterExprs[index] = ExprSyntax(DeclReferenceExprSyntax(baseName: .identifier(varName))) + } + return + } + guard stackParamIndices.count > 1 else { return } for index in stackParamIndices.reversed() { @@ -293,8 +389,7 @@ public class ExportSwift { return } if effects.isAsync { - // The return value of async function (T of `(...) async -> T`) is - // handled by the JSPromise.async, so we don't need to do anything here. + // The async return value is lowered by the generated `Promise_resolve_*` helper. return } @@ -328,25 +423,25 @@ public class ExportSwift { } } + /// A throwing async body needs an explicit closure type, otherwise Swift infers + /// `throws(any Error)` instead of `throws(JSException)`. + /// See: https://github.com/swiftlang/swift/issues/76165 + private func asyncThrowsClosureHead(returnSpelling: String?) -> String { + guard effects.isThrows else { return "" } + let returns = returnSpelling.map { " -> \($0)" } ?? "" + return " () async throws(JSException)\(returns) in" + } + func render(abiName: String) -> DeclSyntax { let body: CodeBlockItemListSyntax - if effects.isAsync { - // Explicit closure type annotation needed when throws is present - // so Swift infers throws(JSException) instead of throws(any Error) - // See: https://github.com/swiftlang/swift/issues/76165 - let closureHead: String - if effects.isThrows { - let hasReturn = self.body.contains { $0.description.contains("return ") } - let ret = hasReturn ? " -> JSValue" : "" - closureHead = " () async throws(JSException)\(ret) in" - } else { - closureHead = "" - } + if effects.isAsync, let resolveType = asyncResolveReturnType { + let resolveName = "Promise_resolve_\(resolveType.mangleTypeName)" + let closureHead = asyncThrowsClosureHead(returnSpelling: resolveType.swiftType) body = """ - let ret = JSPromise.async {\(raw: closureHead) + \(CodeBlockItemListSyntax(asyncHoistedBindings)) + return _bjs_makePromise(resolve: \(raw: resolveName), reject: Promise_reject) {\(raw: closureHead) \(CodeBlockItemListSyntax(self.body)) - }.jsObject - return ret.bridgeJSLowerReturn() + } """ } else if effects.isThrows { body = """ @@ -457,7 +552,10 @@ public class ExportSwift { let className = context.className let isStatic = context.isStatic - let getterBuilder = ExportedThunkBuilder(effects: Effects(isAsync: false, isThrows: false, isStatic: isStatic)) + let getterBuilder = try ExportedThunkBuilder( + effects: Effects(isAsync: false, isThrows: false, isStatic: isStatic), + returnType: property.type + ) if !isStatic { try getterBuilder.liftParameter( @@ -476,8 +574,9 @@ public class ExportSwift { // Generate property setter if not readonly if !property.isReadonly { - let setterBuilder = ExportedThunkBuilder( - effects: Effects(isAsync: false, isThrows: false, isStatic: isStatic) + let setterBuilder = try ExportedThunkBuilder( + effects: Effects(isAsync: false, isThrows: false, isStatic: isStatic), + returnType: .void ) // Lift parameters based on property type @@ -507,7 +606,7 @@ public class ExportSwift { } func renderSingleExportedFunction(function: ExportedFunction) throws -> DeclSyntax { - let builder = ExportedThunkBuilder(effects: function.effects) + let builder = try ExportedThunkBuilder(effects: function.effects, returnType: function.returnType) for param in function.parameters { try builder.liftParameter(param: param) } @@ -536,7 +635,7 @@ public class ExportSwift { callName: String, returnType: BridgeType ) throws -> DeclSyntax { - let builder = ExportedThunkBuilder(effects: constructor.effects) + let builder = try ExportedThunkBuilder(effects: constructor.effects, returnType: returnType) for param in constructor.parameters { try builder.liftParameter(param: param) } @@ -550,7 +649,7 @@ public class ExportSwift { ownerTypeName: String, instanceSelfType: BridgeType ) throws -> DeclSyntax { - let builder = ExportedThunkBuilder(effects: method.effects) + let builder = try ExportedThunkBuilder(effects: method.effects, returnType: method.returnType) if !method.effects.isStatic { try builder.liftParameter(param: Parameter(label: nil, name: "_self", type: instanceSelfType)) } diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index ce0ba0cb8..9a8442435 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -356,6 +356,40 @@ public struct BridgeJSLink { ] } + /// JS const (in the import glue scope) holding the `Symbol` under which a promise's + /// resolve/reject settlers are stashed. + private static let promiseSettlersSymbol = "__bjs_promiseSettlers" + + /// Renders a `bjs[...]` settlement handler that lifts `(promise, value)` and calls the + /// promise's stashed `resolve` / `reject` settler. + private func renderPromiseSettleHandler( + externName: String, + valueType: BridgeType, + settle: String, + into printer: CodeFragmentPrinter + ) throws { + let builder = ImportedThunkBuilder( + effects: Effects(isAsync: false, isThrows: true), + returnType: .void, + intrinsicRegistry: intrinsicRegistry + ) + try builder.liftParameter(param: Parameter(label: nil, name: "promise", type: .jsObject(nil))) + // `Void` can't cross the bridge as a parameter, so the void resolve settles with `undefined`. + let valueArg: String + if valueType == .void { + valueArg = "" + } else { + try builder.liftParameter(param: Parameter(label: nil, name: "value", type: valueType)) + valueArg = builder.parameterForwardings[1] + } + builder.body.write( + "\(builder.parameterForwardings[0])[\(Self.promiseSettlersSymbol)].\(settle)(\(valueArg));" + ) + var lines = builder.renderFunction(name: nil) + lines[0] = "bjs[\"\(externName)\"] = \(lines[0])" + printer.write(lines: lines) + } + private func generateAddImports(needsImportsObject: Bool) throws -> CodeFragmentPrinter { let printer = CodeFragmentPrinter() let allStructs = skeletons.compactMap { $0.exported?.structs }.flatMap { $0 } @@ -526,6 +560,39 @@ public struct BridgeJSLink { } } + // Always provided: the runtime's `_bjs_makePromise` imports it unconditionally. + // The settlers are stored under a Symbol to avoid clashing with promise fields. + printer.write("const \(Self.promiseSettlersSymbol) = Symbol(\"JavaScriptKit.promiseSettlers\");") + printer.write("bjs[\"swift_js_make_promise\"] = function() {") + printer.indent { + printer.write("let resolve, reject;") + printer.write("const promise = new Promise((res, rej) => { resolve = res; reject = rej; });") + printer.write("promise[\(Self.promiseSettlersSymbol)] = { resolve, reject };") + printer.write( + "return \(JSGlueVariableScope.reservedSwift).\(JSGlueVariableScope.reservedMemory).retain(promise);" + ) + } + printer.write("}") + for skeleton in skeletons { + guard let exported = skeleton.exported else { continue } + let asyncResolveTypes = exported.asyncPromiseResolveReturnTypes + guard !asyncResolveTypes.isEmpty else { continue } + for type in asyncResolveTypes { + try renderPromiseSettleHandler( + externName: "promise_resolve_\(skeleton.moduleName)_\(type.mangleTypeName)", + valueType: type, + settle: "resolve", + into: printer + ) + } + try renderPromiseSettleHandler( + externName: "promise_reject_\(skeleton.moduleName)", + valueType: .jsValue, + settle: "reject", + into: printer + ) + } + printer.write("bjs[\"swift_js_return_optional_bool\"] = function(isSome, value) {") printer.indent { printer.write("if (isSome === 0) {") diff --git a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift index 346b7333b..f1e2e80fe 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift @@ -1027,6 +1027,30 @@ public struct ExportedSkeleton: Codable { public var isEmpty: Bool { functions.isEmpty && classes.isEmpty && enums.isEmpty && structs.isEmpty && protocols.isEmpty } + + /// Distinct `async` return types needing a `Promise_resolve_` helper, deduplicated + /// by mangled name. Shared by the Swift codegen and JS link. + public var asyncPromiseResolveReturnTypes: [BridgeType] { + var seen = Set() + var result: [BridgeType] = [] + func consider(_ returnType: BridgeType, _ effects: Effects) { + guard effects.isAsync, returnType.isAsyncResolvable, + seen.insert(returnType.mangleTypeName).inserted + else { return } + result.append(returnType) + } + for function in functions { consider(function.returnType, function.effects) } + for klass in classes { + for method in klass.methods { consider(method.returnType, method.effects) } + } + for structDef in structs { + for method in structDef.methods { consider(method.returnType, method.effects) } + } + for enumDef in enums { + for method in enumDef.staticMethods { consider(method.returnType, method.effects) } + } + return result + } } // MARK: - Imported Skeleton @@ -1584,6 +1608,25 @@ extension BridgeType { return false } + /// Whether a value of this type can be passed to a generated `Promise_resolve_` + /// settlement helper, i.e. lowered through the imported-parameter ABI. Every `async` + /// exported return settles through `_bjs_makePromise`; the few types that cannot be lowered + /// (associated-value enums, protocols, namespace enums, and their compositions) are diagnosed. + public var isAsyncResolvable: Bool { + switch self { + case .associatedValueEnum, .swiftProtocol, .namespaceEnum: + return false + case .nullable(let wrapped, _): + return wrapped.isAsyncResolvable + case .array(let element): + return element.isAsyncResolvable + case .dictionary(let value): + return value.isAsyncResolvable + default: + return true + } + } + /// Simplified Swift ABI-style mangled name /// https://github.com/swiftlang/swift/blob/main/docs/ABI/Mangling.rst#types public var mangleTypeName: String { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift index e71a1f84e..82747f74e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift @@ -305,6 +305,56 @@ import Testing #expect(skeleton.exported != nil) } + // MARK: - Async return validation + + @Test + func asyncReturnOfUnsupportedTypeIsDiagnosed() throws { + // An associated-value enum can be neither lowered through the imported-parameter ABI + // nor settled via `_bjs_makePromise`, so an async return of one must be diagnosed. + let source = """ + @JS enum Payload { + case text(String) + case number(Int) + } + @JS func loadPayload() async -> Payload { + .number(1) + } + """ + let swiftAPI = SwiftToSkeleton( + progress: .silent, + moduleName: "TestModule", + exposeToGlobal: false, + externalModuleIndex: .empty + ) + swiftAPI.addSourceFile(Parser.parse(source: source), inputFilePath: "test.swift") + let skeleton = try swiftAPI.finalize() + let exported = try #require(skeleton.exported) + let exportSwift = ExportSwift(progress: .silent, moduleName: skeleton.moduleName, skeleton: exported) + #expect(throws: BridgeJSCoreError.self) { + _ = try exportSwift.finalize() + } + } + + @Test + func asyncReturnOfConvertibleTypeSucceeds() throws { + let source = """ + @JS func loadCount() async -> Int { + 1 + } + """ + let swiftAPI = SwiftToSkeleton( + progress: .silent, + moduleName: "TestModule", + exposeToGlobal: false, + externalModuleIndex: .empty + ) + swiftAPI.addSourceFile(Parser.parse(source: source), inputFilePath: "test.swift") + let skeleton = try swiftAPI.finalize() + let exported = try #require(skeleton.exported) + let exportSwift = ExportSwift(progress: .silent, moduleName: skeleton.moduleName, skeleton: exported) + #expect(try exportSwift.finalize() != nil) + } + @Test func omitsNextLineWhenErrorIsOnLastLine() throws { let source = """ diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Async.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Async.swift index 214331b32..e63bea4ca 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Async.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Async.swift @@ -17,3 +17,66 @@ @JS func asyncRoundTripJSObject(_ v: JSObject) async -> JSObject { return v } + +@JS struct AsyncPoint { + var x: Int + var y: Int +} + +@JS func asyncRoundTripStruct(_ v: AsyncPoint) async -> AsyncPoint { + return v +} + +@JS func asyncRoundTripStructThrows(_ v: AsyncPoint) async throws(JSException) -> AsyncPoint { + return v +} + +@JS func asyncCombineStructs(_ a: AsyncPoint, _ b: AsyncPoint) async -> AsyncPoint { + return AsyncPoint(x: a.x + b.x, y: a.y + b.y) +} + +@JS enum AsyncDirection { + case north + case south +} + +@JS func asyncRoundTripEnum(_ v: AsyncDirection) async -> AsyncDirection { + return v +} + +@JS enum AsyncTheme: String { + case light + case dark +} + +@JS func asyncRoundTripRawEnum(_ v: AsyncTheme) async -> AsyncTheme { + return v +} + +@JS func asyncRoundTripOptionalEnum(_ v: AsyncDirection?) async -> AsyncDirection? { + return v +} + +@JS func asyncRoundTripOptionalRawEnum(_ v: AsyncTheme?) async -> AsyncTheme? { + return v +} + +@JS func asyncRoundTripOptionalStruct(_ v: AsyncPoint?) async -> AsyncPoint? { + return v +} + +@JS func asyncRoundTripStructArray(_ v: [AsyncPoint]) async -> [AsyncPoint] { + return v +} + +@JS func asyncRoundTripEnumArray(_ v: [AsyncDirection]) async -> [AsyncDirection] { + return v +} + +@JS func asyncRoundTripStructDictionary(_ v: [String: AsyncPoint]) async -> [String: AsyncPoint] { + return v +} + +@JS func asyncRoundTripEnumDictionary(_ v: [String: AsyncDirection]) async -> [String: AsyncDirection] { + return v +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.json index 27ba89aca..3bd594419 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.json @@ -4,7 +4,59 @@ ], "enums" : [ + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "north" + }, + { + "associatedValues" : [ + + ], + "name" : "south" + } + ], + "emitStyle" : "const", + "name" : "AsyncDirection", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "AsyncDirection", + "tsFullPath" : "AsyncDirection" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "light" + }, + { + "associatedValues" : [ + ], + "name" : "dark" + } + ], + "emitStyle" : "const", + "name" : "AsyncTheme", + "rawType" : "String", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "AsyncTheme", + "tsFullPath" : "AsyncTheme" + } ], "exposeToGlobal" : false, "functions" : [ @@ -180,13 +232,422 @@ } } + }, + { + "abiName" : "bjs_asyncRoundTripStruct", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncRoundTripStruct", + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "swiftStruct" : { + "_0" : "AsyncPoint" + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "AsyncPoint" + } + } + }, + { + "abiName" : "bjs_asyncRoundTripStructThrows", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "asyncRoundTripStructThrows", + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "swiftStruct" : { + "_0" : "AsyncPoint" + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "AsyncPoint" + } + } + }, + { + "abiName" : "bjs_asyncCombineStructs", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncCombineStructs", + "parameters" : [ + { + "label" : "_", + "name" : "a", + "type" : { + "swiftStruct" : { + "_0" : "AsyncPoint" + } + } + }, + { + "label" : "_", + "name" : "b", + "type" : { + "swiftStruct" : { + "_0" : "AsyncPoint" + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "AsyncPoint" + } + } + }, + { + "abiName" : "bjs_asyncRoundTripEnum", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncRoundTripEnum", + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "caseEnum" : { + "_0" : "AsyncDirection" + } + } + } + ], + "returnType" : { + "caseEnum" : { + "_0" : "AsyncDirection" + } + } + }, + { + "abiName" : "bjs_asyncRoundTripRawEnum", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncRoundTripRawEnum", + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "rawValueEnum" : { + "_0" : "AsyncTheme", + "_1" : "String" + } + } + } + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "AsyncTheme", + "_1" : "String" + } + } + }, + { + "abiName" : "bjs_asyncRoundTripOptionalEnum", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncRoundTripOptionalEnum", + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "AsyncDirection" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "AsyncDirection" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_asyncRoundTripOptionalRawEnum", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncRoundTripOptionalRawEnum", + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "AsyncTheme", + "_1" : "String" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "AsyncTheme", + "_1" : "String" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_asyncRoundTripOptionalStruct", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncRoundTripOptionalStruct", + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "AsyncPoint" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "AsyncPoint" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_asyncRoundTripStructArray", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncRoundTripStructArray", + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "swiftStruct" : { + "_0" : "AsyncPoint" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "swiftStruct" : { + "_0" : "AsyncPoint" + } + } + } + } + }, + { + "abiName" : "bjs_asyncRoundTripEnumArray", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncRoundTripEnumArray", + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "caseEnum" : { + "_0" : "AsyncDirection" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "caseEnum" : { + "_0" : "AsyncDirection" + } + } + } + } + }, + { + "abiName" : "bjs_asyncRoundTripStructDictionary", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncRoundTripStructDictionary", + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "dictionary" : { + "_0" : { + "swiftStruct" : { + "_0" : "AsyncPoint" + } + } + } + } + } + ], + "returnType" : { + "dictionary" : { + "_0" : { + "swiftStruct" : { + "_0" : "AsyncPoint" + } + } + } + } + }, + { + "abiName" : "bjs_asyncRoundTripEnumDictionary", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncRoundTripEnumDictionary", + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "dictionary" : { + "_0" : { + "caseEnum" : { + "_0" : "AsyncDirection" + } + } + } + } + } + ], + "returnType" : { + "dictionary" : { + "_0" : { + "caseEnum" : { + "_0" : "AsyncDirection" + } + } + } + } } ], "protocols" : [ ], "structs" : [ + { + "methods" : [ + ], + "name" : "AsyncPoint", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "x", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "y", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "swiftCallName" : "AsyncPoint" + } ] }, "moduleName" : "TestModule", diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift index f5230f213..28e6d8d8f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift @@ -1,11 +1,96 @@ +extension AsyncDirection: _BridgedSwiftCaseEnum { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + return bridgeJSRawValue + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> AsyncDirection { + return bridgeJSLiftParameter(value) + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> AsyncDirection { + return AsyncDirection(bridgeJSRawValue: value)! + } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { + return bridgeJSLowerParameter() + } + + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { + switch bridgeJSRawValue { + case 0: + self = .north + case 1: + self = .south + default: + return nil + } + } + + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { + switch self { + case .north: + return 0 + case .south: + return 1 + } + } +} + +extension AsyncTheme: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +} + +extension AsyncPoint: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> AsyncPoint { + let y = Int.bridgeJSStackPop() + let x = Int.bridgeJSStackPop() + return AsyncPoint(x: x, y: y) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.x.bridgeJSStackPush() + self.y.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_AsyncPoint(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_AsyncPoint())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_AsyncPoint") +fileprivate func _bjs_struct_lower_AsyncPoint_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_AsyncPoint_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_AsyncPoint(_ objectId: Int32) -> Void { + return _bjs_struct_lower_AsyncPoint_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_AsyncPoint") +fileprivate func _bjs_struct_lift_AsyncPoint_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_AsyncPoint_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_AsyncPoint() -> Int32 { + return _bjs_struct_lift_AsyncPoint_extern() +} + @_expose(wasm, "bjs_asyncReturnVoid") @_cdecl("bjs_asyncReturnVoid") public func _bjs_asyncReturnVoid() -> Int32 { #if arch(wasm32) - let ret = JSPromise.async { + return _bjs_makePromise(resolve: Promise_resolve_y, reject: Promise_reject) { await asyncReturnVoid() - }.jsObject - return ret.bridgeJSLowerReturn() + } #else fatalError("Only available on WebAssembly") #endif @@ -15,10 +100,9 @@ public func _bjs_asyncReturnVoid() -> Int32 { @_cdecl("bjs_asyncRoundTripInt") public func _bjs_asyncRoundTripInt(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = JSPromise.async { - return await asyncRoundTripInt(_: Int.bridgeJSLiftParameter(v)).jsValue - }.jsObject - return ret.bridgeJSLowerReturn() + return _bjs_makePromise(resolve: Promise_resolve_Si, reject: Promise_reject) { + return await asyncRoundTripInt(_: Int.bridgeJSLiftParameter(v)) + } #else fatalError("Only available on WebAssembly") #endif @@ -28,10 +112,9 @@ public func _bjs_asyncRoundTripInt(_ v: Int32) -> Int32 { @_cdecl("bjs_asyncRoundTripString") public func _bjs_asyncRoundTripString(_ vBytes: Int32, _ vLength: Int32) -> Int32 { #if arch(wasm32) - let ret = JSPromise.async { - return await asyncRoundTripString(_: String.bridgeJSLiftParameter(vBytes, vLength)).jsValue - }.jsObject - return ret.bridgeJSLowerReturn() + return _bjs_makePromise(resolve: Promise_resolve_SS, reject: Promise_reject) { + return await asyncRoundTripString(_: String.bridgeJSLiftParameter(vBytes, vLength)) + } #else fatalError("Only available on WebAssembly") #endif @@ -41,10 +124,9 @@ public func _bjs_asyncRoundTripString(_ vBytes: Int32, _ vLength: Int32) -> Int3 @_cdecl("bjs_asyncRoundTripBool") public func _bjs_asyncRoundTripBool(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = JSPromise.async { - return await asyncRoundTripBool(_: Bool.bridgeJSLiftParameter(v)).jsValue - }.jsObject - return ret.bridgeJSLowerReturn() + return _bjs_makePromise(resolve: Promise_resolve_Sb, reject: Promise_reject) { + return await asyncRoundTripBool(_: Bool.bridgeJSLiftParameter(v)) + } #else fatalError("Only available on WebAssembly") #endif @@ -54,10 +136,9 @@ public func _bjs_asyncRoundTripBool(_ v: Int32) -> Int32 { @_cdecl("bjs_asyncRoundTripFloat") public func _bjs_asyncRoundTripFloat(_ v: Float32) -> Int32 { #if arch(wasm32) - let ret = JSPromise.async { - return await asyncRoundTripFloat(_: Float.bridgeJSLiftParameter(v)).jsValue - }.jsObject - return ret.bridgeJSLowerReturn() + return _bjs_makePromise(resolve: Promise_resolve_Sf, reject: Promise_reject) { + return await asyncRoundTripFloat(_: Float.bridgeJSLiftParameter(v)) + } #else fatalError("Only available on WebAssembly") #endif @@ -67,10 +148,9 @@ public func _bjs_asyncRoundTripFloat(_ v: Float32) -> Int32 { @_cdecl("bjs_asyncRoundTripDouble") public func _bjs_asyncRoundTripDouble(_ v: Float64) -> Int32 { #if arch(wasm32) - let ret = JSPromise.async { - return await asyncRoundTripDouble(_: Double.bridgeJSLiftParameter(v)).jsValue - }.jsObject - return ret.bridgeJSLowerReturn() + return _bjs_makePromise(resolve: Promise_resolve_Sd, reject: Promise_reject) { + return await asyncRoundTripDouble(_: Double.bridgeJSLiftParameter(v)) + } #else fatalError("Only available on WebAssembly") #endif @@ -80,11 +160,543 @@ public func _bjs_asyncRoundTripDouble(_ v: Float64) -> Int32 { @_cdecl("bjs_asyncRoundTripJSObject") public func _bjs_asyncRoundTripJSObject(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = JSPromise.async { - return await asyncRoundTripJSObject(_: JSObject.bridgeJSLiftParameter(v)).jsValue - }.jsObject - return ret.bridgeJSLowerReturn() + return _bjs_makePromise(resolve: Promise_resolve_8JSObjectC, reject: Promise_reject) { + return await asyncRoundTripJSObject(_: JSObject.bridgeJSLiftParameter(v)) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_asyncRoundTripStruct") +@_cdecl("bjs_asyncRoundTripStruct") +public func _bjs_asyncRoundTripStruct() -> Int32 { + #if arch(wasm32) + let _tmp_v = AsyncPoint.bridgeJSLiftParameter() + return _bjs_makePromise(resolve: Promise_resolve_10AsyncPointV, reject: Promise_reject) { + return await asyncRoundTripStruct(_: _tmp_v) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_asyncRoundTripStructThrows") +@_cdecl("bjs_asyncRoundTripStructThrows") +public func _bjs_asyncRoundTripStructThrows() -> Int32 { + #if arch(wasm32) + let _tmp_v = AsyncPoint.bridgeJSLiftParameter() + return _bjs_makePromise(resolve: Promise_resolve_10AsyncPointV, reject: Promise_reject) { () async throws(JSException) -> AsyncPoint in + return try await asyncRoundTripStructThrows(_: _tmp_v) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_asyncCombineStructs") +@_cdecl("bjs_asyncCombineStructs") +public func _bjs_asyncCombineStructs() -> Int32 { + #if arch(wasm32) + let _tmp_b = AsyncPoint.bridgeJSLiftParameter() + let _tmp_a = AsyncPoint.bridgeJSLiftParameter() + return _bjs_makePromise(resolve: Promise_resolve_10AsyncPointV, reject: Promise_reject) { + return await asyncCombineStructs(_: _tmp_a, _: _tmp_b) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_asyncRoundTripEnum") +@_cdecl("bjs_asyncRoundTripEnum") +public func _bjs_asyncRoundTripEnum(_ v: Int32) -> Int32 { + #if arch(wasm32) + return _bjs_makePromise(resolve: Promise_resolve_14AsyncDirectionO, reject: Promise_reject) { + return await asyncRoundTripEnum(_: AsyncDirection.bridgeJSLiftParameter(v)) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_asyncRoundTripRawEnum") +@_cdecl("bjs_asyncRoundTripRawEnum") +public func _bjs_asyncRoundTripRawEnum(_ vBytes: Int32, _ vLength: Int32) -> Int32 { + #if arch(wasm32) + return _bjs_makePromise(resolve: Promise_resolve_10AsyncThemeO, reject: Promise_reject) { + return await asyncRoundTripRawEnum(_: AsyncTheme.bridgeJSLiftParameter(vBytes, vLength)) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_asyncRoundTripOptionalEnum") +@_cdecl("bjs_asyncRoundTripOptionalEnum") +public func _bjs_asyncRoundTripOptionalEnum(_ vIsSome: Int32, _ vValue: Int32) -> Int32 { + #if arch(wasm32) + return _bjs_makePromise(resolve: Promise_resolve_Sq14AsyncDirectionO, reject: Promise_reject) { + return await asyncRoundTripOptionalEnum(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) + } #else fatalError("Only available on WebAssembly") #endif +} + +@_expose(wasm, "bjs_asyncRoundTripOptionalRawEnum") +@_cdecl("bjs_asyncRoundTripOptionalRawEnum") +public func _bjs_asyncRoundTripOptionalRawEnum(_ vIsSome: Int32, _ vBytes: Int32, _ vLength: Int32) -> Int32 { + #if arch(wasm32) + return _bjs_makePromise(resolve: Promise_resolve_Sq10AsyncThemeO, reject: Promise_reject) { + return await asyncRoundTripOptionalRawEnum(_: Optional.bridgeJSLiftParameter(vIsSome, vBytes, vLength)) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_asyncRoundTripOptionalStruct") +@_cdecl("bjs_asyncRoundTripOptionalStruct") +public func _bjs_asyncRoundTripOptionalStruct() -> Int32 { + #if arch(wasm32) + let _tmp_v = Optional.bridgeJSLiftParameter() + return _bjs_makePromise(resolve: Promise_resolve_Sq10AsyncPointV, reject: Promise_reject) { + return await asyncRoundTripOptionalStruct(_: _tmp_v) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_asyncRoundTripStructArray") +@_cdecl("bjs_asyncRoundTripStructArray") +public func _bjs_asyncRoundTripStructArray() -> Int32 { + #if arch(wasm32) + let _tmp_v = [AsyncPoint].bridgeJSStackPop() + return _bjs_makePromise(resolve: Promise_resolve_Sa10AsyncPointV, reject: Promise_reject) { + return await asyncRoundTripStructArray(_: _tmp_v) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_asyncRoundTripEnumArray") +@_cdecl("bjs_asyncRoundTripEnumArray") +public func _bjs_asyncRoundTripEnumArray() -> Int32 { + #if arch(wasm32) + let _tmp_v = [AsyncDirection].bridgeJSStackPop() + return _bjs_makePromise(resolve: Promise_resolve_Sa14AsyncDirectionO, reject: Promise_reject) { + return await asyncRoundTripEnumArray(_: _tmp_v) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_asyncRoundTripStructDictionary") +@_cdecl("bjs_asyncRoundTripStructDictionary") +public func _bjs_asyncRoundTripStructDictionary() -> Int32 { + #if arch(wasm32) + let _tmp_v = [String: AsyncPoint].bridgeJSLiftParameter() + return _bjs_makePromise(resolve: Promise_resolve_SD10AsyncPointV, reject: Promise_reject) { + return await asyncRoundTripStructDictionary(_: _tmp_v) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_asyncRoundTripEnumDictionary") +@_cdecl("bjs_asyncRoundTripEnumDictionary") +public func _bjs_asyncRoundTripEnumDictionary() -> Int32 { + #if arch(wasm32) + let _tmp_v = [String: AsyncDirection].bridgeJSLiftParameter() + return _bjs_makePromise(resolve: Promise_resolve_SD14AsyncDirectionO, reject: Promise_reject) { + return await asyncRoundTripEnumDictionary(_: _tmp_v) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@JSFunction func Promise_reject(_ promise: JSObject, _ value: JSValue) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_reject_TestModule") +fileprivate func promise_reject_TestModule_extern(_ promise: Int32, _ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void +#else +fileprivate func promise_reject_TestModule_extern(_ promise: Int32, _ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_reject_TestModule(_ promise: Int32, _ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void { + return promise_reject_TestModule_extern(promise, valueKind, valuePayload1, valuePayload2) +} + +func _$Promise_reject(_ promise: JSObject, _ value: JSValue) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let (valueKind, valuePayload1, valuePayload2) = value.bridgeJSLowerParameter() + promise_reject_TestModule(promiseValue, valueKind, valuePayload1, valuePayload2) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_y(_ promise: JSObject) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_TestModule_y") +fileprivate func promise_resolve_TestModule_y_extern(_ promise: Int32) -> Void +#else +fileprivate func promise_resolve_TestModule_y_extern(_ promise: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_TestModule_y(_ promise: Int32) -> Void { + return promise_resolve_TestModule_y_extern(promise) +} + +func _$Promise_resolve_y(_ promise: JSObject) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + promise_resolve_TestModule_y(promiseValue) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_Si(_ promise: JSObject, _ value: Int) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_TestModule_Si") +fileprivate func promise_resolve_TestModule_Si_extern(_ promise: Int32, _ value: Int32) -> Void +#else +fileprivate func promise_resolve_TestModule_Si_extern(_ promise: Int32, _ value: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_TestModule_Si(_ promise: Int32, _ value: Int32) -> Void { + return promise_resolve_TestModule_Si_extern(promise, value) +} + +func _$Promise_resolve_Si(_ promise: JSObject, _ value: Int) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueValue = value.bridgeJSLowerParameter() + promise_resolve_TestModule_Si(promiseValue, valueValue) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_SS(_ promise: JSObject, _ value: String) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_TestModule_SS") +fileprivate func promise_resolve_TestModule_SS_extern(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void +#else +fileprivate func promise_resolve_TestModule_SS_extern(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_TestModule_SS(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + return promise_resolve_TestModule_SS_extern(promise, valueBytes, valueLength) +} + +func _$Promise_resolve_SS(_ promise: JSObject, _ value: String) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + value.bridgeJSWithLoweredParameter { (valueBytes, valueLength) in + promise_resolve_TestModule_SS(promiseValue, valueBytes, valueLength) + } + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_Sb(_ promise: JSObject, _ value: Bool) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_TestModule_Sb") +fileprivate func promise_resolve_TestModule_Sb_extern(_ promise: Int32, _ value: Int32) -> Void +#else +fileprivate func promise_resolve_TestModule_Sb_extern(_ promise: Int32, _ value: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_TestModule_Sb(_ promise: Int32, _ value: Int32) -> Void { + return promise_resolve_TestModule_Sb_extern(promise, value) +} + +func _$Promise_resolve_Sb(_ promise: JSObject, _ value: Bool) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueValue = value.bridgeJSLowerParameter() + promise_resolve_TestModule_Sb(promiseValue, valueValue) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_Sf(_ promise: JSObject, _ value: Float) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_TestModule_Sf") +fileprivate func promise_resolve_TestModule_Sf_extern(_ promise: Int32, _ value: Float32) -> Void +#else +fileprivate func promise_resolve_TestModule_Sf_extern(_ promise: Int32, _ value: Float32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_TestModule_Sf(_ promise: Int32, _ value: Float32) -> Void { + return promise_resolve_TestModule_Sf_extern(promise, value) +} + +func _$Promise_resolve_Sf(_ promise: JSObject, _ value: Float) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueValue = value.bridgeJSLowerParameter() + promise_resolve_TestModule_Sf(promiseValue, valueValue) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_Sd(_ promise: JSObject, _ value: Double) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_TestModule_Sd") +fileprivate func promise_resolve_TestModule_Sd_extern(_ promise: Int32, _ value: Float64) -> Void +#else +fileprivate func promise_resolve_TestModule_Sd_extern(_ promise: Int32, _ value: Float64) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_TestModule_Sd(_ promise: Int32, _ value: Float64) -> Void { + return promise_resolve_TestModule_Sd_extern(promise, value) +} + +func _$Promise_resolve_Sd(_ promise: JSObject, _ value: Double) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueValue = value.bridgeJSLowerParameter() + promise_resolve_TestModule_Sd(promiseValue, valueValue) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_8JSObjectC(_ promise: JSObject, _ value: JSObject) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_TestModule_8JSObjectC") +fileprivate func promise_resolve_TestModule_8JSObjectC_extern(_ promise: Int32, _ value: Int32) -> Void +#else +fileprivate func promise_resolve_TestModule_8JSObjectC_extern(_ promise: Int32, _ value: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_TestModule_8JSObjectC(_ promise: Int32, _ value: Int32) -> Void { + return promise_resolve_TestModule_8JSObjectC_extern(promise, value) +} + +func _$Promise_resolve_8JSObjectC(_ promise: JSObject, _ value: JSObject) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueValue = value.bridgeJSLowerParameter() + promise_resolve_TestModule_8JSObjectC(promiseValue, valueValue) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_10AsyncPointV(_ promise: JSObject, _ value: AsyncPoint) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_TestModule_10AsyncPointV") +fileprivate func promise_resolve_TestModule_10AsyncPointV_extern(_ promise: Int32, _ value: Int32) -> Void +#else +fileprivate func promise_resolve_TestModule_10AsyncPointV_extern(_ promise: Int32, _ value: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_TestModule_10AsyncPointV(_ promise: Int32, _ value: Int32) -> Void { + return promise_resolve_TestModule_10AsyncPointV_extern(promise, value) +} + +func _$Promise_resolve_10AsyncPointV(_ promise: JSObject, _ value: AsyncPoint) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueObjectId = value.bridgeJSLowerParameter() + promise_resolve_TestModule_10AsyncPointV(promiseValue, valueObjectId) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_14AsyncDirectionO(_ promise: JSObject, _ value: AsyncDirection) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_TestModule_14AsyncDirectionO") +fileprivate func promise_resolve_TestModule_14AsyncDirectionO_extern(_ promise: Int32, _ value: Int32) -> Void +#else +fileprivate func promise_resolve_TestModule_14AsyncDirectionO_extern(_ promise: Int32, _ value: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_TestModule_14AsyncDirectionO(_ promise: Int32, _ value: Int32) -> Void { + return promise_resolve_TestModule_14AsyncDirectionO_extern(promise, value) +} + +func _$Promise_resolve_14AsyncDirectionO(_ promise: JSObject, _ value: AsyncDirection) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueValue = value.bridgeJSLowerParameter() + promise_resolve_TestModule_14AsyncDirectionO(promiseValue, valueValue) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_10AsyncThemeO(_ promise: JSObject, _ value: AsyncTheme) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_TestModule_10AsyncThemeO") +fileprivate func promise_resolve_TestModule_10AsyncThemeO_extern(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void +#else +fileprivate func promise_resolve_TestModule_10AsyncThemeO_extern(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_TestModule_10AsyncThemeO(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + return promise_resolve_TestModule_10AsyncThemeO_extern(promise, valueBytes, valueLength) +} + +func _$Promise_resolve_10AsyncThemeO(_ promise: JSObject, _ value: AsyncTheme) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + value.bridgeJSWithLoweredParameter { (valueBytes, valueLength) in + promise_resolve_TestModule_10AsyncThemeO(promiseValue, valueBytes, valueLength) + } + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_Sq14AsyncDirectionO(_ promise: JSObject, _ value: Optional) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_TestModule_Sq14AsyncDirectionO") +fileprivate func promise_resolve_TestModule_Sq14AsyncDirectionO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Void +#else +fileprivate func promise_resolve_TestModule_Sq14AsyncDirectionO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_TestModule_Sq14AsyncDirectionO(_ promise: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { + return promise_resolve_TestModule_Sq14AsyncDirectionO_extern(promise, valueIsSome, valueValue) +} + +func _$Promise_resolve_Sq14AsyncDirectionO(_ promise: JSObject, _ value: Optional) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let (valueIsSome, valueValue) = value.bridgeJSLowerParameter() + promise_resolve_TestModule_Sq14AsyncDirectionO(promiseValue, valueIsSome, valueValue) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_Sq10AsyncThemeO(_ promise: JSObject, _ value: Optional) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_TestModule_Sq10AsyncThemeO") +fileprivate func promise_resolve_TestModule_Sq10AsyncThemeO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void +#else +fileprivate func promise_resolve_TestModule_Sq10AsyncThemeO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_TestModule_Sq10AsyncThemeO(_ promise: Int32, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + return promise_resolve_TestModule_Sq10AsyncThemeO_extern(promise, valueIsSome, valueBytes, valueLength) +} + +func _$Promise_resolve_Sq10AsyncThemeO(_ promise: JSObject, _ value: Optional) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + value.bridgeJSWithLoweredParameter { (valueIsSome, valueBytes, valueLength) in + promise_resolve_TestModule_Sq10AsyncThemeO(promiseValue, valueIsSome, valueBytes, valueLength) + } + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_Sq10AsyncPointV(_ promise: JSObject, _ value: Optional) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_TestModule_Sq10AsyncPointV") +fileprivate func promise_resolve_TestModule_Sq10AsyncPointV_extern(_ promise: Int32, _ value: Int32) -> Void +#else +fileprivate func promise_resolve_TestModule_Sq10AsyncPointV_extern(_ promise: Int32, _ value: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_TestModule_Sq10AsyncPointV(_ promise: Int32, _ value: Int32) -> Void { + return promise_resolve_TestModule_Sq10AsyncPointV_extern(promise, value) +} + +func _$Promise_resolve_Sq10AsyncPointV(_ promise: JSObject, _ value: Optional) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueIsSome = value.bridgeJSLowerParameter() + promise_resolve_TestModule_Sq10AsyncPointV(promiseValue, valueIsSome) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_Sa10AsyncPointV(_ promise: JSObject, _ value: [AsyncPoint]) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_TestModule_Sa10AsyncPointV") +fileprivate func promise_resolve_TestModule_Sa10AsyncPointV_extern(_ promise: Int32) -> Void +#else +fileprivate func promise_resolve_TestModule_Sa10AsyncPointV_extern(_ promise: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_TestModule_Sa10AsyncPointV(_ promise: Int32) -> Void { + return promise_resolve_TestModule_Sa10AsyncPointV_extern(promise) +} + +func _$Promise_resolve_Sa10AsyncPointV(_ promise: JSObject, _ value: [AsyncPoint]) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let _ = value.bridgeJSLowerParameter() + promise_resolve_TestModule_Sa10AsyncPointV(promiseValue) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_Sa14AsyncDirectionO(_ promise: JSObject, _ value: [AsyncDirection]) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_TestModule_Sa14AsyncDirectionO") +fileprivate func promise_resolve_TestModule_Sa14AsyncDirectionO_extern(_ promise: Int32) -> Void +#else +fileprivate func promise_resolve_TestModule_Sa14AsyncDirectionO_extern(_ promise: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_TestModule_Sa14AsyncDirectionO(_ promise: Int32) -> Void { + return promise_resolve_TestModule_Sa14AsyncDirectionO_extern(promise) +} + +func _$Promise_resolve_Sa14AsyncDirectionO(_ promise: JSObject, _ value: [AsyncDirection]) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let _ = value.bridgeJSLowerParameter() + promise_resolve_TestModule_Sa14AsyncDirectionO(promiseValue) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_SD10AsyncPointV(_ promise: JSObject, _ value: [String: AsyncPoint]) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_TestModule_SD10AsyncPointV") +fileprivate func promise_resolve_TestModule_SD10AsyncPointV_extern(_ promise: Int32) -> Void +#else +fileprivate func promise_resolve_TestModule_SD10AsyncPointV_extern(_ promise: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_TestModule_SD10AsyncPointV(_ promise: Int32) -> Void { + return promise_resolve_TestModule_SD10AsyncPointV_extern(promise) +} + +func _$Promise_resolve_SD10AsyncPointV(_ promise: JSObject, _ value: [String: AsyncPoint]) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let _ = value.bridgeJSLowerParameter() + promise_resolve_TestModule_SD10AsyncPointV(promiseValue) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_SD14AsyncDirectionO(_ promise: JSObject, _ value: [String: AsyncDirection]) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_TestModule_SD14AsyncDirectionO") +fileprivate func promise_resolve_TestModule_SD14AsyncDirectionO_extern(_ promise: Int32) -> Void +#else +fileprivate func promise_resolve_TestModule_SD14AsyncDirectionO_extern(_ promise: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_TestModule_SD14AsyncDirectionO(_ promise: Int32) -> Void { + return promise_resolve_TestModule_SD14AsyncDirectionO_extern(promise) +} + +func _$Promise_resolve_SD14AsyncDirectionO(_ promise: JSObject, _ value: [String: AsyncDirection]) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let _ = value.bridgeJSLowerParameter() + promise_resolve_TestModule_SD14AsyncDirectionO(promiseValue) + if let error = _swift_js_take_exception() { throw error } } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js index ad0111929..75d961e98 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js @@ -138,6 +138,13 @@ export async function createInstantiator(options, swift) { const value = structHelpers.Point.lift(); return swift.memory.retain(value); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.d.ts index aecab090e..ddf722a3a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.d.ts @@ -4,6 +4,26 @@ // To update this file, just rebuild your project or run // `swift package bridge-js`. +export const AsyncDirectionValues: { + readonly North: 0; + readonly South: 1; +}; +export type AsyncDirectionTag = typeof AsyncDirectionValues[keyof typeof AsyncDirectionValues]; + +export const AsyncThemeValues: { + readonly Light: "light"; + readonly Dark: "dark"; +}; +export type AsyncThemeTag = typeof AsyncThemeValues[keyof typeof AsyncThemeValues]; + +export interface AsyncPoint { + x: number; + y: number; +} +export type AsyncDirectionObject = typeof AsyncDirectionValues; + +export type AsyncThemeObject = typeof AsyncThemeValues; + export type Exports = { asyncReturnVoid(): Promise; asyncRoundTripInt(v: number): Promise; @@ -12,6 +32,20 @@ export type Exports = { asyncRoundTripFloat(v: number): Promise; asyncRoundTripDouble(v: number): Promise; asyncRoundTripJSObject(v: any): Promise; + asyncRoundTripStruct(v: AsyncPoint): Promise; + asyncRoundTripStructThrows(v: AsyncPoint): Promise; + asyncCombineStructs(a: AsyncPoint, b: AsyncPoint): Promise; + asyncRoundTripEnum(v: AsyncDirectionTag): Promise; + asyncRoundTripRawEnum(v: AsyncThemeTag): Promise; + asyncRoundTripOptionalEnum(v: AsyncDirectionTag | null): Promise; + asyncRoundTripOptionalRawEnum(v: AsyncThemeTag | null): Promise; + asyncRoundTripOptionalStruct(v: AsyncPoint | null): Promise; + asyncRoundTripStructArray(v: AsyncPoint[]): Promise; + asyncRoundTripEnumArray(v: AsyncDirectionTag[]): Promise; + asyncRoundTripStructDictionary(v: Record): Promise>; + asyncRoundTripEnumDictionary(v: Record): Promise>; + AsyncDirection: AsyncDirectionObject + AsyncTheme: AsyncThemeObject } export type Imports = { } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js index a4c42674e..887102a76 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js @@ -4,6 +4,16 @@ // To update this file, just rebuild your project or run // `swift package bridge-js`. +export const AsyncDirectionValues = { + North: 0, + South: 1, +}; + +export const AsyncThemeValues = { + Light: "light", + Dark: "dark", +}; + export async function createInstantiator(options, swift) { let instance; let memory; @@ -31,6 +41,106 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + function __bjs_jsValueLower(value) { + let kind; + let payload1; + let payload2; + if (value === null) { + kind = 4; + payload1 = 0; + payload2 = 0; + } else { + switch (typeof value) { + case "boolean": + kind = 0; + payload1 = value ? 1 : 0; + payload2 = 0; + break; + case "number": + kind = 2; + payload1 = 0; + payload2 = value; + break; + case "string": + kind = 1; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "undefined": + kind = 5; + payload1 = 0; + payload2 = 0; + break; + case "object": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "function": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "symbol": + kind = 7; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "bigint": + kind = 8; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + default: + throw new TypeError("Unsupported JSValue type"); + } + } + return [kind, payload1, payload2]; + } + function __bjs_jsValueLift(kind, payload1, payload2) { + let jsValue; + switch (kind) { + case 0: + jsValue = payload1 !== 0; + break; + case 1: + jsValue = swift.memory.getObject(payload1); + break; + case 2: + jsValue = payload2; + break; + case 3: + jsValue = swift.memory.getObject(payload1); + break; + case 4: + jsValue = null; + break; + case 5: + jsValue = undefined; + break; + case 7: + jsValue = swift.memory.getObject(payload1); + break; + case 8: + jsValue = swift.memory.getObject(payload1); + break; + default: + throw new TypeError("Unsupported JSValue kind " + kind); + } + return jsValue; + } + + const __bjs_createAsyncPointHelpers = () => ({ + lower: (value) => { + i32Stack.push((value.x | 0)); + i32Stack.push((value.y | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + const int1 = i32Stack.pop(); + return { x: int1, y: int }; + } + }); return { /** @@ -106,6 +216,203 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["swift_js_struct_lower_AsyncPoint"] = function(objectId) { + structHelpers.AsyncPoint.lower(swift.memory.getObject(objectId)); + } + bjs["swift_js_struct_lift_AsyncPoint"] = function() { + const value = structHelpers.AsyncPoint.lift(); + return swift.memory.retain(value); + } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } + bjs["promise_resolve_TestModule_y"] = function(promise) { + try { + swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(); + } catch (error) { + setException(error); + } + } + bjs["promise_resolve_TestModule_Si"] = function(promise, value) { + try { + swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(value); + } catch (error) { + setException(error); + } + } + bjs["promise_resolve_TestModule_SS"] = function(promise, valueBytes, valueCount) { + try { + const string = decodeString(valueBytes, valueCount); + swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(string); + } catch (error) { + setException(error); + } + } + bjs["promise_resolve_TestModule_Sb"] = function(promise, value) { + try { + swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(value !== 0); + } catch (error) { + setException(error); + } + } + bjs["promise_resolve_TestModule_Sf"] = function(promise, value) { + try { + swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(value); + } catch (error) { + setException(error); + } + } + bjs["promise_resolve_TestModule_Sd"] = function(promise, value) { + try { + swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(value); + } catch (error) { + setException(error); + } + } + bjs["promise_resolve_TestModule_8JSObjectC"] = function(promise, value) { + try { + swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(swift.memory.getObject(value)); + } catch (error) { + setException(error); + } + } + bjs["promise_resolve_TestModule_10AsyncPointV"] = function(promise, value) { + try { + const value1 = swift.memory.getObject(value); + swift.memory.release(value); + swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(value1); + } catch (error) { + setException(error); + } + } + bjs["promise_resolve_TestModule_14AsyncDirectionO"] = function(promise, value) { + try { + swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(value); + } catch (error) { + setException(error); + } + } + bjs["promise_resolve_TestModule_10AsyncThemeO"] = function(promise, valueBytes, valueCount) { + try { + const string = decodeString(valueBytes, valueCount); + swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(string); + } catch (error) { + setException(error); + } + } + bjs["promise_resolve_TestModule_Sq14AsyncDirectionO"] = function(promise, valueIsSome, valueWrappedValue) { + try { + swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(valueIsSome ? valueWrappedValue : null); + } catch (error) { + setException(error); + } + } + bjs["promise_resolve_TestModule_Sq10AsyncThemeO"] = function(promise, valueIsSome, valueBytes, valueCount) { + try { + let optResult; + if (valueIsSome) { + const string = decodeString(valueBytes, valueCount); + optResult = string; + } else { + optResult = null; + } + swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(optResult); + } catch (error) { + setException(error); + } + } + bjs["promise_resolve_TestModule_Sq10AsyncPointV"] = function(promise, value) { + try { + let optResult; + if (value) { + const struct = structHelpers.AsyncPoint.lift(); + optResult = struct; + } else { + optResult = null; + } + swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(optResult); + } catch (error) { + setException(error); + } + } + bjs["promise_resolve_TestModule_Sa10AsyncPointV"] = function(promise) { + try { + const arrayLen = i32Stack.pop(); + let arrayResult; + if (arrayLen === -1) { + arrayResult = taStack.pop(); + } else { + arrayResult = []; + for (let i = 0; i < arrayLen; i++) { + const struct = structHelpers.AsyncPoint.lift(); + arrayResult.push(struct); + } + arrayResult.reverse(); + } + swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(arrayResult); + } catch (error) { + setException(error); + } + } + bjs["promise_resolve_TestModule_Sa14AsyncDirectionO"] = function(promise) { + try { + const arrayLen = i32Stack.pop(); + let arrayResult; + if (arrayLen === -1) { + arrayResult = taStack.pop(); + } else { + arrayResult = []; + for (let i = 0; i < arrayLen; i++) { + const caseId = i32Stack.pop(); + arrayResult.push(caseId); + } + arrayResult.reverse(); + } + swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(arrayResult); + } catch (error) { + setException(error); + } + } + bjs["promise_resolve_TestModule_SD10AsyncPointV"] = function(promise) { + try { + const dictLen = i32Stack.pop(); + const dictResult = {}; + for (let i = 0; i < dictLen; i++) { + const struct = structHelpers.AsyncPoint.lift(); + const string = strStack.pop(); + dictResult[string] = struct; + } + swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(dictResult); + } catch (error) { + setException(error); + } + } + bjs["promise_resolve_TestModule_SD14AsyncDirectionO"] = function(promise) { + try { + const dictLen = i32Stack.pop(); + const dictResult = {}; + for (let i = 0; i < dictLen; i++) { + const caseId = i32Stack.pop(); + const string = strStack.pop(); + dictResult[string] = caseId; + } + swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(dictResult); + } catch (error) { + setException(error); + } + } + bjs["promise_reject_TestModule"] = function(promise, valueKind, valuePayload1, valuePayload2) { + try { + const jsValue = __bjs_jsValueLift(valueKind, valuePayload1, valuePayload2); + swift.memory.getObject(promise)[__bjs_promiseSettlers].reject(jsValue); + } catch (error) { + setException(error); + } + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; @@ -210,6 +517,9 @@ export async function createInstantiator(options, swift) { /** @param {WebAssembly.Instance} instance */ createExports: (instance) => { const js = swift.memory.heap; + const AsyncPointHelpers = __bjs_createAsyncPointHelpers(); + structHelpers.AsyncPoint = AsyncPointHelpers; + const exports = { asyncReturnVoid: function bjs_asyncReturnVoid() { const ret = instance.exports.bjs_asyncReturnVoid(); @@ -255,6 +565,137 @@ export async function createInstantiator(options, swift) { swift.memory.release(ret); return ret1; }, + asyncRoundTripStruct: function bjs_asyncRoundTripStruct(v) { + structHelpers.AsyncPoint.lower(v); + const ret = instance.exports.bjs_asyncRoundTripStruct(); + const ret1 = swift.memory.getObject(ret); + swift.memory.release(ret); + return ret1; + }, + asyncRoundTripStructThrows: function bjs_asyncRoundTripStructThrows(v) { + structHelpers.AsyncPoint.lower(v); + const ret = instance.exports.bjs_asyncRoundTripStructThrows(); + const ret1 = swift.memory.getObject(ret); + swift.memory.release(ret); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + return ret1; + }, + asyncCombineStructs: function bjs_asyncCombineStructs(a, b) { + structHelpers.AsyncPoint.lower(a); + structHelpers.AsyncPoint.lower(b); + const ret = instance.exports.bjs_asyncCombineStructs(); + const ret1 = swift.memory.getObject(ret); + swift.memory.release(ret); + return ret1; + }, + asyncRoundTripEnum: function bjs_asyncRoundTripEnum(v) { + const ret = instance.exports.bjs_asyncRoundTripEnum(v); + const ret1 = swift.memory.getObject(ret); + swift.memory.release(ret); + return ret1; + }, + asyncRoundTripRawEnum: function bjs_asyncRoundTripRawEnum(v) { + const vBytes = textEncoder.encode(v); + const vId = swift.memory.retain(vBytes); + const ret = instance.exports.bjs_asyncRoundTripRawEnum(vId, vBytes.length); + const ret1 = swift.memory.getObject(ret); + swift.memory.release(ret); + return ret1; + }, + asyncRoundTripOptionalEnum: function bjs_asyncRoundTripOptionalEnum(v) { + const isSome = v != null; + const ret = instance.exports.bjs_asyncRoundTripOptionalEnum(+isSome, isSome ? v : 0); + const ret1 = swift.memory.getObject(ret); + swift.memory.release(ret); + return ret1; + }, + asyncRoundTripOptionalRawEnum: function bjs_asyncRoundTripOptionalRawEnum(v) { + const isSome = v != null; + let result, result1; + if (isSome) { + const vBytes = textEncoder.encode(v); + const vId = swift.memory.retain(vBytes); + result = vId; + result1 = vBytes.length; + } else { + result = 0; + result1 = 0; + } + const ret = instance.exports.bjs_asyncRoundTripOptionalRawEnum(+isSome, result, result1); + const ret1 = swift.memory.getObject(ret); + swift.memory.release(ret); + return ret1; + }, + asyncRoundTripOptionalStruct: function bjs_asyncRoundTripOptionalStruct(v) { + const isSome = v != null; + if (isSome) { + structHelpers.AsyncPoint.lower(v); + } + i32Stack.push(+isSome); + const ret = instance.exports.bjs_asyncRoundTripOptionalStruct(); + const ret1 = swift.memory.getObject(ret); + swift.memory.release(ret); + return ret1; + }, + asyncRoundTripStructArray: function bjs_asyncRoundTripStructArray(v) { + for (const elem of v) { + structHelpers.AsyncPoint.lower(elem); + } + i32Stack.push(v.length); + const ret = instance.exports.bjs_asyncRoundTripStructArray(); + const ret1 = swift.memory.getObject(ret); + swift.memory.release(ret); + return ret1; + }, + asyncRoundTripEnumArray: function bjs_asyncRoundTripEnumArray(v) { + for (const elem of v) { + i32Stack.push((elem | 0)); + } + i32Stack.push(v.length); + const ret = instance.exports.bjs_asyncRoundTripEnumArray(); + const ret1 = swift.memory.getObject(ret); + swift.memory.release(ret); + return ret1; + }, + asyncRoundTripStructDictionary: function bjs_asyncRoundTripStructDictionary(v) { + const entries = Object.entries(v); + for (const entry of entries) { + const [key, value] = entry; + const bytes = textEncoder.encode(key); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + structHelpers.AsyncPoint.lower(value); + } + i32Stack.push(entries.length); + const ret = instance.exports.bjs_asyncRoundTripStructDictionary(); + const ret1 = swift.memory.getObject(ret); + swift.memory.release(ret); + return ret1; + }, + asyncRoundTripEnumDictionary: function bjs_asyncRoundTripEnumDictionary(v) { + const entries = Object.entries(v); + for (const entry of entries) { + const [key, value] = entry; + const bytes = textEncoder.encode(key); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + i32Stack.push((value | 0)); + } + i32Stack.push(entries.length); + const ret = instance.exports.bjs_asyncRoundTripEnumDictionary(); + const ret1 = swift.memory.getObject(ret); + swift.memory.release(ret); + return ret1; + }, + AsyncDirection: AsyncDirectionValues, + AsyncTheme: AsyncThemeValues, }; _exports = exports; return exports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js index fd27e3d67..27e53b8d7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js @@ -221,6 +221,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js index 6b6698377..789379a32 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js @@ -220,6 +220,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js index 8f8463bf0..4b13bb633 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js @@ -162,6 +162,13 @@ export async function createInstantiator(options, swift) { const value = structHelpers.MathOperations.lift(); return swift.memory.retain(value); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js index d040df41c..2021f1c96 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js @@ -154,6 +154,13 @@ export async function createInstantiator(options, swift) { const value = structHelpers.Counters.lift(); return swift.memory.retain(value); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js index 23819a6e8..d97e4ef11 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js @@ -856,6 +856,13 @@ export async function createInstantiator(options, swift) { const value = structHelpers.Point.lift(); return swift.memory.retain(value); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js index 5272717ec..b4c5870b6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js @@ -130,6 +130,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js index e232c7cbb..dc1b3c6b3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js @@ -111,6 +111,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js index ecf121aa4..050c16b18 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js @@ -150,6 +150,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js index 247a11e54..9f2f4122c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js @@ -131,6 +131,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js index 4e4449e06..2ab98b31b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js @@ -182,6 +182,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js index 211cbefa3..94bfe89cd 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js @@ -107,6 +107,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js index f5895589d..174c9b430 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js @@ -107,6 +107,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js index 77e8002f8..e8a89c6e4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js @@ -106,6 +106,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js index db876ff02..99c0bb4ea 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js @@ -106,6 +106,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js index ca958e564..82458b81a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js @@ -106,6 +106,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js index ca958e564..82458b81a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js @@ -106,6 +106,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js index 613d4a10b..8ebcbda28 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js @@ -107,6 +107,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js index ab4b4b34d..710eebe36 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js @@ -152,6 +152,13 @@ export async function createInstantiator(options, swift) { const value = structHelpers.FooContainer.lift(); return swift.memory.retain(value); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js index 59c8be11d..605359fb8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js @@ -107,6 +107,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js index f3293ae52..e24b5dac5 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js @@ -107,6 +107,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js index ef666149b..b936636a9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js @@ -107,6 +107,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.js index b12640234..c5c37a512 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.js @@ -106,6 +106,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js index 71e66827e..e8f617e5b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js @@ -196,6 +196,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js index 6c3ddb555..3abacf371 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js @@ -106,6 +106,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js index 70f1575b4..a2dc23d68 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js @@ -106,6 +106,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js index 16ec9433c..7fdf9b4c8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js @@ -106,6 +106,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js index d698857d3..09a6ace60 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js @@ -106,6 +106,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js index 92b8f5dae..1c9287a08 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js @@ -106,6 +106,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js index 33b4e60c1..7c2751964 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js @@ -145,6 +145,13 @@ export async function createInstantiator(options, swift) { const value = structHelpers.Player_Stats.lift(); return swift.memory.retain(value); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js index f376c1b24..c045286ae 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js @@ -107,6 +107,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js index 97c1a44fe..3957b5482 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js @@ -107,6 +107,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js index a140ea232..e624ceb1a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js @@ -107,6 +107,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js index b8116a32f..6e66102e2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js @@ -106,6 +106,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js index d992bf75d..ac533b6d4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js @@ -163,6 +163,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js index 89f84d29a..102ac6020 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js @@ -131,6 +131,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js index 32a739587..5257c9856 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js @@ -150,6 +150,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js index 16cf2881f..91316a8c4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js @@ -150,6 +150,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js index b616665ca..f238551a9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js @@ -111,6 +111,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js index f6e1fdbce..c7f9b4955 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js @@ -111,6 +111,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js index 885c0980f..994e1710a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js @@ -107,6 +107,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js index aab8b67fe..839e194cf 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js @@ -107,6 +107,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js index 88f04efe9..5ee56f5bc 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js @@ -107,6 +107,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js index c82bc5b8d..cdd80e90a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js @@ -241,6 +241,13 @@ export async function createInstantiator(options, swift) { const value = structHelpers.Animal.lift(); return swift.memory.retain(value); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js index cffbdcf67..6fd627dcb 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js @@ -132,6 +132,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js index d55d5c095..aa523be20 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js @@ -375,6 +375,13 @@ export async function createInstantiator(options, swift) { const value = structHelpers.Vector2D.lift(); return swift.memory.retain(value); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js index 17bf086ff..44b7c5527 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js @@ -125,6 +125,13 @@ export async function createInstantiator(options, swift) { const value = structHelpers.Point.lift(); return swift.memory.retain(value); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.js index 2b51ebd3b..f07b00968 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.js @@ -131,6 +131,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js index 9c41c3061..d1036cba4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js @@ -106,6 +106,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js index 97a00c278..54276025b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js @@ -130,6 +130,13 @@ export async function createInstantiator(options, swift) { const value = structHelpers.PointerFields.lift(); return swift.memory.retain(value); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js index 2951ef5f8..755165ee1 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js @@ -107,6 +107,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/PackageToJS/Templates/instantiate.js b/Plugins/PackageToJS/Templates/instantiate.js index 88e322538..36d840099 100644 --- a/Plugins/PackageToJS/Templates/instantiate.js +++ b/Plugins/PackageToJS/Templates/instantiate.js @@ -69,6 +69,7 @@ async function createInstantiator(options, swift) { swift_js_pop_i64: unexpectedBjsCall, swift_js_closure_unregister: unexpectedBjsCall, swift_js_push_typed_array: unexpectedBjsCall, + swift_js_make_promise: unexpectedBjsCall, }; }, /** @param {WebAssembly.Instance} instance */ diff --git a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift index ff586b45b..e39e6f2fa 100644 --- a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift +++ b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift @@ -2286,3 +2286,67 @@ extension _BridgedAsOptional { throw error } } + +// MARK: Async Promise Creation + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_make_promise") +private func _swift_js_make_promise_extern() -> Int32 +#else +private func _swift_js_make_promise_extern() -> Int32 { _onlyAvailableOnWasm() } +#endif + +// `@unchecked Sendable` is safe because the Wasm runtime is single-threaded. +private struct _BridgeJSMakePromiseContext: @unchecked Sendable { + let promise: JSObject + let resolve: (JSObject, T) throws(JSException) -> Void + let reject: (JSObject, JSValue) throws(JSException) -> Void + let body: () async throws(JSException) -> T +} + +/// Returns a `Promise` synchronously and settles it from a `Task` via the generated +/// `resolve` / `reject` thunks, which this library cannot name directly. +@_spi(BridgeJS) public func _bjs_makePromise( + resolve: @escaping (JSObject, T) throws(JSException) -> Void, + reject: @escaping (JSObject, JSValue) throws(JSException) -> Void, + _ body: @escaping () async throws(JSException) -> T +) -> Int32 { + let promise = JSObject(id: JavaScriptObjectRef(bitPattern: _swift_js_make_promise_extern())) + let context = _BridgeJSMakePromiseContext(promise: promise, resolve: resolve, reject: reject, body: body) + Task { + do throws(JSException) { + let value = try await context.body() + try context.resolve(context.promise, value) + } catch { + try? context.reject(context.promise, error.thrownValue) + } + } + return promise.bridgeJSLowerReturn() +} + +private struct _BridgeJSMakeVoidPromiseContext: @unchecked Sendable { + let promise: JSObject + let resolve: (JSObject) throws(JSException) -> Void + let reject: (JSObject, JSValue) throws(JSException) -> Void + let body: () async throws(JSException) -> Void +} + +/// `Void`-returning overload: a `Void` value can't cross the bridge as a parameter, so the +/// generated `resolve` thunk takes only the promise and settles it with `undefined`. +@_spi(BridgeJS) public func _bjs_makePromise( + resolve: @escaping (JSObject) throws(JSException) -> Void, + reject: @escaping (JSObject, JSValue) throws(JSException) -> Void, + _ body: @escaping () async throws(JSException) -> Void +) -> Int32 { + let promise = JSObject(id: JavaScriptObjectRef(bitPattern: _swift_js_make_promise_extern())) + let context = _BridgeJSMakeVoidPromiseContext(promise: promise, resolve: resolve, reject: reject, body: body) + Task { + do throws(JSException) { + try await context.body() + try context.resolve(context.promise) + } catch { + try? context.reject(context.promise, error.thrownValue) + } + } + return promise.bridgeJSLowerReturn() +} diff --git a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift index c6e216203..1529a051b 100644 --- a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift @@ -174,6 +174,10 @@ extension Greeter { return a + b } + @JS func asyncMakePoint(x: Int, y: Int) async -> PublicPoint { + return PublicPoint(x: x, y: y) + } + deinit { Self.onDeinit() } @@ -302,6 +306,26 @@ extension StaticCalculator { return .light } +@JS func asyncRoundTripTheme(_ v: Theme) async -> Theme { v } + +@JS func asyncRoundTripDirection(_ v: Direction) async -> Direction { v } + +@JS func asyncRoundTripOptionalTheme(_ v: Theme?) async -> Theme? { v } + +@JS func asyncRoundTripOptionalDirection(_ v: Direction?) async -> Direction? { v } + +@JS func asyncRoundTripDirectionArray(_ v: [Direction]) async -> [Direction] { v } + +@JS func asyncRoundTripDirectionDict(_ v: [String: Direction]) async -> [String: Direction] { v } + +@JS func asyncRoundTripThemeArray(_ v: [Theme]) async -> [Theme] { v } + +@JS func asyncRoundTripThemeDict(_ v: [String: Theme]) async -> [String: Theme] { v } + +@JS func asyncRoundTripFileSize(_ v: FileSize) async -> FileSize { v } + +@JS func asyncRoundTripOptionalFileSize(_ v: FileSize?) async -> FileSize? { v } + @JS func setHttpStatus(_ status: HttpStatus) -> HttpStatus { return status } diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index e6c2f940b..3fd09d496 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -7182,10 +7182,9 @@ public func _bjs_throwsWithJSObjectResult() -> Int32 { @_cdecl("bjs_asyncRoundTripVoid") public func _bjs_asyncRoundTripVoid() -> Int32 { #if arch(wasm32) - let ret = JSPromise.async { + return _bjs_makePromise(resolve: Promise_resolve_y, reject: Promise_reject) { await asyncRoundTripVoid() - }.jsObject - return ret.bridgeJSLowerReturn() + } #else fatalError("Only available on WebAssembly") #endif @@ -7195,10 +7194,9 @@ public func _bjs_asyncRoundTripVoid() -> Int32 { @_cdecl("bjs_asyncRoundTripInt") public func _bjs_asyncRoundTripInt(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = JSPromise.async { - return await asyncRoundTripInt(v: Int.bridgeJSLiftParameter(v)).jsValue - }.jsObject - return ret.bridgeJSLowerReturn() + return _bjs_makePromise(resolve: Promise_resolve_Si, reject: Promise_reject) { + return await asyncRoundTripInt(v: Int.bridgeJSLiftParameter(v)) + } #else fatalError("Only available on WebAssembly") #endif @@ -7208,10 +7206,9 @@ public func _bjs_asyncRoundTripInt(_ v: Int32) -> Int32 { @_cdecl("bjs_asyncRoundTripFloat") public func _bjs_asyncRoundTripFloat(_ v: Float32) -> Int32 { #if arch(wasm32) - let ret = JSPromise.async { - return await asyncRoundTripFloat(v: Float.bridgeJSLiftParameter(v)).jsValue - }.jsObject - return ret.bridgeJSLowerReturn() + return _bjs_makePromise(resolve: Promise_resolve_Sf, reject: Promise_reject) { + return await asyncRoundTripFloat(v: Float.bridgeJSLiftParameter(v)) + } #else fatalError("Only available on WebAssembly") #endif @@ -7221,10 +7218,9 @@ public func _bjs_asyncRoundTripFloat(_ v: Float32) -> Int32 { @_cdecl("bjs_asyncRoundTripDouble") public func _bjs_asyncRoundTripDouble(_ v: Float64) -> Int32 { #if arch(wasm32) - let ret = JSPromise.async { - return await asyncRoundTripDouble(v: Double.bridgeJSLiftParameter(v)).jsValue - }.jsObject - return ret.bridgeJSLowerReturn() + return _bjs_makePromise(resolve: Promise_resolve_Sd, reject: Promise_reject) { + return await asyncRoundTripDouble(v: Double.bridgeJSLiftParameter(v)) + } #else fatalError("Only available on WebAssembly") #endif @@ -7234,10 +7230,9 @@ public func _bjs_asyncRoundTripDouble(_ v: Float64) -> Int32 { @_cdecl("bjs_asyncRoundTripBool") public func _bjs_asyncRoundTripBool(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = JSPromise.async { - return await asyncRoundTripBool(v: Bool.bridgeJSLiftParameter(v)).jsValue - }.jsObject - return ret.bridgeJSLowerReturn() + return _bjs_makePromise(resolve: Promise_resolve_Sb, reject: Promise_reject) { + return await asyncRoundTripBool(v: Bool.bridgeJSLiftParameter(v)) + } #else fatalError("Only available on WebAssembly") #endif @@ -7247,10 +7242,9 @@ public func _bjs_asyncRoundTripBool(_ v: Int32) -> Int32 { @_cdecl("bjs_asyncRoundTripString") public func _bjs_asyncRoundTripString(_ vBytes: Int32, _ vLength: Int32) -> Int32 { #if arch(wasm32) - let ret = JSPromise.async { - return await asyncRoundTripString(v: String.bridgeJSLiftParameter(vBytes, vLength)).jsValue - }.jsObject - return ret.bridgeJSLowerReturn() + return _bjs_makePromise(resolve: Promise_resolve_SS, reject: Promise_reject) { + return await asyncRoundTripString(v: String.bridgeJSLiftParameter(vBytes, vLength)) + } #else fatalError("Only available on WebAssembly") #endif @@ -7260,10 +7254,9 @@ public func _bjs_asyncRoundTripString(_ vBytes: Int32, _ vLength: Int32) -> Int3 @_cdecl("bjs_asyncRoundTripSwiftHeapObject") public func _bjs_asyncRoundTripSwiftHeapObject(_ v: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = JSPromise.async { - return await asyncRoundTripSwiftHeapObject(v: Greeter.bridgeJSLiftParameter(v)).jsValue - }.jsObject - return ret.bridgeJSLowerReturn() + return _bjs_makePromise(resolve: Promise_resolve_7GreeterC, reject: Promise_reject) { + return await asyncRoundTripSwiftHeapObject(v: Greeter.bridgeJSLiftParameter(v)) + } #else fatalError("Only available on WebAssembly") #endif @@ -7273,10 +7266,9 @@ public func _bjs_asyncRoundTripSwiftHeapObject(_ v: UnsafeMutableRawPointer) -> @_cdecl("bjs_asyncRoundTripJSObject") public func _bjs_asyncRoundTripJSObject(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = JSPromise.async { - return await asyncRoundTripJSObject(v: JSObject.bridgeJSLiftParameter(v)).jsValue - }.jsObject - return ret.bridgeJSLowerReturn() + return _bjs_makePromise(resolve: Promise_resolve_8JSObjectC, reject: Promise_reject) { + return await asyncRoundTripJSObject(v: JSObject.bridgeJSLiftParameter(v)) + } #else fatalError("Only available on WebAssembly") #endif @@ -7402,6 +7394,130 @@ public func _bjs_getTheme() -> Void { #endif } +@_expose(wasm, "bjs_asyncRoundTripTheme") +@_cdecl("bjs_asyncRoundTripTheme") +public func _bjs_asyncRoundTripTheme(_ vBytes: Int32, _ vLength: Int32) -> Int32 { + #if arch(wasm32) + return _bjs_makePromise(resolve: Promise_resolve_5ThemeO, reject: Promise_reject) { + return await asyncRoundTripTheme(_: Theme.bridgeJSLiftParameter(vBytes, vLength)) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_asyncRoundTripDirection") +@_cdecl("bjs_asyncRoundTripDirection") +public func _bjs_asyncRoundTripDirection(_ v: Int32) -> Int32 { + #if arch(wasm32) + return _bjs_makePromise(resolve: Promise_resolve_9DirectionO, reject: Promise_reject) { + return await asyncRoundTripDirection(_: Direction.bridgeJSLiftParameter(v)) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_asyncRoundTripOptionalTheme") +@_cdecl("bjs_asyncRoundTripOptionalTheme") +public func _bjs_asyncRoundTripOptionalTheme(_ vIsSome: Int32, _ vBytes: Int32, _ vLength: Int32) -> Int32 { + #if arch(wasm32) + return _bjs_makePromise(resolve: Promise_resolve_Sq5ThemeO, reject: Promise_reject) { + return await asyncRoundTripOptionalTheme(_: Optional.bridgeJSLiftParameter(vIsSome, vBytes, vLength)) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_asyncRoundTripOptionalDirection") +@_cdecl("bjs_asyncRoundTripOptionalDirection") +public func _bjs_asyncRoundTripOptionalDirection(_ vIsSome: Int32, _ vValue: Int32) -> Int32 { + #if arch(wasm32) + return _bjs_makePromise(resolve: Promise_resolve_Sq9DirectionO, reject: Promise_reject) { + return await asyncRoundTripOptionalDirection(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_asyncRoundTripDirectionArray") +@_cdecl("bjs_asyncRoundTripDirectionArray") +public func _bjs_asyncRoundTripDirectionArray() -> Int32 { + #if arch(wasm32) + let _tmp_v = [Direction].bridgeJSStackPop() + return _bjs_makePromise(resolve: Promise_resolve_Sa9DirectionO, reject: Promise_reject) { + return await asyncRoundTripDirectionArray(_: _tmp_v) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_asyncRoundTripDirectionDict") +@_cdecl("bjs_asyncRoundTripDirectionDict") +public func _bjs_asyncRoundTripDirectionDict() -> Int32 { + #if arch(wasm32) + let _tmp_v = [String: Direction].bridgeJSLiftParameter() + return _bjs_makePromise(resolve: Promise_resolve_SD9DirectionO, reject: Promise_reject) { + return await asyncRoundTripDirectionDict(_: _tmp_v) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_asyncRoundTripThemeArray") +@_cdecl("bjs_asyncRoundTripThemeArray") +public func _bjs_asyncRoundTripThemeArray() -> Int32 { + #if arch(wasm32) + let _tmp_v = [Theme].bridgeJSStackPop() + return _bjs_makePromise(resolve: Promise_resolve_Sa5ThemeO, reject: Promise_reject) { + return await asyncRoundTripThemeArray(_: _tmp_v) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_asyncRoundTripThemeDict") +@_cdecl("bjs_asyncRoundTripThemeDict") +public func _bjs_asyncRoundTripThemeDict() -> Int32 { + #if arch(wasm32) + let _tmp_v = [String: Theme].bridgeJSLiftParameter() + return _bjs_makePromise(resolve: Promise_resolve_SD5ThemeO, reject: Promise_reject) { + return await asyncRoundTripThemeDict(_: _tmp_v) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_asyncRoundTripFileSize") +@_cdecl("bjs_asyncRoundTripFileSize") +public func _bjs_asyncRoundTripFileSize(_ v: Int64) -> Int32 { + #if arch(wasm32) + return _bjs_makePromise(resolve: Promise_resolve_8FileSizeO, reject: Promise_reject) { + return await asyncRoundTripFileSize(_: FileSize.bridgeJSLiftParameter(v)) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_asyncRoundTripOptionalFileSize") +@_cdecl("bjs_asyncRoundTripOptionalFileSize") +public func _bjs_asyncRoundTripOptionalFileSize(_ vIsSome: Int32, _ vValue: Int64) -> Int32 { + #if arch(wasm32) + return _bjs_makePromise(resolve: Promise_resolve_Sq8FileSizeO, reject: Promise_reject) { + return await asyncRoundTripOptionalFileSize(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_setHttpStatus") @_cdecl("bjs_setHttpStatus") public func _bjs_setHttpStatus(_ status: Int32) -> Int32 { @@ -8050,6 +8166,110 @@ public func _bjs_roundTripPublicPoint() -> Void { #endif } +@_expose(wasm, "bjs_asyncRoundTripPublicPoint") +@_cdecl("bjs_asyncRoundTripPublicPoint") +public func _bjs_asyncRoundTripPublicPoint() -> Int32 { + #if arch(wasm32) + let _tmp_point = PublicPoint.bridgeJSLiftParameter() + return _bjs_makePromise(resolve: Promise_resolve_11PublicPointV, reject: Promise_reject) { + return await asyncRoundTripPublicPoint(_: _tmp_point) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_asyncRoundTripPublicPointThrows") +@_cdecl("bjs_asyncRoundTripPublicPointThrows") +public func _bjs_asyncRoundTripPublicPointThrows() -> Int32 { + #if arch(wasm32) + let _tmp_point = PublicPoint.bridgeJSLiftParameter() + return _bjs_makePromise(resolve: Promise_resolve_11PublicPointV, reject: Promise_reject) { () async throws(JSException) -> PublicPoint in + return try await asyncRoundTripPublicPointThrows(_: _tmp_point) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_asyncStructOrThrow") +@_cdecl("bjs_asyncStructOrThrow") +public func _bjs_asyncStructOrThrow(_ shouldThrow: Int32) -> Int32 { + #if arch(wasm32) + return _bjs_makePromise(resolve: Promise_resolve_11PublicPointV, reject: Promise_reject) { () async throws(JSException) -> PublicPoint in + return try await asyncStructOrThrow(_: Bool.bridgeJSLiftParameter(shouldThrow)) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_asyncCombinePublicPoints") +@_cdecl("bjs_asyncCombinePublicPoints") +public func _bjs_asyncCombinePublicPoints() -> Int32 { + #if arch(wasm32) + let _tmp_b = PublicPoint.bridgeJSLiftParameter() + let _tmp_a = PublicPoint.bridgeJSLiftParameter() + return _bjs_makePromise(resolve: Promise_resolve_11PublicPointV, reject: Promise_reject) { + return await asyncCombinePublicPoints(_: _tmp_a, _: _tmp_b) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_asyncRoundTripContact") +@_cdecl("bjs_asyncRoundTripContact") +public func _bjs_asyncRoundTripContact() -> Int32 { + #if arch(wasm32) + let _tmp_contact = Contact.bridgeJSLiftParameter() + return _bjs_makePromise(resolve: Promise_resolve_7ContactV, reject: Promise_reject) { + return await asyncRoundTripContact(_: _tmp_contact) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_asyncRoundTripPublicPointArray") +@_cdecl("bjs_asyncRoundTripPublicPointArray") +public func _bjs_asyncRoundTripPublicPointArray() -> Int32 { + #if arch(wasm32) + let _tmp_points = [PublicPoint].bridgeJSStackPop() + return _bjs_makePromise(resolve: Promise_resolve_Sa11PublicPointV, reject: Promise_reject) { + return await asyncRoundTripPublicPointArray(_: _tmp_points) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_asyncRoundTripOptionalPublicPoint") +@_cdecl("bjs_asyncRoundTripOptionalPublicPoint") +public func _bjs_asyncRoundTripOptionalPublicPoint() -> Int32 { + #if arch(wasm32) + let _tmp_point = Optional.bridgeJSLiftParameter() + return _bjs_makePromise(resolve: Promise_resolve_Sq11PublicPointV, reject: Promise_reject) { + return await asyncRoundTripOptionalPublicPoint(_: _tmp_point) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_asyncRoundTripPublicPointDict") +@_cdecl("bjs_asyncRoundTripPublicPointDict") +public func _bjs_asyncRoundTripPublicPointDict() -> Int32 { + #if arch(wasm32) + let _tmp_points = [String: PublicPoint].bridgeJSLiftParameter() + return _bjs_makePromise(resolve: Promise_resolve_SD11PublicPointV, reject: Promise_reject) { + return await asyncRoundTripPublicPointDict(_: _tmp_points) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_roundTripContact") @_cdecl("bjs_roundTripContact") public func _bjs_roundTripContact() -> Void { @@ -8659,6 +8879,18 @@ public func _bjs_Calculator_add(_ _self: UnsafeMutableRawPointer, _ a: Int32, _ #endif } +@_expose(wasm, "bjs_Calculator_asyncMakePoint") +@_cdecl("bjs_Calculator_asyncMakePoint") +public func _bjs_Calculator_asyncMakePoint(_ _self: UnsafeMutableRawPointer, _ x: Int32, _ y: Int32) -> Int32 { + #if arch(wasm32) + return _bjs_makePromise(resolve: Promise_resolve_11PublicPointV, reject: Promise_reject) { + return await Calculator.bridgeJSLiftParameter(_self).asyncMakePoint(x: Int.bridgeJSLiftParameter(x), y: Int.bridgeJSLiftParameter(y)) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_Calculator_deinit") @_cdecl("bjs_Calculator_deinit") public func _bjs_Calculator_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { @@ -11139,6 +11371,512 @@ fileprivate func _bjs_LeakCheck_wrap_extern(_ pointer: UnsafeMutableRawPointer) return _bjs_LeakCheck_wrap_extern(pointer) } +@JSFunction func Promise_reject(_ promise: JSObject, _ value: JSValue) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_reject_BridgeJSRuntimeTests") +fileprivate func promise_reject_BridgeJSRuntimeTests_extern(_ promise: Int32, _ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void +#else +fileprivate func promise_reject_BridgeJSRuntimeTests_extern(_ promise: Int32, _ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_reject_BridgeJSRuntimeTests(_ promise: Int32, _ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void { + return promise_reject_BridgeJSRuntimeTests_extern(promise, valueKind, valuePayload1, valuePayload2) +} + +func _$Promise_reject(_ promise: JSObject, _ value: JSValue) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let (valueKind, valuePayload1, valuePayload2) = value.bridgeJSLowerParameter() + promise_reject_BridgeJSRuntimeTests(promiseValue, valueKind, valuePayload1, valuePayload2) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_y(_ promise: JSObject) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_y") +fileprivate func promise_resolve_BridgeJSRuntimeTests_y_extern(_ promise: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_y_extern(_ promise: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_y(_ promise: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_y_extern(promise) +} + +func _$Promise_resolve_y(_ promise: JSObject) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_y(promiseValue) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_Si(_ promise: JSObject, _ value: Int) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Si") +fileprivate func promise_resolve_BridgeJSRuntimeTests_Si_extern(_ promise: Int32, _ value: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_Si_extern(_ promise: Int32, _ value: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Si(_ promise: Int32, _ value: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_Si_extern(promise, value) +} + +func _$Promise_resolve_Si(_ promise: JSObject, _ value: Int) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueValue = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_Si(promiseValue, valueValue) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_Sf(_ promise: JSObject, _ value: Float) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sf") +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sf_extern(_ promise: Int32, _ value: Float32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sf_extern(_ promise: Int32, _ value: Float32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sf(_ promise: Int32, _ value: Float32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_Sf_extern(promise, value) +} + +func _$Promise_resolve_Sf(_ promise: JSObject, _ value: Float) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueValue = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_Sf(promiseValue, valueValue) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_Sd(_ promise: JSObject, _ value: Double) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sd") +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sd_extern(_ promise: Int32, _ value: Float64) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sd_extern(_ promise: Int32, _ value: Float64) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sd(_ promise: Int32, _ value: Float64) -> Void { + return promise_resolve_BridgeJSRuntimeTests_Sd_extern(promise, value) +} + +func _$Promise_resolve_Sd(_ promise: JSObject, _ value: Double) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueValue = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_Sd(promiseValue, valueValue) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_Sb(_ promise: JSObject, _ value: Bool) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sb") +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sb_extern(_ promise: Int32, _ value: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sb_extern(_ promise: Int32, _ value: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sb(_ promise: Int32, _ value: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_Sb_extern(promise, value) +} + +func _$Promise_resolve_Sb(_ promise: JSObject, _ value: Bool) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueValue = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_Sb(promiseValue, valueValue) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_SS(_ promise: JSObject, _ value: String) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_SS") +fileprivate func promise_resolve_BridgeJSRuntimeTests_SS_extern(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_SS_extern(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_SS(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_SS_extern(promise, valueBytes, valueLength) +} + +func _$Promise_resolve_SS(_ promise: JSObject, _ value: String) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + value.bridgeJSWithLoweredParameter { (valueBytes, valueLength) in + promise_resolve_BridgeJSRuntimeTests_SS(promiseValue, valueBytes, valueLength) + } + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_7GreeterC(_ promise: JSObject, _ value: Greeter) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_7GreeterC") +fileprivate func promise_resolve_BridgeJSRuntimeTests_7GreeterC_extern(_ promise: Int32, _ value: UnsafeMutableRawPointer) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_7GreeterC_extern(_ promise: Int32, _ value: UnsafeMutableRawPointer) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_7GreeterC(_ promise: Int32, _ value: UnsafeMutableRawPointer) -> Void { + return promise_resolve_BridgeJSRuntimeTests_7GreeterC_extern(promise, value) +} + +func _$Promise_resolve_7GreeterC(_ promise: JSObject, _ value: Greeter) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valuePointer = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_7GreeterC(promiseValue, valuePointer) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_8JSObjectC(_ promise: JSObject, _ value: JSObject) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_8JSObjectC") +fileprivate func promise_resolve_BridgeJSRuntimeTests_8JSObjectC_extern(_ promise: Int32, _ value: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_8JSObjectC_extern(_ promise: Int32, _ value: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_8JSObjectC(_ promise: Int32, _ value: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_8JSObjectC_extern(promise, value) +} + +func _$Promise_resolve_8JSObjectC(_ promise: JSObject, _ value: JSObject) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueValue = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_8JSObjectC(promiseValue, valueValue) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_5ThemeO(_ promise: JSObject, _ value: Theme) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_5ThemeO") +fileprivate func promise_resolve_BridgeJSRuntimeTests_5ThemeO_extern(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_5ThemeO_extern(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_5ThemeO(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_5ThemeO_extern(promise, valueBytes, valueLength) +} + +func _$Promise_resolve_5ThemeO(_ promise: JSObject, _ value: Theme) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + value.bridgeJSWithLoweredParameter { (valueBytes, valueLength) in + promise_resolve_BridgeJSRuntimeTests_5ThemeO(promiseValue, valueBytes, valueLength) + } + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_9DirectionO(_ promise: JSObject, _ value: Direction) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_9DirectionO") +fileprivate func promise_resolve_BridgeJSRuntimeTests_9DirectionO_extern(_ promise: Int32, _ value: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_9DirectionO_extern(_ promise: Int32, _ value: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_9DirectionO(_ promise: Int32, _ value: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_9DirectionO_extern(promise, value) +} + +func _$Promise_resolve_9DirectionO(_ promise: JSObject, _ value: Direction) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueValue = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_9DirectionO(promiseValue, valueValue) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_Sq5ThemeO(_ promise: JSObject, _ value: Optional) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sq5ThemeO") +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq5ThemeO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq5ThemeO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq5ThemeO(_ promise: Int32, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_Sq5ThemeO_extern(promise, valueIsSome, valueBytes, valueLength) +} + +func _$Promise_resolve_Sq5ThemeO(_ promise: JSObject, _ value: Optional) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + value.bridgeJSWithLoweredParameter { (valueIsSome, valueBytes, valueLength) in + promise_resolve_BridgeJSRuntimeTests_Sq5ThemeO(promiseValue, valueIsSome, valueBytes, valueLength) + } + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_Sq9DirectionO(_ promise: JSObject, _ value: Optional) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sq9DirectionO") +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq9DirectionO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq9DirectionO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq9DirectionO(_ promise: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_Sq9DirectionO_extern(promise, valueIsSome, valueValue) +} + +func _$Promise_resolve_Sq9DirectionO(_ promise: JSObject, _ value: Optional) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let (valueIsSome, valueValue) = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_Sq9DirectionO(promiseValue, valueIsSome, valueValue) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_Sa9DirectionO(_ promise: JSObject, _ value: [Direction]) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sa9DirectionO") +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sa9DirectionO_extern(_ promise: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sa9DirectionO_extern(_ promise: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sa9DirectionO(_ promise: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_Sa9DirectionO_extern(promise) +} + +func _$Promise_resolve_Sa9DirectionO(_ promise: JSObject, _ value: [Direction]) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let _ = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_Sa9DirectionO(promiseValue) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_SD9DirectionO(_ promise: JSObject, _ value: [String: Direction]) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_SD9DirectionO") +fileprivate func promise_resolve_BridgeJSRuntimeTests_SD9DirectionO_extern(_ promise: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_SD9DirectionO_extern(_ promise: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_SD9DirectionO(_ promise: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_SD9DirectionO_extern(promise) +} + +func _$Promise_resolve_SD9DirectionO(_ promise: JSObject, _ value: [String: Direction]) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let _ = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_SD9DirectionO(promiseValue) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_Sa5ThemeO(_ promise: JSObject, _ value: [Theme]) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sa5ThemeO") +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sa5ThemeO_extern(_ promise: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sa5ThemeO_extern(_ promise: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sa5ThemeO(_ promise: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_Sa5ThemeO_extern(promise) +} + +func _$Promise_resolve_Sa5ThemeO(_ promise: JSObject, _ value: [Theme]) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let _ = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_Sa5ThemeO(promiseValue) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_SD5ThemeO(_ promise: JSObject, _ value: [String: Theme]) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_SD5ThemeO") +fileprivate func promise_resolve_BridgeJSRuntimeTests_SD5ThemeO_extern(_ promise: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_SD5ThemeO_extern(_ promise: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_SD5ThemeO(_ promise: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_SD5ThemeO_extern(promise) +} + +func _$Promise_resolve_SD5ThemeO(_ promise: JSObject, _ value: [String: Theme]) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let _ = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_SD5ThemeO(promiseValue) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_8FileSizeO(_ promise: JSObject, _ value: FileSize) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_8FileSizeO") +fileprivate func promise_resolve_BridgeJSRuntimeTests_8FileSizeO_extern(_ promise: Int32, _ value: Int64) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_8FileSizeO_extern(_ promise: Int32, _ value: Int64) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_8FileSizeO(_ promise: Int32, _ value: Int64) -> Void { + return promise_resolve_BridgeJSRuntimeTests_8FileSizeO_extern(promise, value) +} + +func _$Promise_resolve_8FileSizeO(_ promise: JSObject, _ value: FileSize) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueValue = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_8FileSizeO(promiseValue, valueValue) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_Sq8FileSizeO(_ promise: JSObject, _ value: Optional) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sq8FileSizeO") +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq8FileSizeO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueValue: Int64) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq8FileSizeO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueValue: Int64) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq8FileSizeO(_ promise: Int32, _ valueIsSome: Int32, _ valueValue: Int64) -> Void { + return promise_resolve_BridgeJSRuntimeTests_Sq8FileSizeO_extern(promise, valueIsSome, valueValue) +} + +func _$Promise_resolve_Sq8FileSizeO(_ promise: JSObject, _ value: Optional) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let (valueIsSome, valueValue) = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_Sq8FileSizeO(promiseValue, valueIsSome, valueValue) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_11PublicPointV(_ promise: JSObject, _ value: PublicPoint) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_11PublicPointV") +fileprivate func promise_resolve_BridgeJSRuntimeTests_11PublicPointV_extern(_ promise: Int32, _ value: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_11PublicPointV_extern(_ promise: Int32, _ value: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_11PublicPointV(_ promise: Int32, _ value: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_11PublicPointV_extern(promise, value) +} + +func _$Promise_resolve_11PublicPointV(_ promise: JSObject, _ value: PublicPoint) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueObjectId = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_11PublicPointV(promiseValue, valueObjectId) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_7ContactV(_ promise: JSObject, _ value: Contact) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_7ContactV") +fileprivate func promise_resolve_BridgeJSRuntimeTests_7ContactV_extern(_ promise: Int32, _ value: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_7ContactV_extern(_ promise: Int32, _ value: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_7ContactV(_ promise: Int32, _ value: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_7ContactV_extern(promise, value) +} + +func _$Promise_resolve_7ContactV(_ promise: JSObject, _ value: Contact) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueObjectId = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_7ContactV(promiseValue, valueObjectId) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_Sa11PublicPointV(_ promise: JSObject, _ value: [PublicPoint]) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sa11PublicPointV") +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sa11PublicPointV_extern(_ promise: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sa11PublicPointV_extern(_ promise: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sa11PublicPointV(_ promise: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_Sa11PublicPointV_extern(promise) +} + +func _$Promise_resolve_Sa11PublicPointV(_ promise: JSObject, _ value: [PublicPoint]) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let _ = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_Sa11PublicPointV(promiseValue) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_Sq11PublicPointV(_ promise: JSObject, _ value: Optional) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sq11PublicPointV") +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq11PublicPointV_extern(_ promise: Int32, _ value: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq11PublicPointV_extern(_ promise: Int32, _ value: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq11PublicPointV(_ promise: Int32, _ value: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_Sq11PublicPointV_extern(promise, value) +} + +func _$Promise_resolve_Sq11PublicPointV(_ promise: JSObject, _ value: Optional) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueIsSome = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_Sq11PublicPointV(promiseValue, valueIsSome) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_SD11PublicPointV(_ promise: JSObject, _ value: [String: PublicPoint]) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_SD11PublicPointV") +fileprivate func promise_resolve_BridgeJSRuntimeTests_SD11PublicPointV_extern(_ promise: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_SD11PublicPointV_extern(_ promise: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_SD11PublicPointV(_ promise: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_SD11PublicPointV_extern(promise) +} + +func _$Promise_resolve_SD11PublicPointV(_ promise: JSObject, _ value: [String: PublicPoint]) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let _ = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_SD11PublicPointV(promiseValue) + if let error = _swift_js_take_exception() { throw error } +} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ArrayElementObject_init") fileprivate func bjs_ArrayElementObject_init_extern(_ idBytes: Int32, _ idLength: Int32) -> Int32 diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index a28843142..7be4d110e 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -908,6 +908,46 @@ } } } + }, + { + "abiName" : "bjs_Calculator_asyncMakePoint", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncMakePoint", + "parameters" : [ + { + "label" : "x", + "name" : "x", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "label" : "y", + "name" : "y", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "PublicPoint" + } + } } ], "name" : "Calculator", @@ -12569,233 +12609,557 @@ } }, { - "abiName" : "bjs_setHttpStatus", + "abiName" : "bjs_asyncRoundTripTheme", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "setHttpStatus", + "name" : "asyncRoundTripTheme", "parameters" : [ { "label" : "_", - "name" : "status", + "name" : "v", "type" : { "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" + "_0" : "Theme", + "_1" : "String" } } } ], "returnType" : { "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" - } - } - }, - { - "abiName" : "bjs_getHttpStatus", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "getHttpStatus", - "parameters" : [ - - ], - "returnType" : { - "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" + "_0" : "Theme", + "_1" : "String" } } }, { - "abiName" : "bjs_setFileSize", + "abiName" : "bjs_asyncRoundTripDirection", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "setFileSize", + "name" : "asyncRoundTripDirection", "parameters" : [ { "label" : "_", - "name" : "size", + "name" : "v", "type" : { - "rawValueEnum" : { - "_0" : "FileSize", - "_1" : "Int64" + "caseEnum" : { + "_0" : "Direction" } } } ], "returnType" : { - "rawValueEnum" : { - "_0" : "FileSize", - "_1" : "Int64" + "caseEnum" : { + "_0" : "Direction" } } }, { - "abiName" : "bjs_getFileSize", + "abiName" : "bjs_asyncRoundTripOptionalTheme", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "getFileSize", + "name" : "asyncRoundTripOptionalTheme", "parameters" : [ - + { + "label" : "_", + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + }, + "_1" : "null" + } + } + } ], "returnType" : { - "rawValueEnum" : { - "_0" : "FileSize", - "_1" : "Int64" + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_setSessionId", + "abiName" : "bjs_asyncRoundTripOptionalDirection", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "setSessionId", + "name" : "asyncRoundTripOptionalDirection", "parameters" : [ { "label" : "_", - "name" : "session", + "name" : "v", "type" : { - "rawValueEnum" : { - "_0" : "SessionId", - "_1" : "UInt64" + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + }, + "_1" : "null" } } } ], "returnType" : { - "rawValueEnum" : { - "_0" : "SessionId", - "_1" : "UInt64" + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_getSessionId", + "abiName" : "bjs_asyncRoundTripDirectionArray", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "getSessionId", + "name" : "asyncRoundTripDirectionArray", "parameters" : [ - + { + "label" : "_", + "name" : "v", + "type" : { + "array" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + } + } + } + } ], "returnType" : { - "rawValueEnum" : { - "_0" : "SessionId", - "_1" : "UInt64" + "array" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + } } } }, { - "abiName" : "bjs_processTheme", + "abiName" : "bjs_asyncRoundTripDirectionDict", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "processTheme", + "name" : "asyncRoundTripDirectionDict", "parameters" : [ { "label" : "_", - "name" : "theme", + "name" : "v", "type" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" + "dictionary" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + } } } } ], "returnType" : { - "rawValueEnum" : { - "_0" : "HttpStatus", - "_1" : "Int" + "dictionary" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + } } } }, { - "abiName" : "bjs_setTSDirection", + "abiName" : "bjs_asyncRoundTripThemeArray", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "setTSDirection", + "name" : "asyncRoundTripThemeArray", "parameters" : [ { "label" : "_", - "name" : "direction", + "name" : "v", "type" : { - "caseEnum" : { - "_0" : "TSDirection" + "array" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + } } } } ], "returnType" : { - "caseEnum" : { - "_0" : "TSDirection" + "array" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + } } } }, { - "abiName" : "bjs_getTSDirection", + "abiName" : "bjs_asyncRoundTripThemeDict", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "getTSDirection", + "name" : "asyncRoundTripThemeDict", "parameters" : [ - + { + "label" : "_", + "name" : "v", + "type" : { + "dictionary" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + } + } + } + } ], "returnType" : { - "caseEnum" : { - "_0" : "TSDirection" + "dictionary" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + } } } }, { - "abiName" : "bjs_setTSTheme", + "abiName" : "bjs_asyncRoundTripFileSize", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "setTSTheme", + "name" : "asyncRoundTripFileSize", "parameters" : [ { "label" : "_", - "name" : "theme", + "name" : "v", "type" : { "rawValueEnum" : { - "_0" : "TSTheme", - "_1" : "String" + "_0" : "FileSize", + "_1" : "Int64" } } } ], "returnType" : { "rawValueEnum" : { - "_0" : "TSTheme", - "_1" : "String" + "_0" : "FileSize", + "_1" : "Int64" + } + } + }, + { + "abiName" : "bjs_asyncRoundTripOptionalFileSize", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncRoundTripOptionalFileSize", + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "FileSize", + "_1" : "Int64" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "FileSize", + "_1" : "Int64" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_setHttpStatus", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "setHttpStatus", + "parameters" : [ + { + "label" : "_", + "name" : "status", + "type" : { + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" + } + } + } + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" + } + } + }, + { + "abiName" : "bjs_getHttpStatus", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getHttpStatus", + "parameters" : [ + + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" + } + } + }, + { + "abiName" : "bjs_setFileSize", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "setFileSize", + "parameters" : [ + { + "label" : "_", + "name" : "size", + "type" : { + "rawValueEnum" : { + "_0" : "FileSize", + "_1" : "Int64" + } + } + } + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "FileSize", + "_1" : "Int64" + } + } + }, + { + "abiName" : "bjs_getFileSize", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getFileSize", + "parameters" : [ + + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "FileSize", + "_1" : "Int64" + } + } + }, + { + "abiName" : "bjs_setSessionId", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "setSessionId", + "parameters" : [ + { + "label" : "_", + "name" : "session", + "type" : { + "rawValueEnum" : { + "_0" : "SessionId", + "_1" : "UInt64" + } + } + } + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "SessionId", + "_1" : "UInt64" + } + } + }, + { + "abiName" : "bjs_getSessionId", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getSessionId", + "parameters" : [ + + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "SessionId", + "_1" : "UInt64" + } + } + }, + { + "abiName" : "bjs_processTheme", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "processTheme", + "parameters" : [ + { + "label" : "_", + "name" : "theme", + "type" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + } + } + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "HttpStatus", + "_1" : "Int" + } + } + }, + { + "abiName" : "bjs_setTSDirection", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "setTSDirection", + "parameters" : [ + { + "label" : "_", + "name" : "direction", + "type" : { + "caseEnum" : { + "_0" : "TSDirection" + } + } + } + ], + "returnType" : { + "caseEnum" : { + "_0" : "TSDirection" + } + } + }, + { + "abiName" : "bjs_getTSDirection", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "getTSDirection", + "parameters" : [ + + ], + "returnType" : { + "caseEnum" : { + "_0" : "TSDirection" + } + } + }, + { + "abiName" : "bjs_setTSTheme", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "setTSTheme", + "parameters" : [ + { + "label" : "_", + "name" : "theme", + "type" : { + "rawValueEnum" : { + "_0" : "TSTheme", + "_1" : "String" + } + } + } + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "TSTheme", + "_1" : "String" } } }, @@ -14360,6 +14724,241 @@ } } }, + { + "abiName" : "bjs_asyncRoundTripPublicPoint", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncRoundTripPublicPoint", + "parameters" : [ + { + "label" : "_", + "name" : "point", + "type" : { + "swiftStruct" : { + "_0" : "PublicPoint" + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "PublicPoint" + } + } + }, + { + "abiName" : "bjs_asyncRoundTripPublicPointThrows", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "asyncRoundTripPublicPointThrows", + "parameters" : [ + { + "label" : "_", + "name" : "point", + "type" : { + "swiftStruct" : { + "_0" : "PublicPoint" + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "PublicPoint" + } + } + }, + { + "abiName" : "bjs_asyncStructOrThrow", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "asyncStructOrThrow", + "parameters" : [ + { + "label" : "_", + "name" : "shouldThrow", + "type" : { + "bool" : { + + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "PublicPoint" + } + } + }, + { + "abiName" : "bjs_asyncCombinePublicPoints", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncCombinePublicPoints", + "parameters" : [ + { + "label" : "_", + "name" : "a", + "type" : { + "swiftStruct" : { + "_0" : "PublicPoint" + } + } + }, + { + "label" : "_", + "name" : "b", + "type" : { + "swiftStruct" : { + "_0" : "PublicPoint" + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "PublicPoint" + } + } + }, + { + "abiName" : "bjs_asyncRoundTripContact", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncRoundTripContact", + "parameters" : [ + { + "label" : "_", + "name" : "contact", + "type" : { + "swiftStruct" : { + "_0" : "Contact" + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "Contact" + } + } + }, + { + "abiName" : "bjs_asyncRoundTripPublicPointArray", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncRoundTripPublicPointArray", + "parameters" : [ + { + "label" : "_", + "name" : "points", + "type" : { + "array" : { + "_0" : { + "swiftStruct" : { + "_0" : "PublicPoint" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "swiftStruct" : { + "_0" : "PublicPoint" + } + } + } + } + }, + { + "abiName" : "bjs_asyncRoundTripOptionalPublicPoint", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncRoundTripOptionalPublicPoint", + "parameters" : [ + { + "label" : "_", + "name" : "point", + "type" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "PublicPoint" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "PublicPoint" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_asyncRoundTripPublicPointDict", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncRoundTripPublicPointDict", + "parameters" : [ + { + "label" : "_", + "name" : "points", + "type" : { + "dictionary" : { + "_0" : { + "swiftStruct" : { + "_0" : "PublicPoint" + } + } + } + } + } + ], + "returnType" : { + "dictionary" : { + "_0" : { + "swiftStruct" : { + "_0" : "PublicPoint" + } + } + } + } + }, { "abiName" : "bjs_roundTripContact", "effects" : { diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/AsyncImportTests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/AsyncImportTests.mjs index f64531d4a..eca2b209c 100644 --- a/Tests/BridgeJSRuntimeTests/JavaScript/AsyncImportTests.mjs +++ b/Tests/BridgeJSRuntimeTests/JavaScript/AsyncImportTests.mjs @@ -1,6 +1,7 @@ // @ts-check import assert from 'node:assert'; +import { ThemeValues, DirectionValues, FileSizeValues } from '../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.js'; /** * @returns {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Imports["AsyncImportImports"]} @@ -43,4 +44,79 @@ export function getImports(importsContext) { /** @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports */ export async function runAsyncWorksTests(exports) { await exports.asyncRoundTripVoid(); + + const asyncPoint = { x: 7, y: 11 }; + assert.deepEqual(await exports.asyncRoundTripPublicPoint(asyncPoint), asyncPoint); + assert.deepEqual(await exports.asyncRoundTripPublicPointThrows(asyncPoint), asyncPoint); + + const [c1, c2] = await Promise.all([ + exports.asyncRoundTripPublicPoint({ x: 1, y: 2 }), + exports.asyncRoundTripPublicPoint({ x: 3, y: 4 }), + ]); + assert.deepEqual(c1, { x: 1, y: 2 }); + assert.deepEqual(c2, { x: 3, y: 4 }); + + assert.deepEqual(await exports.asyncCombinePublicPoints({ x: 1, y: 2 }, { x: 10, y: 20 }), { x: 11, y: 22 }); + + assert.deepEqual(await exports.asyncStructOrThrow(false), { x: 1, y: 2 }); + await assert.rejects( + () => exports.asyncStructOrThrow(true), + (error) => error instanceof Error && error.message === "async struct failure" + ); + + const richContact = { + name: "Alice", + age: 30, + address: { street: "123 Main St", city: "NYC", zipCode: 10001 }, + email: "alice@test.com", + secondaryAddress: { street: "456 Oak Ave", city: "LA", zipCode: null }, + }; + assert.deepEqual(await exports.asyncRoundTripContact(richContact), richContact); + + const calc = exports.createCalculator(); + assert.deepEqual(await calc.asyncMakePoint(3, 4), { x: 3, y: 4 }); + calc.release(); + + assert.equal(await exports.asyncRoundTripTheme(ThemeValues.Dark), ThemeValues.Dark); + assert.equal(await exports.asyncRoundTripDirection(DirectionValues.East), DirectionValues.East); + + assert.deepEqual( + await exports.asyncRoundTripPublicPointArray([{ x: 1, y: 2 }, { x: 3, y: 4 }]), + [{ x: 1, y: 2 }, { x: 3, y: 4 }] + ); + + assert.equal(await exports.asyncRoundTripOptionalTheme(ThemeValues.Light), ThemeValues.Light); + assert.equal(await exports.asyncRoundTripOptionalTheme(null), null); + assert.equal(await exports.asyncRoundTripOptionalDirection(DirectionValues.South), DirectionValues.South); + assert.equal(await exports.asyncRoundTripOptionalDirection(null), null); + + assert.deepEqual(await exports.asyncRoundTripOptionalPublicPoint({ x: 5, y: 6 }), { x: 5, y: 6 }); + assert.equal(await exports.asyncRoundTripOptionalPublicPoint(null), null); + + assert.deepEqual( + await exports.asyncRoundTripPublicPointDict({ a: { x: 1, y: 2 }, b: { x: 3, y: 4 } }), + { a: { x: 1, y: 2 }, b: { x: 3, y: 4 } } + ); + + assert.deepEqual( + await exports.asyncRoundTripDirectionArray([DirectionValues.North, DirectionValues.East]), + [DirectionValues.North, DirectionValues.East] + ); + assert.deepEqual( + await exports.asyncRoundTripDirectionDict({ a: DirectionValues.North, b: DirectionValues.South }), + { a: DirectionValues.North, b: DirectionValues.South } + ); + + assert.deepEqual( + await exports.asyncRoundTripThemeArray([ThemeValues.Light, ThemeValues.Dark]), + [ThemeValues.Light, ThemeValues.Dark] + ); + assert.deepEqual( + await exports.asyncRoundTripThemeDict({ a: ThemeValues.Light, b: ThemeValues.Auto }), + { a: ThemeValues.Light, b: ThemeValues.Auto } + ); + + assert.equal(await exports.asyncRoundTripFileSize(FileSizeValues.Large), FileSizeValues.Large); + assert.equal(await exports.asyncRoundTripOptionalFileSize(FileSizeValues.Tiny), FileSizeValues.Tiny); + assert.equal(await exports.asyncRoundTripOptionalFileSize(null), null); } diff --git a/Tests/BridgeJSRuntimeTests/StructAPIs.swift b/Tests/BridgeJSRuntimeTests/StructAPIs.swift index daa7ad1e2..c2216c808 100644 --- a/Tests/BridgeJSRuntimeTests/StructAPIs.swift +++ b/Tests/BridgeJSRuntimeTests/StructAPIs.swift @@ -210,6 +210,41 @@ extension Vector2D { point } +@JS public func asyncRoundTripPublicPoint(_ point: PublicPoint) async -> PublicPoint { + point +} + +@JS public func asyncRoundTripPublicPointThrows(_ point: PublicPoint) async throws(JSException) -> PublicPoint { + point +} + +@JS public func asyncStructOrThrow(_ shouldThrow: Bool) async throws(JSException) -> PublicPoint { + if shouldThrow { + throw JSException(JSError(message: "async struct failure").jsValue) + } + return PublicPoint(x: 1, y: 2) +} + +@JS public func asyncCombinePublicPoints(_ a: PublicPoint, _ b: PublicPoint) async -> PublicPoint { + PublicPoint(x: a.x + b.x, y: a.y + b.y) +} + +@JS func asyncRoundTripContact(_ contact: Contact) async -> Contact { + contact +} + +@JS public func asyncRoundTripPublicPointArray(_ points: [PublicPoint]) async -> [PublicPoint] { + points +} + +@JS public func asyncRoundTripOptionalPublicPoint(_ point: PublicPoint?) async -> PublicPoint? { + point +} + +@JS public func asyncRoundTripPublicPointDict(_ points: [String: PublicPoint]) async -> [String: PublicPoint] { + points +} + @JS func roundTripContact(_ contact: Contact) -> Contact { return contact } From 453b841f4fd78e6001c576f524b5bc597a9373bd Mon Sep 17 00:00:00 2001 From: Max Desiatov Date: Tue, 9 Jun 2026 21:13:15 +0100 Subject: [PATCH 08/50] Fix error descriptions Embedded Swift compatibility (#759) The BridgeJS generator emits `JSError(message: String(describing: error))` for throwing `@JS` exports, but `String.init(describing:)` is unavailable in Embedded Swift, so embedded Wasm builds of any package with a throwing export fail. The caught error is statically a `JSException` with a stored `description`, so the generated glue now uses `error.description` for identical output. Snapshots regenerated. --- .../PlayBridgeJS/Generated/BridgeJS.swift | 2 +- .../Sources/BridgeJSCore/ExportSwift.swift | 2 +- .../EnumNamespace.Global.swift | 2 +- .../BridgeJSCodegenTests/EnumNamespace.swift | 2 +- .../ImportedTypeInExportedInterface.swift | 2 +- .../BridgeJSCodegenTests/Throws.swift | 2 +- .../Generated/BridgeJS.swift | 18 +++++++++--------- 7 files changed, 15 insertions(+), 15 deletions(-) diff --git a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift index 920f2cc2f..37b024346 100644 --- a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift +++ b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift @@ -188,7 +188,7 @@ public func _bjs_PlayBridgeJS_updateDetailed(_ _self: UnsafeMutableRawPointer, _ _swift_js_throw(Int32(bitPattern: $0.id)) } } else { - let jsError = JSError(message: String(describing: error)) + let jsError = JSError(message: error.description) withExtendedLifetime(jsError.jsObject) { _swift_js_throw(Int32(bitPattern: $0.id)) } diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift index c9ef1e6f1..440960237 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift @@ -453,7 +453,7 @@ public class ExportSwift { _swift_js_throw(Int32(bitPattern: $0.id)) } } else { - let jsError = JSError(message: String(describing: error)) + let jsError = JSError(message: error.description) withExtendedLifetime(jsError.jsObject) { _swift_js_throw(Int32(bitPattern: $0.id)) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift index 5bde4ff93..4f588f6c7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift @@ -117,7 +117,7 @@ public func _bjs_Services_Graph_GraphOperations_static_validate(_ graphId: Int32 _swift_js_throw(Int32(bitPattern: $0.id)) } } else { - let jsError = JSError(message: String(describing: error)) + let jsError = JSError(message: error.description) withExtendedLifetime(jsError.jsObject) { _swift_js_throw(Int32(bitPattern: $0.id)) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift index 5bde4ff93..4f588f6c7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift @@ -117,7 +117,7 @@ public func _bjs_Services_Graph_GraphOperations_static_validate(_ graphId: Int32 _swift_js_throw(Int32(bitPattern: $0.id)) } } else { - let jsError = JSError(message: String(describing: error)) + let jsError = JSError(message: error.description) withExtendedLifetime(jsError.jsObject) { _swift_js_throw(Int32(bitPattern: $0.id)) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.swift index f3c3f2fc1..62f9a3b68 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.swift @@ -59,7 +59,7 @@ public func _bjs_makeFoo() -> Int32 { _swift_js_throw(Int32(bitPattern: $0.id)) } } else { - let jsError = JSError(message: String(describing: error)) + let jsError = JSError(message: error.description) withExtendedLifetime(jsError.jsObject) { _swift_js_throw(Int32(bitPattern: $0.id)) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Throws.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Throws.swift index 37f6d9c96..91787a642 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Throws.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Throws.swift @@ -10,7 +10,7 @@ public func _bjs_throwsSomething() -> Void { _swift_js_throw(Int32(bitPattern: $0.id)) } } else { - let jsError = JSError(message: String(describing: error)) + let jsError = JSError(message: error.description) withExtendedLifetime(jsError.jsObject) { _swift_js_throw(Int32(bitPattern: $0.id)) } diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index c20946b39..497fa3355 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -6967,7 +6967,7 @@ public func _bjs_makeImportedFoo(_ valueBytes: Int32, _ valueLength: Int32) -> I _swift_js_throw(Int32(bitPattern: $0.id)) } } else { - let jsError = JSError(message: String(describing: error)) + let jsError = JSError(message: error.description) withExtendedLifetime(jsError.jsObject) { _swift_js_throw(Int32(bitPattern: $0.id)) } @@ -7002,7 +7002,7 @@ public func _bjs_throwsSwiftError(_ shouldThrow: Int32) -> Void { _swift_js_throw(Int32(bitPattern: $0.id)) } } else { - let jsError = JSError(message: String(describing: error)) + let jsError = JSError(message: error.description) withExtendedLifetime(jsError.jsObject) { _swift_js_throw(Int32(bitPattern: $0.id)) } @@ -7027,7 +7027,7 @@ public func _bjs_throwsWithIntResult() -> Int32 { _swift_js_throw(Int32(bitPattern: $0.id)) } } else { - let jsError = JSError(message: String(describing: error)) + let jsError = JSError(message: error.description) withExtendedLifetime(jsError.jsObject) { _swift_js_throw(Int32(bitPattern: $0.id)) } @@ -7052,7 +7052,7 @@ public func _bjs_throwsWithStringResult() -> Void { _swift_js_throw(Int32(bitPattern: $0.id)) } } else { - let jsError = JSError(message: String(describing: error)) + let jsError = JSError(message: error.description) withExtendedLifetime(jsError.jsObject) { _swift_js_throw(Int32(bitPattern: $0.id)) } @@ -7077,7 +7077,7 @@ public func _bjs_throwsWithBoolResult() -> Int32 { _swift_js_throw(Int32(bitPattern: $0.id)) } } else { - let jsError = JSError(message: String(describing: error)) + let jsError = JSError(message: error.description) withExtendedLifetime(jsError.jsObject) { _swift_js_throw(Int32(bitPattern: $0.id)) } @@ -7102,7 +7102,7 @@ public func _bjs_throwsWithFloatResult() -> Float32 { _swift_js_throw(Int32(bitPattern: $0.id)) } } else { - let jsError = JSError(message: String(describing: error)) + let jsError = JSError(message: error.description) withExtendedLifetime(jsError.jsObject) { _swift_js_throw(Int32(bitPattern: $0.id)) } @@ -7127,7 +7127,7 @@ public func _bjs_throwsWithDoubleResult() -> Float64 { _swift_js_throw(Int32(bitPattern: $0.id)) } } else { - let jsError = JSError(message: String(describing: error)) + let jsError = JSError(message: error.description) withExtendedLifetime(jsError.jsObject) { _swift_js_throw(Int32(bitPattern: $0.id)) } @@ -7152,7 +7152,7 @@ public func _bjs_throwsWithSwiftHeapObjectResult() -> UnsafeMutableRawPointer { _swift_js_throw(Int32(bitPattern: $0.id)) } } else { - let jsError = JSError(message: String(describing: error)) + let jsError = JSError(message: error.description) withExtendedLifetime(jsError.jsObject) { _swift_js_throw(Int32(bitPattern: $0.id)) } @@ -7177,7 +7177,7 @@ public func _bjs_throwsWithJSObjectResult() -> Int32 { _swift_js_throw(Int32(bitPattern: $0.id)) } } else { - let jsError = JSError(message: String(describing: error)) + let jsError = JSError(message: error.description) withExtendedLifetime(jsError.jsObject) { _swift_js_throw(Int32(bitPattern: $0.id)) } From 1f2fe86b7fa10f10bd8f00f9a24e323d05171497 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Wed, 10 Jun 2026 13:55:21 +0200 Subject: [PATCH 09/50] BridgeJS: Fix reject path of zero-parameter async throwing exports --- .../Sources/BridgeJSCore/ExportSwift.swift | 34 +++++++++-- .../Inputs/MacroSwift/Async.swift | 4 ++ .../BridgeJSCodegenTests/Async.json | 17 ++++++ .../BridgeJSCodegenTests/Async.swift | 14 +++++ .../BridgeJSLinkTests/Async.d.ts | 1 + .../__Snapshots__/BridgeJSLinkTests/Async.js | 12 ++++ .../BridgeJSRuntimeTests/ExportAPITests.swift | 4 ++ .../Generated/BridgeJS.swift | 58 ++++++++++++------- .../Generated/JavaScript/BridgeJS.json | 17 ++++++ .../JavaScript/AsyncImportTests.mjs | 5 ++ 10 files changed, 139 insertions(+), 27 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift index 440960237..90c572b9d 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift @@ -426,21 +426,45 @@ public class ExportSwift { /// A throwing async body needs an explicit closure type, otherwise Swift infers /// `throws(any Error)` instead of `throws(JSException)`. /// See: https://github.com/swiftlang/swift/issues/76165 - private func asyncThrowsClosureHead(returnSpelling: String?) -> String { + private func asyncThrowsClosureHead(returnSpelling: String?, forcesCapture: Bool) -> String { guard effects.isThrows else { return "" } let returns = returnSpelling.map { " -> \($0)" } ?? "" - return " () async throws(JSException)\(returns) in" + let capture = forcesCapture ? "[__bjs_capture] " : "" + return " \(capture)() async throws(JSException)\(returns) in" + } + + /// A captureless throwing async body closure lowers via `thin_to_thick_function`, + /// which miscompiles typed-error calls on wasm32. Forcing a capture that the body + /// reads turns the closure into a partial apply with a context, avoiding the + /// broken convention. An unread capture list entry is dropped by capture analysis, + /// so the body must also read the captured value. + /// See: https://github.com/swiftlang/swift/issues/89320 + private var asyncThrowsBodyForcesCapture: Bool { + effects.isThrows && abiParameterSignatures.isEmpty && asyncHoistedBindings.isEmpty } func render(abiName: String) -> DeclSyntax { let body: CodeBlockItemListSyntax if effects.isAsync, let resolveType = asyncResolveReturnType { let resolveName = "Promise_resolve_\(resolveType.mangleTypeName)" - let closureHead = asyncThrowsClosureHead(returnSpelling: resolveType.swiftType) + let forcesCapture = asyncThrowsBodyForcesCapture + let closureHead = asyncThrowsClosureHead( + returnSpelling: resolveType.swiftType, + forcesCapture: forcesCapture + ) + var hoistedBindings = asyncHoistedBindings + var bodyItems = self.body + if forcesCapture { + hoistedBindings.append("let __bjs_capture = 0") + if !bodyItems.isEmpty { + bodyItems[0] = bodyItems[0].with(\.leadingTrivia, .newline) + } + bodyItems.insert("_ = __bjs_capture", at: 0) + } body = """ - \(CodeBlockItemListSyntax(asyncHoistedBindings)) + \(CodeBlockItemListSyntax(hoistedBindings)) return _bjs_makePromise(resolve: \(raw: resolveName), reject: Promise_reject) {\(raw: closureHead) - \(CodeBlockItemListSyntax(self.body)) + \(CodeBlockItemListSyntax(bodyItems)) } """ } else if effects.isThrows { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Async.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Async.swift index e63bea4ca..742d96ed2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Async.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Async.swift @@ -31,6 +31,10 @@ return v } +@JS func asyncThrowsZeroArg() async throws(JSException) -> String { + return "ok" +} + @JS func asyncCombineStructs(_ a: AsyncPoint, _ b: AsyncPoint) async -> AsyncPoint { return AsyncPoint(x: a.x + b.x, y: a.y + b.y) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.json index 3bd594419..8684291f0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.json @@ -283,6 +283,23 @@ } } }, + { + "abiName" : "bjs_asyncThrowsZeroArg", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "asyncThrowsZeroArg", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + }, { "abiName" : "bjs_asyncCombineStructs", "effects" : { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift index 28e6d8d8f..661fbd3a5 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift @@ -194,6 +194,20 @@ public func _bjs_asyncRoundTripStructThrows() -> Int32 { #endif } +@_expose(wasm, "bjs_asyncThrowsZeroArg") +@_cdecl("bjs_asyncThrowsZeroArg") +public func _bjs_asyncThrowsZeroArg() -> Int32 { + #if arch(wasm32) + let __bjs_capture = 0 + return _bjs_makePromise(resolve: Promise_resolve_SS, reject: Promise_reject) { [__bjs_capture] () async throws(JSException) -> String in + _ = __bjs_capture + return try await asyncThrowsZeroArg() + } + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_asyncCombineStructs") @_cdecl("bjs_asyncCombineStructs") public func _bjs_asyncCombineStructs() -> Int32 { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.d.ts index ddf722a3a..507a96d4a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.d.ts @@ -34,6 +34,7 @@ export type Exports = { asyncRoundTripJSObject(v: any): Promise; asyncRoundTripStruct(v: AsyncPoint): Promise; asyncRoundTripStructThrows(v: AsyncPoint): Promise; + asyncThrowsZeroArg(): Promise; asyncCombineStructs(a: AsyncPoint, b: AsyncPoint): Promise; asyncRoundTripEnum(v: AsyncDirectionTag): Promise; asyncRoundTripRawEnum(v: AsyncThemeTag): Promise; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js index 887102a76..9319cdd7e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js @@ -585,6 +585,18 @@ export async function createInstantiator(options, swift) { } return ret1; }, + asyncThrowsZeroArg: function bjs_asyncThrowsZeroArg() { + const ret = instance.exports.bjs_asyncThrowsZeroArg(); + const ret1 = swift.memory.getObject(ret); + swift.memory.release(ret); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + return ret1; + }, asyncCombineStructs: function bjs_asyncCombineStructs(a, b) { structHelpers.AsyncPoint.lower(a); structHelpers.AsyncPoint.lower(b); diff --git a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift index 79a931930..a0453b8f8 100644 --- a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift @@ -96,6 +96,10 @@ struct TestError: Error { @JS func throwsWithSwiftHeapObjectResult() throws(JSException) -> Greeter { return Greeter(name: "Test") } @JS func throwsWithJSObjectResult() throws(JSException) -> JSObject { return JSObject() } +@JS func zeroArgAsyncThrows() async throws(JSException) -> String { + throw JSException(JSError(message: "ZeroArgAsyncThrowsError").jsValue) +} + @JS func asyncRoundTripVoid() async -> Void { return } @JS func asyncRoundTripInt(v: Int) async -> Int { return v } @JS func asyncRoundTripFloat(v: Float) async -> Float { return v } diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 497fa3355..78bac8952 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -7189,6 +7189,20 @@ public func _bjs_throwsWithJSObjectResult() -> Int32 { #endif } +@_expose(wasm, "bjs_zeroArgAsyncThrows") +@_cdecl("bjs_zeroArgAsyncThrows") +public func _bjs_zeroArgAsyncThrows() -> Int32 { + #if arch(wasm32) + let __bjs_capture = 0 + return _bjs_makePromise(resolve: Promise_resolve_SS, reject: Promise_reject) { [__bjs_capture] () async throws(JSException) -> String in + _ = __bjs_capture + return try await zeroArgAsyncThrows() + } + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_asyncRoundTripVoid") @_cdecl("bjs_asyncRoundTripVoid") public func _bjs_asyncRoundTripVoid() -> Int32 { @@ -11403,6 +11417,28 @@ func _$Promise_reject(_ promise: JSObject, _ value: JSValue) throws(JSException) if let error = _swift_js_take_exception() { throw error } } +@JSFunction func Promise_resolve_SS(_ promise: JSObject, _ value: String) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_SS") +fileprivate func promise_resolve_BridgeJSRuntimeTests_SS_extern(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_SS_extern(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_SS(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_SS_extern(promise, valueBytes, valueLength) +} + +func _$Promise_resolve_SS(_ promise: JSObject, _ value: String) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + value.bridgeJSWithLoweredParameter { (valueBytes, valueLength) in + promise_resolve_BridgeJSRuntimeTests_SS(promiseValue, valueBytes, valueLength) + } + if let error = _swift_js_take_exception() { throw error } +} + @JSFunction func Promise_resolve_y(_ promise: JSObject) throws(JSException) #if arch(wasm32) @@ -11507,28 +11543,6 @@ func _$Promise_resolve_Sb(_ promise: JSObject, _ value: Bool) throws(JSException if let error = _swift_js_take_exception() { throw error } } -@JSFunction func Promise_resolve_SS(_ promise: JSObject, _ value: String) throws(JSException) - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_SS") -fileprivate func promise_resolve_BridgeJSRuntimeTests_SS_extern(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void -#else -fileprivate func promise_resolve_BridgeJSRuntimeTests_SS_extern(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_SS(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { - return promise_resolve_BridgeJSRuntimeTests_SS_extern(promise, valueBytes, valueLength) -} - -func _$Promise_resolve_SS(_ promise: JSObject, _ value: String) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() - value.bridgeJSWithLoweredParameter { (valueBytes, valueLength) in - promise_resolve_BridgeJSRuntimeTests_SS(promiseValue, valueBytes, valueLength) - } - if let error = _swift_js_take_exception() { throw error } -} - @JSFunction func Promise_resolve_7GreeterC(_ promise: JSObject, _ value: Greeter) throws(JSException) #if arch(wasm32) diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index d77883980..6535e9fc1 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -12171,6 +12171,23 @@ } } }, + { + "abiName" : "bjs_zeroArgAsyncThrows", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "zeroArgAsyncThrows", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + }, { "abiName" : "bjs_asyncRoundTripVoid", "effects" : { diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/AsyncImportTests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/AsyncImportTests.mjs index eca2b209c..1a767b184 100644 --- a/Tests/BridgeJSRuntimeTests/JavaScript/AsyncImportTests.mjs +++ b/Tests/BridgeJSRuntimeTests/JavaScript/AsyncImportTests.mjs @@ -64,6 +64,11 @@ export async function runAsyncWorksTests(exports) { (error) => error instanceof Error && error.message === "async struct failure" ); + await assert.rejects( + () => exports.zeroArgAsyncThrows(), + (error) => error instanceof Error && error.message === "ZeroArgAsyncThrowsError" + ); + const richContact = { name: "Alice", age: 30, From 8291fb97970c54656b2f51feccc09973913fd328 Mon Sep 17 00:00:00 2001 From: Yuta Saito Date: Thu, 11 Jun 2026 00:44:34 +0100 Subject: [PATCH 10/50] [codex] Drop Swift 6.1/6.2 support and raise MSSV to 6.3 (#762) * drop swift 6.1 * fix ci matrix * Detach async JS bridge tasks * Stabilize identity GC test * Revert detached async bridge tasks * Use Swift 6.2.4 in CI * Use Swift 6.2.3 in CI * Drop Swift 6.2 from CI * Document minimum Swift version * Add MSSV section to README * Fix async closure test formatting * Move tracing override to 24.04 matrix entry --- .github/workflows/test.yml | 17 +- Examples/Embedded/README.md | 2 +- Package@swift-6.1.swift | 222 ------------------ Plugins/PackageToJS/Tests/ExampleTests.swift | 7 - README.md | 4 + Sources/JavaScriptEventLoop/JSRemote.swift | 8 +- Sources/JavaScriptEventLoop/JSSending.swift | 17 +- .../JavaScriptEventLoop.swift | 6 +- .../WebWorkerTaskExecutor.swift | 6 +- .../FundamentalObjects/JSObject.swift | 10 +- Sources/JavaScriptKit/ThreadLocal.swift | 2 +- .../IdentityModeTests.swift | 4 +- .../JSClosure+AsyncTests.swift | 6 +- .../WebWorkerDedicatedExecutorTests.swift | 2 +- .../WebWorkerTaskExecutorTests.swift | 2 +- 15 files changed, 35 insertions(+), 280 deletions(-) delete mode 100644 Package@swift-6.1.swift diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index baba9c79b..58b2eb647 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -12,18 +12,13 @@ jobs: strategy: matrix: entry: - - os: ubuntu-22.04 - toolchain: - download-url: https://download.swift.org/swift-6.1-release/ubuntu2204/swift-6.1-RELEASE/swift-6.1-RELEASE-ubuntu22.04.tar.gz - wasi-backend: Node - target: "wasm32-unknown-wasi" - env: | - JAVASCRIPTKIT_DISABLE_TRACING_TRAIT=1 - os: ubuntu-24.04 toolchain: download-url: https://download.swift.org/development/ubuntu2404/swift-DEVELOPMENT-SNAPSHOT-2025-12-01-a/swift-DEVELOPMENT-SNAPSHOT-2025-12-01-a-ubuntu24.04.tar.gz wasi-backend: Node target: "wasm32-unknown-wasip1" + env: | + JAVASCRIPTKIT_DISABLE_TRACING_TRAIT=1 - os: ubuntu-24.04 toolchain: download-url: https://download.swift.org/swift-6.3-branch/ubuntu2404/swift-6.3-DEVELOPMENT-SNAPSHOT-2026-03-05-a/swift-6.3-DEVELOPMENT-SNAPSHOT-2026-03-05-a-ubuntu24.04.tar.gz @@ -77,10 +72,6 @@ jobs: strategy: matrix: entry: - - image: "swift:6.1.2" - swift-syntax-version: "601.0.0" - - image: "swift:6.2" - swift-syntax-version: "602.0.0" - image: "swift:6.3" swift-syntax-version: "603.0.0" runs-on: ubuntu-latest @@ -110,7 +101,7 @@ jobs: matrix: include: - os: macos-15 - xcode: Xcode_16.4 + xcode: Xcode_26.0.1 runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v6 @@ -134,7 +125,7 @@ jobs: format: runs-on: ubuntu-latest container: - image: swift:6.1.2 + image: swift:6.3 steps: - uses: actions/checkout@v6 - run: ./Utilities/format.swift diff --git a/Examples/Embedded/README.md b/Examples/Embedded/README.md index e99d659ff..97e2490b7 100644 --- a/Examples/Embedded/README.md +++ b/Examples/Embedded/README.md @@ -1,6 +1,6 @@ # Embedded example -Requires a recent DEVELOPMENT-SNAPSHOT toolchain. (tested with swift-6.1-DEVELOPMENT-SNAPSHOT-2025-02-21-a) +Requires a recent DEVELOPMENT-SNAPSHOT toolchain. ```sh $ ./build.sh diff --git a/Package@swift-6.1.swift b/Package@swift-6.1.swift deleted file mode 100644 index fe98ec529..000000000 --- a/Package@swift-6.1.swift +++ /dev/null @@ -1,222 +0,0 @@ -// swift-tools-version:6.1 - -import CompilerPluginSupport -import PackageDescription - -// NOTE: needed for embedded customizations, ideally this will not be necessary at all in the future, or can be replaced with traits -let shouldBuildForEmbedded = Context.environment["JAVASCRIPTKIT_EXPERIMENTAL_EMBEDDED_WASM"].flatMap(Bool.init) ?? false -let useLegacyResourceBundling = - Context.environment["JAVASCRIPTKIT_USE_LEGACY_RESOURCE_BUNDLING"].flatMap(Bool.init) ?? false - -let testingLinkerFlags: [LinkerSetting] = [ - .unsafeFlags( - [ - "-Xlinker", "--stack-first", - "-Xlinker", "--global-base=524288", - "-Xlinker", "-z", - "-Xlinker", "stack-size=524288", - ], - .when(platforms: [.wasi]) - ) -] - -let package = Package( - name: "JavaScriptKit", - platforms: [ - .macOS(.v13), - .iOS(.v13), - .tvOS(.v13), - .watchOS(.v6), - .macCatalyst(.v13), - ], - products: [ - .library(name: "JavaScriptKit", targets: ["JavaScriptKit"]), - .library(name: "JavaScriptEventLoop", targets: ["JavaScriptEventLoop"]), - .library(name: "JavaScriptBigIntSupport", targets: ["JavaScriptBigIntSupport"]), - .library(name: "JavaScriptFoundationCompat", targets: ["JavaScriptFoundationCompat"]), - .library(name: "JavaScriptEventLoopTestSupport", targets: ["JavaScriptEventLoopTestSupport"]), - .plugin(name: "PackageToJS", targets: ["PackageToJS"]), - .plugin(name: "BridgeJS", targets: ["BridgeJS"]), - .plugin(name: "BridgeJSCommandPlugin", targets: ["BridgeJSCommandPlugin"]), - ], - dependencies: [ - .package(url: "https://github.com/swiftlang/swift-syntax", "600.0.0"..<"603.0.0") - ], - targets: [ - .target( - name: "JavaScriptKit", - dependencies: ["_CJavaScriptKit", "BridgeJSMacros"], - exclude: useLegacyResourceBundling ? [] : ["Runtime"], - resources: useLegacyResourceBundling ? [.copy("Runtime")] : [], - cSettings: shouldBuildForEmbedded - ? [ - .unsafeFlags(["-fdeclspec"]) - ] : nil, - swiftSettings: [ - .enableExperimentalFeature("Extern") - ] - + (shouldBuildForEmbedded - ? [ - .enableExperimentalFeature("Embedded"), - .unsafeFlags(["-Xfrontend", "-emit-empty-object-file"]), - ] : []) - ), - .target(name: "_CJavaScriptKit"), - .macro( - name: "BridgeJSMacros", - dependencies: [ - .product(name: "SwiftSyntaxMacros", package: "swift-syntax"), - .product(name: "SwiftCompilerPlugin", package: "swift-syntax"), - ] - ), - - .testTarget( - name: "JavaScriptKitTests", - dependencies: ["JavaScriptKit"], - swiftSettings: [ - .enableExperimentalFeature("Extern") - ], - linkerSettings: testingLinkerFlags - ), - - .target( - name: "JavaScriptBigIntSupport", - dependencies: ["_CJavaScriptBigIntSupport", "JavaScriptKit"], - swiftSettings: shouldBuildForEmbedded - ? [ - .enableExperimentalFeature("Embedded"), - .unsafeFlags(["-Xfrontend", "-emit-empty-object-file"]), - ] : [] - ), - .target(name: "_CJavaScriptBigIntSupport", dependencies: ["_CJavaScriptKit"]), - .testTarget( - name: "JavaScriptBigIntSupportTests", - dependencies: ["JavaScriptBigIntSupport", "JavaScriptKit"], - linkerSettings: testingLinkerFlags - ), - - .target( - name: "JavaScriptEventLoop", - dependencies: ["JavaScriptKit", "_CJavaScriptEventLoop"], - swiftSettings: shouldBuildForEmbedded - ? [ - .enableExperimentalFeature("Embedded"), - .unsafeFlags(["-Xfrontend", "-emit-empty-object-file"]), - ] : [] - ), - .target(name: "_CJavaScriptEventLoop"), - .testTarget( - name: "JavaScriptEventLoopTests", - dependencies: [ - "JavaScriptEventLoop", - "JavaScriptKit", - "JavaScriptEventLoopTestSupport", - ], - swiftSettings: [ - .enableExperimentalFeature("Extern") - ], - linkerSettings: testingLinkerFlags - ), - .target( - name: "JavaScriptEventLoopTestSupport", - dependencies: [ - "_CJavaScriptEventLoopTestSupport", - "JavaScriptEventLoop", - ] - ), - .target(name: "_CJavaScriptEventLoopTestSupport"), - .testTarget( - name: "JavaScriptEventLoopTestSupportTests", - dependencies: [ - "JavaScriptKit", - "JavaScriptEventLoopTestSupport", - ], - linkerSettings: testingLinkerFlags - ), - .target( - name: "JavaScriptFoundationCompat", - dependencies: [ - "JavaScriptKit" - ] - ), - .testTarget( - name: "JavaScriptFoundationCompatTests", - dependencies: [ - "JavaScriptFoundationCompat" - ], - linkerSettings: testingLinkerFlags - ), - .plugin( - name: "PackageToJS", - capability: .command( - intent: .custom(verb: "js", description: "Convert a Swift package to a JavaScript package") - ), - path: "Plugins/PackageToJS/Sources" - ), - .plugin( - name: "BridgeJS", - capability: .buildTool(), - dependencies: ["BridgeJSTool"], - path: "Plugins/BridgeJS/Sources/BridgeJSBuildPlugin" - ), - .plugin( - name: "BridgeJSCommandPlugin", - capability: .command( - intent: .custom(verb: "bridge-js", description: "Generate bridging code"), - permissions: [.writeToPackageDirectory(reason: "Generate bridging code")] - ), - dependencies: ["BridgeJSTool"], - path: "Plugins/BridgeJS/Sources/BridgeJSCommandPlugin" - ), - .executableTarget( - name: "BridgeJSTool", - dependencies: [ - .product(name: "SwiftParser", package: "swift-syntax"), - .product(name: "SwiftSyntax", package: "swift-syntax"), - .product(name: "SwiftBasicFormat", package: "swift-syntax"), - .product(name: "SwiftSyntaxBuilder", package: "swift-syntax"), - ], - exclude: ["TS2Swift/JavaScript", "README.md"] - ), - .testTarget( - name: "BridgeJSRuntimeTests", - dependencies: ["JavaScriptKit", "JavaScriptEventLoop"], - exclude: [ - "bridge-js.config.json", - "bridge-js.d.ts", - "bridge-js.global.d.ts", - "Generated/JavaScript", - "JavaScript", - ], - swiftSettings: [ - .enableExperimentalFeature("Extern") - ], - linkerSettings: testingLinkerFlags - ), - .testTarget( - name: "BridgeJSGlobalTests", - dependencies: ["JavaScriptKit", "JavaScriptEventLoop"], - exclude: [ - "bridge-js.config.json", - "bridge-js.d.ts", - "Generated/JavaScript", - ], - swiftSettings: [ - .enableExperimentalFeature("Extern") - ], - linkerSettings: testingLinkerFlags - ), - .testTarget( - name: "BridgeJSIdentityTests", - dependencies: ["JavaScriptKit", "JavaScriptEventLoop"], - exclude: [ - "bridge-js.config.json", - "Generated/JavaScript", - ], - swiftSettings: [ - .enableExperimentalFeature("Extern") - ], - linkerSettings: testingLinkerFlags - ), - ] -) diff --git a/Plugins/PackageToJS/Tests/ExampleTests.swift b/Plugins/PackageToJS/Tests/ExampleTests.swift index d26832771..1f5bedcdc 100644 --- a/Plugins/PackageToJS/Tests/ExampleTests.swift +++ b/Plugins/PackageToJS/Tests/ExampleTests.swift @@ -297,7 +297,6 @@ extension Trait where Self == ConditionTrait { } } - #if compiler(>=6.1) @Test(.requireSwiftSDK) func testingWithCoverage() throws { let swiftSDKID = try #require(Self.getSwiftSDKID()) @@ -325,7 +324,6 @@ extension Trait where Self == ConditionTrait { } } } - #endif #endif // compiler(>=6.3) @Test(.requireSwiftSDK(triple: "wasm32-unknown-wasip1-threads")) @@ -379,7 +377,6 @@ extension Trait where Self == ConditionTrait { } } - #if compiler(>=6.1) // TODO: Remove triple restriction once swift-testing is shipped in p1-threads SDK @Test(.requireSwiftSDK(triple: "wasm32-unknown-wasi")) func continuationLeakInTest_SwiftTesting() throws { @@ -391,8 +388,6 @@ extension Trait where Self == ConditionTrait { try runSwift(["package", "--disable-sandbox", "--swift-sdk", swiftSDKID, "js", "test"], [:]) } } - #endif - @Test(.requireSwiftSDK) func playwrightOnPageLoad_XCTest() throws { let swiftSDKID = try #require(Self.getSwiftSDKID()) @@ -413,7 +408,6 @@ extension Trait where Self == ConditionTrait { } } - #if compiler(>=6.1) // TODO: Remove triple restriction once swift-testing is shipped in p1-threads SDK @Test(.requireSwiftSDK(triple: "wasm32-unknown-wasi")) func playwrightOnPageLoad_SwiftTesting() throws { @@ -434,5 +428,4 @@ extension Trait where Self == ConditionTrait { ) } } - #endif } diff --git a/README.md b/README.md index 03129c3e2..88c1332a2 100644 --- a/README.md +++ b/README.md @@ -120,6 +120,10 @@ Use the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/) Check out the [examples](https://github.com/swiftwasm/JavaScriptKit/tree/main/Examples) for more detailed usage patterns. +## Minimum Supported Swift Version (MSSV) + +The minimum supported Swift version is 6.3. + ## Contributing Contributions are welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for details on how to contribute to the project. diff --git a/Sources/JavaScriptEventLoop/JSRemote.swift b/Sources/JavaScriptEventLoop/JSRemote.swift index 4f488d7b8..b85b4991c 100644 --- a/Sources/JavaScriptEventLoop/JSRemote.swift +++ b/Sources/JavaScriptEventLoop/JSRemote.swift @@ -62,7 +62,7 @@ extension JSRemote where T == JSObject { /// /// - Parameter object: The JavaScript object to reference remotely. public init(_ object: JSObject) { - #if compiler(>=6.1) && _runtime(_multithreaded) + #if _runtime(_multithreaded) self.init(sourceObject: object, sourceTid: object.ownerTid) #else self.init(sourceObject: object, sourceTid: -1) @@ -92,7 +92,7 @@ extension JSRemote where T == JSObject { public func withJSObject( _ body: @Sendable @escaping (JSObject) throws(E) -> R ) async throws(E) -> sending R { - #if compiler(>=6.1) && _runtime(_multithreaded) + #if _runtime(_multithreaded) if storage.sourceTid == swjs_get_worker_thread_id_cached() { return try body(storage.sourceObject) } @@ -137,13 +137,11 @@ private final class _JSRemoteContext: @unchecked Sendable { } } -#if compiler(>=6.1) @_expose(wasm, "swjs_invoke_remote_jsobject_body") @_cdecl("swjs_invoke_remote_jsobject_body") -#endif @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) func _swjs_invoke_remote_jsobject_body(_ contextPtr: UnsafeRawPointer?) -> Bool { - #if compiler(>=6.1) && _runtime(_multithreaded) + #if _runtime(_multithreaded) guard let contextPtr else { return true } let context = Unmanaged<_JSRemoteContext>.fromOpaque(contextPtr).takeRetainedValue() diff --git a/Sources/JavaScriptEventLoop/JSSending.swift b/Sources/JavaScriptEventLoop/JSSending.swift index fb2fb1ddf..613abdd8a 100644 --- a/Sources/JavaScriptEventLoop/JSSending.swift +++ b/Sources/JavaScriptEventLoop/JSSending.swift @@ -105,7 +105,7 @@ extension JSSending where T == JSObject { construct: { $0 }, deconstruct: { $0 }, getSourceTid: { - #if compiler(>=6.1) && _runtime(_multithreaded) + #if _runtime(_multithreaded) return $0.ownerTid #else _ = $0 @@ -258,7 +258,7 @@ extension JSSending { file: StaticString = #file, line: UInt = #line ) async throws -> T { - #if compiler(>=6.1) && _runtime(_multithreaded) + #if _runtime(_multithreaded) let idInDestination = try await withCheckedThrowingContinuation { continuation in let context = _JSSendingContext(continuation: continuation) let idInSource = self.storage.idInSource @@ -278,8 +278,6 @@ extension JSSending { } #endif - // 6.0 and below can't compile the following without a compiler crash. - #if compiler(>=6.1) /// Receives multiple `JSSending` instances from a thread in a single operation. /// /// This method is more efficient than receiving multiple objects individually, as it @@ -317,7 +315,7 @@ extension JSSending { file: StaticString = #file, line: UInt = #line ) async throws -> (repeat each U) where T == (repeat each U) { - #if compiler(>=6.1) && _runtime(_multithreaded) + #if _runtime(_multithreaded) var sendingObjects: [JavaScriptObjectRef] = [] var transferringObjects: [JavaScriptObjectRef] = [] var sourceTid: Int32? @@ -363,7 +361,6 @@ extension JSSending { return try await (repeat (each sendings).receive()) #endif } - #endif // compiler(>=6.1) } @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) @@ -404,13 +401,11 @@ public struct JSSendingError: Error, CustomStringConvertible { /// - object: The `JSObject` to be received. /// - contextPtr: A pointer to the `_JSSendingContext` instance. // swift-format-ignore -#if compiler(>=6.1) // @_expose and @_extern are only available in Swift 6.1+ @_expose(wasm, "swjs_receive_response") @_cdecl("swjs_receive_response") -#endif @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) func _swjs_receive_response(_ object: JavaScriptObjectRef, _ contextPtr: UnsafeRawPointer?) { - #if compiler(>=6.1) && _runtime(_multithreaded) + #if _runtime(_multithreaded) guard let contextPtr = contextPtr else { return } let context = Unmanaged<_JSSendingContext>.fromOpaque(contextPtr).takeRetainedValue() context.continuation.resume(returning: object) @@ -424,13 +419,11 @@ func _swjs_receive_response(_ object: JavaScriptObjectRef, _ contextPtr: UnsafeR /// - error: The error to be received. /// - contextPtr: A pointer to the `_JSSendingContext` instance. // swift-format-ignore -#if compiler(>=6.1) // @_expose and @_extern are only available in Swift 6.1+ @_expose(wasm, "swjs_receive_error") @_cdecl("swjs_receive_error") -#endif @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) func _swjs_receive_error(_ error: JavaScriptObjectRef, _ contextPtr: UnsafeRawPointer?) { - #if compiler(>=6.1) && _runtime(_multithreaded) + #if _runtime(_multithreaded) guard let contextPtr = contextPtr else { return } let context = Unmanaged<_JSSendingContext>.fromOpaque(contextPtr).takeRetainedValue() context.continuation.resume(throwing: JSException(JSObject(id: error).jsValue)) diff --git a/Sources/JavaScriptEventLoop/JavaScriptEventLoop.swift b/Sources/JavaScriptEventLoop/JavaScriptEventLoop.swift index 5fc267ddc..ead6157bf 100644 --- a/Sources/JavaScriptEventLoop/JavaScriptEventLoop.swift +++ b/Sources/JavaScriptEventLoop/JavaScriptEventLoop.swift @@ -65,7 +65,7 @@ public final class JavaScriptEventLoop: SerialExecutor, @unchecked Sendable { return _shared } - #if compiler(>=6.1) && _runtime(_multithreaded) + #if _runtime(_multithreaded) // In multi-threaded environment, we have an event loop executor per // thread (per Web Worker). A job enqueued in one thread should be // executed in the same thread under this global executor. @@ -129,7 +129,7 @@ public final class JavaScriptEventLoop: SerialExecutor, @unchecked Sendable { _Concurrency._createExecutors(factory: JavaScriptEventLoop.self) } #else - // For Swift 6.1 and below, or Embedded Swift, we need to install + // For Embedded Swift, we need to install // the global executor by hook API. The ExecutorFactory mechanism // does not work in Embedded Swift because ExecutorImpl.swift is // excluded from the embedded Concurrency library. @@ -151,7 +151,7 @@ public final class JavaScriptEventLoop: SerialExecutor, @unchecked Sendable { } internal func unsafeEnqueue(_ job: UnownedJob) { - #if canImport(wasi_pthread) && compiler(>=6.1) && _runtime(_multithreaded) + #if canImport(wasi_pthread) && _runtime(_multithreaded) guard swjs_get_worker_thread_id_cached() == SWJS_MAIN_THREAD_ID else { // Notify the main thread to execute the job when a job is // enqueued from a Web Worker thread but without an executor preference. diff --git a/Sources/JavaScriptEventLoop/WebWorkerTaskExecutor.swift b/Sources/JavaScriptEventLoop/WebWorkerTaskExecutor.swift index b827ad980..b6bfb9c5f 100644 --- a/Sources/JavaScriptEventLoop/WebWorkerTaskExecutor.swift +++ b/Sources/JavaScriptEventLoop/WebWorkerTaskExecutor.swift @@ -385,7 +385,7 @@ public final class WebWorkerTaskExecutor: TaskExecutor { } func start(timeout: Duration, checkInterval: Duration) async throws { - #if canImport(wasi_pthread) && compiler(>=6.1) && _runtime(_multithreaded) + #if canImport(wasi_pthread) && _runtime(_multithreaded) class Context: @unchecked Sendable { let executor: WebWorkerTaskExecutor.Executor let worker: Worker @@ -610,9 +610,7 @@ public final class WebWorkerTaskExecutor: TaskExecutor { /// Enqueue a job scheduled from a Web Worker thread to the main thread. /// This function is called when a job is enqueued from a Web Worker thread. @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) -#if compiler(>=6.1) // @_expose and @_extern are only available in Swift 6.1+ @_expose(wasm, "swjs_enqueue_main_job_from_worker") -#endif func _swjs_enqueue_main_job_from_worker(_ job: UnownedJob) { WebWorkerTaskExecutor.traceStatsIncrement(\.receiveJobFromWorkerThread) JavaScriptEventLoop.shared.enqueue(ExecutorJob(job)) @@ -621,9 +619,7 @@ func _swjs_enqueue_main_job_from_worker(_ job: UnownedJob) { /// Wake up the worker thread. /// This function is called when a job is enqueued from the main thread to a worker thread. @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) -#if compiler(>=6.1) // @_expose and @_extern are only available in Swift 6.1+ @_expose(wasm, "swjs_wake_worker_thread") -#endif func _swjs_wake_worker_thread() { WebWorkerTaskExecutor.Worker.currentThread!.wakeUpFromOtherThread() } diff --git a/Sources/JavaScriptKit/FundamentalObjects/JSObject.swift b/Sources/JavaScriptKit/FundamentalObjects/JSObject.swift index 1b6facada..7bc799c64 100644 --- a/Sources/JavaScriptKit/FundamentalObjects/JSObject.swift +++ b/Sources/JavaScriptKit/FundamentalObjects/JSObject.swift @@ -22,7 +22,7 @@ public class JSObject: Equatable, ExpressibleByDictionaryLiteral { @usableFromInline internal var _id: JavaScriptObjectRef - #if compiler(>=6.1) && _runtime(_multithreaded) + #if _runtime(_multithreaded) package let ownerTid: Int32 #endif @@ -35,7 +35,7 @@ public class JSObject: Equatable, ExpressibleByDictionaryLiteral { @_spi(BridgeJS) public init(id: JavaScriptObjectRef) { self._id = id - #if compiler(>=6.1) && _runtime(_multithreaded) + #if _runtime(_multithreaded) self.ownerTid = swjs_get_worker_thread_id_cached() #endif } @@ -61,7 +61,7 @@ public class JSObject: Equatable, ExpressibleByDictionaryLiteral { /// is a programmer error and will result in a runtime assertion failure because JavaScript /// object spaces are not shared across threads backed by Web Workers. private func assertOnOwnerThread(hint: @autoclosure () -> String) { - #if compiler(>=6.1) && _runtime(_multithreaded) + #if _runtime(_multithreaded) precondition( ownerTid == swjs_get_worker_thread_id_cached(), "JSObject is being accessed from a thread other than the owner thread: \(hint())" @@ -71,7 +71,7 @@ public class JSObject: Equatable, ExpressibleByDictionaryLiteral { /// Asserts that the two objects being compared are owned by the same thread. private static func assertSameOwnerThread(lhs: JSObject, rhs: JSObject, hint: @autoclosure () -> String) { - #if compiler(>=6.1) && _runtime(_multithreaded) + #if _runtime(_multithreaded) precondition( lhs.ownerTid == rhs.ownerTid, "JSObject is being accessed from a thread other than the owner thread: \(hint())" @@ -282,7 +282,7 @@ public class JSObject: Equatable, ExpressibleByDictionaryLiteral { }) deinit { - #if compiler(>=6.1) && _runtime(_multithreaded) + #if _runtime(_multithreaded) if ownerTid != swjs_get_worker_thread_id_cached() { // If the object is not owned by the current thread swjs_release_remote(ownerTid, id) diff --git a/Sources/JavaScriptKit/ThreadLocal.swift b/Sources/JavaScriptKit/ThreadLocal.swift index 12bf78773..4c8bac75f 100644 --- a/Sources/JavaScriptKit/ThreadLocal.swift +++ b/Sources/JavaScriptKit/ThreadLocal.swift @@ -17,7 +17,7 @@ import Glibc /// The value is stored in a thread-local variable, which is a separate copy for each thread. @propertyWrapper final class ThreadLocal: Sendable { - #if compiler(>=6.1) && _runtime(_multithreaded) + #if _runtime(_multithreaded) /// The wrapped value stored in the thread-local storage. /// The initial value is `nil` for each thread. var wrappedValue: Value? { diff --git a/Tests/BridgeJSIdentityTests/IdentityModeTests.swift b/Tests/BridgeJSIdentityTests/IdentityModeTests.swift index 0aa036163..dacf85800 100644 --- a/Tests/BridgeJSIdentityTests/IdentityModeTests.swift +++ b/Tests/BridgeJSIdentityTests/IdentityModeTests.swift @@ -38,7 +38,9 @@ final class IdentityModeTests: XCTestCase { // let FinalizationRegistry fire and call deinit. for _ in 0..<100 { try gc() - try await Task.sleep(for: .milliseconds(0)) + // Give the JS runtime an actual turn so FinalizationRegistry callbacks + // can run before we check the Swift weak reference. + try await Task.sleep(for: .milliseconds(1)) if weakSubject == nil { break } diff --git a/Tests/JavaScriptEventLoopTests/JSClosure+AsyncTests.swift b/Tests/JavaScriptEventLoopTests/JSClosure+AsyncTests.swift index db093e549..e3c19a8e4 100644 --- a/Tests/JavaScriptEventLoopTests/JSClosure+AsyncTests.swift +++ b/Tests/JavaScriptEventLoopTests/JSClosure+AsyncTests.swift @@ -72,7 +72,7 @@ class JSClosureAsyncTests: XCTestCase { )!.value() XCTAssertEqual(result, 42.0) } - + func testAsyncOneshotClosureWithPriority() async throws { let priority = UnsafeSendableBox(nil) let closure = JSOneshotClosure.async(priority: .high) { _ in @@ -83,7 +83,7 @@ class JSClosureAsyncTests: XCTestCase { XCTAssertEqual(result, 42.0) XCTAssertEqual(priority.value, .high) } - + @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) func testAsyncOneshotClosureWithTaskExecutor() async throws { let executor = AnyTaskExecutor() @@ -93,7 +93,7 @@ class JSClosureAsyncTests: XCTestCase { let result = try await JSPromise(from: closure.function!())!.value() XCTAssertEqual(result, 42.0) } - + @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) func testAsyncOneshotClosureWithTaskExecutorPreference() async throws { let executor = AnyTaskExecutor() diff --git a/Tests/JavaScriptEventLoopTests/WebWorkerDedicatedExecutorTests.swift b/Tests/JavaScriptEventLoopTests/WebWorkerDedicatedExecutorTests.swift index aae8c2cea..b1dee1f3b 100644 --- a/Tests/JavaScriptEventLoopTests/WebWorkerDedicatedExecutorTests.swift +++ b/Tests/JavaScriptEventLoopTests/WebWorkerDedicatedExecutorTests.swift @@ -1,4 +1,4 @@ -#if compiler(>=6.1) && _runtime(_multithreaded) +#if _runtime(_multithreaded) import XCTest @testable import JavaScriptEventLoop diff --git a/Tests/JavaScriptEventLoopTests/WebWorkerTaskExecutorTests.swift b/Tests/JavaScriptEventLoopTests/WebWorkerTaskExecutorTests.swift index 69b3390dc..a40a039bd 100644 --- a/Tests/JavaScriptEventLoopTests/WebWorkerTaskExecutorTests.swift +++ b/Tests/JavaScriptEventLoopTests/WebWorkerTaskExecutorTests.swift @@ -1,4 +1,4 @@ -#if compiler(>=6.1) && _runtime(_multithreaded) +#if _runtime(_multithreaded) import Synchronization import XCTest import _CJavaScriptKit // For swjs_get_worker_thread_id From 6f4009c27b9cab8fa47d032dc03dfc370fbd9970 Mon Sep 17 00:00:00 2001 From: Yuta Saito Date: Thu, 11 Jun 2026 08:02:25 +0100 Subject: [PATCH 11/50] [codex] update to latest development snapshot toolchain (#763) * Use latest snapshot toolchain * Use native build system for examples * Use native build system in PackageToJS tests * Fix build-examples CI hang * Apply formatter output * Match formatter whitespace --- .github/workflows/test.yml | 12 ++-- Examples/ActorOnWebWorker/build.sh | 2 +- Examples/Basic/build.sh | 2 +- Examples/Embedded/build.sh | 2 +- Examples/Multithreading/build.sh | 2 +- Examples/OffscrenCanvas/build.sh | 2 +- Examples/PlayBridgeJS/build.sh | 2 +- Makefile | 2 +- Plugins/PackageToJS/Tests/ExampleTests.swift | 64 ++++++++++++++----- .../JavaScriptEventLoop+ExecutorFactory.swift | 13 ---- Utilities/build-examples.sh | 14 ++-- 11 files changed, 68 insertions(+), 49 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 58b2eb647..ef72ca352 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -14,7 +14,7 @@ jobs: entry: - os: ubuntu-24.04 toolchain: - download-url: https://download.swift.org/development/ubuntu2404/swift-DEVELOPMENT-SNAPSHOT-2025-12-01-a/swift-DEVELOPMENT-SNAPSHOT-2025-12-01-a-ubuntu24.04.tar.gz + download-url: https://download.swift.org/development/ubuntu2404/swift-DEVELOPMENT-SNAPSHOT-2026-05-27-a/swift-DEVELOPMENT-SNAPSHOT-2026-05-27-a-ubuntu24.04.tar.gz wasi-backend: Node target: "wasm32-unknown-wasip1" env: | @@ -26,7 +26,7 @@ jobs: target: "wasm32-unknown-wasip1" - os: ubuntu-22.04 toolchain: - download-url: https://download.swift.org/development/ubuntu2204/swift-DEVELOPMENT-SNAPSHOT-2025-12-01-a/swift-DEVELOPMENT-SNAPSHOT-2025-12-01-a-ubuntu22.04.tar.gz + download-url: https://download.swift.org/development/ubuntu2204/swift-DEVELOPMENT-SNAPSHOT-2026-05-27-a/swift-DEVELOPMENT-SNAPSHOT-2026-05-27-a-ubuntu22.04.tar.gz wasi-backend: Node target: "wasm32-unknown-wasip1-threads" @@ -143,7 +143,7 @@ jobs: - uses: actions/checkout@v6 - uses: ./.github/actions/install-swift with: - download-url: https://download.swift.org/development/ubuntu2204/swift-DEVELOPMENT-SNAPSHOT-2025-09-14-a/swift-DEVELOPMENT-SNAPSHOT-2025-09-14-a-ubuntu22.04.tar.gz + download-url: https://download.swift.org/development/ubuntu2204/swift-DEVELOPMENT-SNAPSHOT-2026-05-27-a/swift-DEVELOPMENT-SNAPSHOT-2026-05-27-a-ubuntu22.04.tar.gz - run: make bootstrap - run: ./Utilities/bridge-js-generate.sh - name: Check if BridgeJS generated files are up-to-date @@ -160,16 +160,14 @@ jobs: - uses: actions/checkout@v6 - uses: ./.github/actions/install-swift with: - download-url: https://download.swift.org/development/ubuntu2204/swift-DEVELOPMENT-SNAPSHOT-2026-03-09-a/swift-DEVELOPMENT-SNAPSHOT-2026-03-09-a-ubuntu22.04.tar.gz + download-url: https://download.swift.org/development/ubuntu2204/swift-DEVELOPMENT-SNAPSHOT-2026-05-27-a/swift-DEVELOPMENT-SNAPSHOT-2026-05-27-a-ubuntu22.04.tar.gz - uses: swiftwasm/setup-swiftwasm@v2 id: setup-wasm32-unknown-wasip1 with: { target: wasm32-unknown-wasip1 } - uses: swiftwasm/setup-swiftwasm@v2 id: setup-wasm32-unknown-wasip1-threads with: { target: wasm32-unknown-wasip1-threads } - - run: | - swift --version - ./Utilities/build-examples.sh + - run: ./Utilities/build-examples.sh env: SWIFT_SDK_ID_wasm32_unknown_wasip1_threads: ${{ steps.setup-wasm32-unknown-wasip1-threads.outputs.swift-sdk-id }} SWIFT_SDK_ID_wasm32_unknown_wasip1: ${{ steps.setup-wasm32-unknown-wasip1.outputs.swift-sdk-id }} diff --git a/Examples/ActorOnWebWorker/build.sh b/Examples/ActorOnWebWorker/build.sh index 4def77883..66c10a2c4 100755 --- a/Examples/ActorOnWebWorker/build.sh +++ b/Examples/ActorOnWebWorker/build.sh @@ -1,5 +1,5 @@ #!/bin/bash set -euxo pipefail -swift package --swift-sdk "${SWIFT_SDK_ID_wasm32_unknown_wasip1_threads:-${SWIFT_SDK_ID:-wasm32-unknown-wasip1-threads}}" \ +swift package --build-system native --swift-sdk "${SWIFT_SDK_ID_wasm32_unknown_wasip1_threads:-${SWIFT_SDK_ID:-wasm32-unknown-wasip1-threads}}" \ plugin --allow-writing-to-package-directory \ js --use-cdn --output ./Bundle -c release diff --git a/Examples/Basic/build.sh b/Examples/Basic/build.sh index 2351f4e2d..07f436c4b 100755 --- a/Examples/Basic/build.sh +++ b/Examples/Basic/build.sh @@ -1,3 +1,3 @@ #!/bin/bash set -euxo pipefail -swift package --swift-sdk "${SWIFT_SDK_ID_wasm32_unknown_wasip1:-${SWIFT_SDK_ID:-wasm32-unknown-wasip1}}" js --use-cdn -c "${1:-debug}" +swift package --build-system native --swift-sdk "${SWIFT_SDK_ID_wasm32_unknown_wasip1:-${SWIFT_SDK_ID:-wasm32-unknown-wasip1}}" js --use-cdn -c "${1:-debug}" diff --git a/Examples/Embedded/build.sh b/Examples/Embedded/build.sh index d756d8d1e..486f3581d 100755 --- a/Examples/Embedded/build.sh +++ b/Examples/Embedded/build.sh @@ -1,5 +1,5 @@ #!/bin/bash set -euxo pipefail package_dir="$(cd "$(dirname "$0")" && pwd)" -swift package --package-path "$package_dir" \ +swift package --build-system native --package-path "$package_dir" \ --swift-sdk "${SWIFT_SDK_ID_wasm32_unknown_wasip1:-${SWIFT_SDK_ID:-wasm32-unknown-wasip1}}-embedded" js -c release diff --git a/Examples/Multithreading/build.sh b/Examples/Multithreading/build.sh index 4def77883..66c10a2c4 100755 --- a/Examples/Multithreading/build.sh +++ b/Examples/Multithreading/build.sh @@ -1,5 +1,5 @@ #!/bin/bash set -euxo pipefail -swift package --swift-sdk "${SWIFT_SDK_ID_wasm32_unknown_wasip1_threads:-${SWIFT_SDK_ID:-wasm32-unknown-wasip1-threads}}" \ +swift package --build-system native --swift-sdk "${SWIFT_SDK_ID_wasm32_unknown_wasip1_threads:-${SWIFT_SDK_ID:-wasm32-unknown-wasip1-threads}}" \ plugin --allow-writing-to-package-directory \ js --use-cdn --output ./Bundle -c release diff --git a/Examples/OffscrenCanvas/build.sh b/Examples/OffscrenCanvas/build.sh index 4def77883..66c10a2c4 100755 --- a/Examples/OffscrenCanvas/build.sh +++ b/Examples/OffscrenCanvas/build.sh @@ -1,5 +1,5 @@ #!/bin/bash set -euxo pipefail -swift package --swift-sdk "${SWIFT_SDK_ID_wasm32_unknown_wasip1_threads:-${SWIFT_SDK_ID:-wasm32-unknown-wasip1-threads}}" \ +swift package --build-system native --swift-sdk "${SWIFT_SDK_ID_wasm32_unknown_wasip1_threads:-${SWIFT_SDK_ID:-wasm32-unknown-wasip1-threads}}" \ plugin --allow-writing-to-package-directory \ js --use-cdn --output ./Bundle -c release diff --git a/Examples/PlayBridgeJS/build.sh b/Examples/PlayBridgeJS/build.sh index 31c07896c..eb444a899 100755 --- a/Examples/PlayBridgeJS/build.sh +++ b/Examples/PlayBridgeJS/build.sh @@ -1,5 +1,5 @@ #!/bin/bash set -euxo pipefail -swift package --swift-sdk "${SWIFT_SDK_ID_wasm32_unknown_wasip1:-${SWIFT_SDK_ID:-wasm32-unknown-wasip1}}" \ +swift package --build-system native --swift-sdk "${SWIFT_SDK_ID_wasm32_unknown_wasip1:-${SWIFT_SDK_ID:-wasm32-unknown-wasip1}}" \ plugin --allow-writing-to-package-directory \ js --use-cdn --output ./Bundle -c "${1:-debug}" diff --git a/Makefile b/Makefile index 270eb9b36..4b174e347 100644 --- a/Makefile +++ b/Makefile @@ -16,7 +16,7 @@ unittest: echo "SWIFT_SDK_ID is not set. Run 'swift sdk list' and pass a matching SDK, e.g. 'make unittest SWIFT_SDK_ID='."; \ exit 2; \ } - swift package --swift-sdk "$(SWIFT_SDK_ID)" \ + swift package --build-system native --swift-sdk "$(SWIFT_SDK_ID)" \ $(TRACING_ARGS) \ --disable-sandbox \ js test --prelude ./Tests/prelude.mjs -Xnode --expose-gc diff --git a/Plugins/PackageToJS/Tests/ExampleTests.swift b/Plugins/PackageToJS/Tests/ExampleTests.swift index 1f5bedcdc..d131b329a 100644 --- a/Plugins/PackageToJS/Tests/ExampleTests.swift +++ b/Plugins/PackageToJS/Tests/ExampleTests.swift @@ -246,11 +246,26 @@ extension Trait where Self == ConditionTrait { func basic() throws { let swiftSDKID = try #require(Self.getSwiftSDKID()) try withPackage(at: "Examples/Basic") { packageDir, _, runSwift in - try runSwift(["package", "--swift-sdk", swiftSDKID, "js"], [:]) - try runSwift(["package", "--swift-sdk", swiftSDKID, "js", "--debug-info-format", "dwarf"], [:]) - try runSwift(["package", "--swift-sdk", swiftSDKID, "js", "--debug-info-format", "name"], [:]) + try runSwift(["package", "--build-system", "native", "--swift-sdk", swiftSDKID, "js"], [:]) try runSwift( - ["package", "--swift-sdk", swiftSDKID, "-Xswiftc", "-DJAVASCRIPTKIT_WITHOUT_WEAKREFS", "js"], + [ + "package", "--build-system", "native", "--swift-sdk", swiftSDKID, "js", "--debug-info-format", + "dwarf", + ], + [:] + ) + try runSwift( + [ + "package", "--build-system", "native", "--swift-sdk", swiftSDKID, "js", "--debug-info-format", + "name", + ], + [:] + ) + try runSwift( + [ + "package", "--build-system", "native", "--swift-sdk", swiftSDKID, "-Xswiftc", + "-DJAVASCRIPTKIT_WITHOUT_WEAKREFS", "js", + ], [:] ) } @@ -266,7 +281,10 @@ extension Trait where Self == ConditionTrait { try runProcess(which("npm"), ["install"], [:]) try runProcess(which("npx"), ["playwright", "install", "chromium-headless-shell"], [:]) - try runSwift(["package", "--disable-sandbox", "--swift-sdk", swiftSDKID, "js", "test"], [:]) + try runSwift( + ["package", "--build-system", "native", "--disable-sandbox", "--swift-sdk", swiftSDKID, "js", "test"], + [:] + ) try withTemporaryDirectory(body: { tempDir, _ in let scriptContent = """ const fs = require('fs'); @@ -278,7 +296,8 @@ extension Trait where Self == ConditionTrait { let scriptPath = tempDir.appending(path: "script.js") try runSwift( [ - "package", "--disable-sandbox", "--swift-sdk", swiftSDKID, "js", "test", + "package", "--build-system", "native", "--disable-sandbox", "--swift-sdk", swiftSDKID, "js", + "test", "-Xnode=--require=\(scriptPath.path)", ], [:] @@ -291,7 +310,10 @@ extension Trait where Self == ConditionTrait { ) }) try runSwift( - ["package", "--disable-sandbox", "--swift-sdk", swiftSDKID, "js", "test", "--environment", "browser"], + [ + "package", "--build-system", "native", "--disable-sandbox", "--swift-sdk", swiftSDKID, "js", "test", + "--environment", "browser", + ], [:] ) } @@ -303,7 +325,10 @@ extension Trait where Self == ConditionTrait { let swiftPath = try #require(Self.getSwiftPath()) try withPackage(at: "Examples/Testing") { packageDir, runProcess, runSwift in try runSwift( - ["package", "--disable-sandbox", "--swift-sdk", swiftSDKID, "js", "test", "--enable-code-coverage"], + [ + "package", "--build-system", "native", "--disable-sandbox", "--swift-sdk", swiftSDKID, "js", "test", + "--enable-code-coverage", + ], [ "LLVM_PROFDATA_PATH": URL(fileURLWithPath: swiftPath).appending(path: "llvm-profdata").path ] @@ -330,7 +355,7 @@ extension Trait where Self == ConditionTrait { func multithreading() throws { let swiftSDKID = try #require(Self.getSwiftSDKID()) try withPackage(at: "Examples/Multithreading") { packageDir, _, runSwift in - try runSwift(["package", "--swift-sdk", swiftSDKID, "js"], [:]) + try runSwift(["package", "--build-system", "native", "--swift-sdk", swiftSDKID, "js"], [:]) } } @@ -338,7 +363,7 @@ extension Trait where Self == ConditionTrait { func offscreenCanvas() throws { let swiftSDKID = try #require(Self.getSwiftSDKID()) try withPackage(at: "Examples/OffscrenCanvas") { packageDir, _, runSwift in - try runSwift(["package", "--swift-sdk", swiftSDKID, "js"], [:]) + try runSwift(["package", "--build-system", "native", "--swift-sdk", swiftSDKID, "js"], [:]) } } @@ -346,7 +371,7 @@ extension Trait where Self == ConditionTrait { func actorOnWebWorker() throws { let swiftSDKID = try #require(Self.getSwiftSDKID()) try withPackage(at: "Examples/ActorOnWebWorker") { packageDir, _, runSwift in - try runSwift(["package", "--swift-sdk", swiftSDKID, "js"], [:]) + try runSwift(["package", "--build-system", "native", "--swift-sdk", swiftSDKID, "js"], [:]) } } @@ -357,7 +382,7 @@ extension Trait where Self == ConditionTrait { let swiftSDKID = try #require(Self.getEmbeddedSwiftSDKID()) try withPackage(at: "Examples/Embedded") { packageDir, _, runSwift in try runSwift( - ["package", "--swift-sdk", swiftSDKID, "js", "-c", "release"], + ["package", "--build-system", "native", "--swift-sdk", swiftSDKID, "js", "-c", "release"], [ "JAVASCRIPTKIT_EXPERIMENTAL_EMBEDDED_WASM": "true" ] @@ -373,7 +398,10 @@ extension Trait where Self == ConditionTrait { at: "Plugins/PackageToJS/Fixtures/ContinuationLeakInTest/XCTest", assertTerminationStatus: { $0 != 0 } ) { packageDir, _, runSwift in - try runSwift(["package", "--disable-sandbox", "--swift-sdk", swiftSDKID, "js", "test"], [:]) + try runSwift( + ["package", "--build-system", "native", "--disable-sandbox", "--swift-sdk", swiftSDKID, "js", "test"], + [:] + ) } } @@ -385,7 +413,10 @@ extension Trait where Self == ConditionTrait { at: "Plugins/PackageToJS/Fixtures/ContinuationLeakInTest/SwiftTesting", assertTerminationStatus: { $0 != 0 } ) { packageDir, _, runSwift in - try runSwift(["package", "--disable-sandbox", "--swift-sdk", swiftSDKID, "js", "test"], [:]) + try runSwift( + ["package", "--build-system", "native", "--disable-sandbox", "--swift-sdk", swiftSDKID, "js", "test"], + [:] + ) } } @Test(.requireSwiftSDK) @@ -400,7 +431,7 @@ extension Trait where Self == ConditionTrait { try runSwift( ["package", "--disable-sandbox"] + Self.stackSizeLinkerFlags + [ - "--swift-sdk", swiftSDKID, "js", "test", "--environment", "browser", + "--build-system", "native", "--swift-sdk", swiftSDKID, "js", "test", "--environment", "browser", "--playwright-expose", "../expose.js", ], [:] @@ -421,7 +452,8 @@ extension Trait where Self == ConditionTrait { try runSwift( [ - "package", "--disable-sandbox", "--swift-sdk", swiftSDKID, "js", "test", "--environment", "browser", + "package", "--build-system", "native", "--disable-sandbox", "--swift-sdk", swiftSDKID, "js", "test", + "--environment", "browser", "--playwright-expose", "../expose.js", ], [:] diff --git a/Sources/JavaScriptEventLoop/JavaScriptEventLoop+ExecutorFactory.swift b/Sources/JavaScriptEventLoop/JavaScriptEventLoop+ExecutorFactory.swift index 0d2010016..17aedca3b 100644 --- a/Sources/JavaScriptEventLoop/JavaScriptEventLoop+ExecutorFactory.swift +++ b/Sources/JavaScriptEventLoop/JavaScriptEventLoop+ExecutorFactory.swift @@ -57,25 +57,12 @@ extension JavaScriptEventLoop: SchedulingExecutor { #endif // #if compiler(>=6.4) (Embedded) #else // #if hasFeature(Embedded) let duration: Duration - // Handle clocks we know if let _ = clock as? ContinuousClock { duration = delay as! ContinuousClock.Duration } else if let _ = clock as? SuspendingClock { duration = delay as! SuspendingClock.Duration } else { - #if compiler(>=6.4) - // Hand-off the scheduling work to Clock implementation for unknown clocks. - // Clock.enqueue is only available in the development branch (6.4+). - clock.enqueue( - job, - on: self, - at: clock.now.advanced(by: delay), - tolerance: tolerance - ) - return - #else fatalError("Unsupported clock type; only ContinuousClock and SuspendingClock are supported") - #endif // #if compiler(>=6.4) (non-Embedded) } let milliseconds = Self.delayInMilliseconds(from: duration) self.enqueue( diff --git a/Utilities/build-examples.sh b/Utilities/build-examples.sh index bc84e6943..77e923322 100755 --- a/Utilities/build-examples.sh +++ b/Utilities/build-examples.sh @@ -6,12 +6,14 @@ EXCLUDED_EXAMPLES=() for example in Examples/*; do skip_example=false - for excluded in "${EXCLUDED_EXAMPLES[@]}"; do - if [[ "$example" == *"$excluded"* ]]; then - skip_example=true - break - fi - done + if ((${#EXCLUDED_EXAMPLES[@]})); then + for excluded in "${EXCLUDED_EXAMPLES[@]}"; do + if [[ "$example" == *"$excluded"* ]]; then + skip_example=true + break + fi + done + fi if [ "$skip_example" = true ]; then echo "Skipping $example" continue From 3396b5eeda2a979679996bdeeddcf43ad3d26eff Mon Sep 17 00:00:00 2001 From: Yuta Saito Date: Thu, 11 Jun 2026 08:05:42 +0100 Subject: [PATCH 12/50] [codex] BridgeJS: support associated-value enums in import and async paths (#764) * BridgeJS: support associated-value enums in import and async paths * Format Swift sources * Match Swift 6.1 formatter output --- .../Sources/BridgeJSCore/ImportTS.swift | 14 +- .../Sources/BridgeJSLink/JSGlueGen.swift | 44 +- .../BridgeJSSkeleton/BridgeJSSkeleton.swift | 4 +- .../BridgeJSToolTests/DiagnosticsTests.swift | 13 +- .../MacroSwift/AsyncAssociatedValueEnum.swift | 13 + .../EnumAssociatedValueImport.swift | 14 + .../AsyncAssociatedValueEnum.json | 129 ++++++ .../AsyncAssociatedValueEnum.swift | 116 +++++ .../EnumAssociatedValueImport.json | 194 ++++++++ .../EnumAssociatedValueImport.swift | 112 +++++ .../AsyncAssociatedValueEnum.d.ts | 33 ++ .../AsyncAssociatedValueEnum.js | 414 ++++++++++++++++++ .../EnumAssociatedValueImport.d.ts | 39 ++ .../EnumAssociatedValueImport.js | 323 ++++++++++++++ .../AsyncImportTests.swift | 35 ++ .../BridgeJSRuntimeTests/ExportAPITests.swift | 10 + .../Generated/BridgeJS.swift | 364 +++++++++++++++ .../Generated/JavaScript/BridgeJS.json | 317 ++++++++++++++ .../BridgeJSRuntimeTests/ImportAPITests.swift | 35 ++ .../JavaScript/AsyncImportTests.mjs | 19 +- Tests/prelude.mjs | 6 + 21 files changed, 2196 insertions(+), 52 deletions(-) create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/AsyncAssociatedValueEnum.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/EnumAssociatedValueImport.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncAssociatedValueEnum.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncAssociatedValueEnum.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValueImport.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValueImport.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.d.ts create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.d.ts create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift index 02c623918..a6a73b8f7 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift @@ -936,12 +936,7 @@ extension BridgeType { let wasmType = rawType.wasmCoreType ?? .i32 return LoweringParameterInfo(loweredParameters: [("value", wasmType)]) case .associatedValueEnum: - switch context { - case .importTS: - throw BridgeJSCoreError("Enum types are not yet supported in TypeScript imports") - case .exportSwift: - return LoweringParameterInfo(loweredParameters: [("caseId", .i32)]) - } + return LoweringParameterInfo(loweredParameters: [("caseId", .i32)]) case .swiftStruct: switch context { case .importTS: @@ -1011,12 +1006,7 @@ extension BridgeType { let wasmType = rawType.wasmCoreType ?? .i32 return LiftingReturnInfo(valueToLift: wasmType) case .associatedValueEnum: - switch context { - case .importTS: - throw BridgeJSCoreError("Enum types are not yet supported in TypeScript imports") - case .exportSwift: - return LiftingReturnInfo(valueToLift: .i32) - } + return LiftingReturnInfo(valueToLift: .i32) case .swiftStruct: switch context { case .importTS: diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift index aed01da5a..ac2144bbc 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift @@ -1422,27 +1422,19 @@ struct IntrinsicJSFragment: Sendable { return try .optionalLiftParameter(wrappedType: wrappedType, kind: kind, context: context) case .rawValueEnum(_, .string): return .stringLiftParameter case .associatedValueEnum(let fullName): - switch context { - case .importTS: - throw BridgeJSLinkError( - message: - "Associated value enums are not supported to be passed as parameters to imported JS functions: \(fullName)" - ) - case .exportSwift: - let base = fullName.components(separatedBy: ".").last ?? fullName - return IntrinsicJSFragment( - parameters: ["caseId"], - printCode: { arguments, context in - let (scope, printer) = (context.scope, context.printer) - let caseId = arguments[0] - let resultVar = scope.variable("enumValue") - printer.write( - "const \(resultVar) = \(JSGlueVariableScope.reservedEnumHelpers).\(base).lift(\(caseId));" - ) - return [resultVar] - } - ) - } + let base = fullName.components(separatedBy: ".").last ?? fullName + return IntrinsicJSFragment( + parameters: ["caseId"], + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) + let caseId = arguments[0] + let resultVar = scope.variable("enumValue") + printer.write( + "const \(resultVar) = \(JSGlueVariableScope.reservedEnumHelpers).\(base).lift(\(caseId));" + ) + return [resultVar] + } + ) case .swiftStruct(let fullName): switch context { case .importTS: @@ -1502,15 +1494,7 @@ struct IntrinsicJSFragment: Sendable { return try .optionalLowerReturn(wrappedType: wrappedType, kind: kind) case .rawValueEnum(_, .string): return .stringLowerReturn case .associatedValueEnum(let fullName): - switch context { - case .importTS: - throw BridgeJSLinkError( - message: - "Associated value enums are not supported to be returned from imported JS functions: \(fullName)" - ) - case .exportSwift: - return associatedValueLowerReturn(fullName: fullName) - } + return associatedValueLowerReturn(fullName: fullName) case .swiftStruct(let fullName): switch context { case .importTS: diff --git a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift index f1e2e80fe..830132481 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift @@ -1611,10 +1611,10 @@ extension BridgeType { /// Whether a value of this type can be passed to a generated `Promise_resolve_` /// settlement helper, i.e. lowered through the imported-parameter ABI. Every `async` /// exported return settles through `_bjs_makePromise`; the few types that cannot be lowered - /// (associated-value enums, protocols, namespace enums, and their compositions) are diagnosed. + /// (protocols, namespace enums, and their compositions) are diagnosed. public var isAsyncResolvable: Bool { switch self { - case .associatedValueEnum, .swiftProtocol, .namespaceEnum: + case .swiftProtocol, .namespaceEnum: return false case .nullable(let wrapped, _): return wrapped.isAsyncResolvable diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift index 82747f74e..ae12b6566 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift @@ -309,15 +309,14 @@ import Testing @Test func asyncReturnOfUnsupportedTypeIsDiagnosed() throws { - // An associated-value enum can be neither lowered through the imported-parameter ABI - // nor settled via `_bjs_makePromise`, so an async return of one must be diagnosed. + // Protocol existentials still can't be lowered through the imported-parameter ABI, so + // an async return of one must still be diagnosed. let source = """ - @JS enum Payload { - case text(String) - case number(Int) + @JS protocol PayloadDelegate { + func notify() } - @JS func loadPayload() async -> Payload { - .number(1) + @JS func loadPayload() async -> PayloadDelegate { + fatalError() } """ let swiftAPI = SwiftToSkeleton( diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/AsyncAssociatedValueEnum.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/AsyncAssociatedValueEnum.swift new file mode 100644 index 000000000..662e01fce --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/AsyncAssociatedValueEnum.swift @@ -0,0 +1,13 @@ +@JS enum AsyncPayloadResult { + case success(String) + case failure(Int) + case idle +} + +@JS func asyncRoundTripAssociatedValueEnum(_ value: AsyncPayloadResult) async -> AsyncPayloadResult { + return value +} + +@JS func asyncRoundTripOptionalAssociatedValueEnum(_ value: AsyncPayloadResult?) async -> AsyncPayloadResult? { + return value +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/EnumAssociatedValueImport.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/EnumAssociatedValueImport.swift new file mode 100644 index 000000000..aa404b72c --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/EnumAssociatedValueImport.swift @@ -0,0 +1,14 @@ +@JS enum PayloadSignal { + case start(String) + case stop(Int) + case idle +} + +// Associated-value enums bridge as their `Int32` case ID plus stack payload in imported +// function parameters and return values. +@JSClass struct PayloadSignalControls { + @JSFunction func send(_ signal: PayloadSignal) throws(JSException) + @JSFunction func current() throws(JSException) -> PayloadSignal + @JSFunction static func roundTrip(_ signal: PayloadSignal) throws(JSException) -> PayloadSignal + @JSFunction func roundTripOptional(_ signal: PayloadSignal?) throws(JSException) -> PayloadSignal? +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncAssociatedValueEnum.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncAssociatedValueEnum.json new file mode 100644 index 000000000..6b0d70453 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncAssociatedValueEnum.json @@ -0,0 +1,129 @@ +{ + "exported" : { + "classes" : [ + + ], + "enums" : [ + { + "cases" : [ + { + "associatedValues" : [ + { + "type" : { + "string" : { + + } + } + } + ], + "name" : "success" + }, + { + "associatedValues" : [ + { + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "name" : "failure" + }, + { + "associatedValues" : [ + + ], + "name" : "idle" + } + ], + "emitStyle" : "const", + "name" : "AsyncPayloadResult", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "AsyncPayloadResult", + "tsFullPath" : "AsyncPayloadResult" + } + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_asyncRoundTripAssociatedValueEnum", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncRoundTripAssociatedValueEnum", + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "associatedValueEnum" : { + "_0" : "AsyncPayloadResult" + } + } + } + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "AsyncPayloadResult" + } + } + }, + { + "abiName" : "bjs_asyncRoundTripOptionalAssociatedValueEnum", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncRoundTripOptionalAssociatedValueEnum", + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "AsyncPayloadResult" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "AsyncPayloadResult" + } + }, + "_1" : "null" + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncAssociatedValueEnum.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncAssociatedValueEnum.swift new file mode 100644 index 000000000..7ceb8cfe3 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncAssociatedValueEnum.swift @@ -0,0 +1,116 @@ +extension AsyncPayloadResult: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> AsyncPayloadResult { + switch caseId { + case 0: + return .success(String.bridgeJSStackPop()) + case 1: + return .failure(Int.bridgeJSStackPop()) + case 2: + return .idle + default: + fatalError("Unknown AsyncPayloadResult case ID: \(caseId)") + } + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { + switch self { + case .success(let param0): + param0.bridgeJSStackPush() + return Int32(0) + case .failure(let param0): + param0.bridgeJSStackPush() + return Int32(1) + case .idle: + return Int32(2) + } + } +} + +@_expose(wasm, "bjs_asyncRoundTripAssociatedValueEnum") +@_cdecl("bjs_asyncRoundTripAssociatedValueEnum") +public func _bjs_asyncRoundTripAssociatedValueEnum(_ value: Int32) -> Int32 { + #if arch(wasm32) + let _tmp_value = AsyncPayloadResult.bridgeJSLiftParameter(value) + return _bjs_makePromise(resolve: Promise_resolve_18AsyncPayloadResultO, reject: Promise_reject) { + return await asyncRoundTripAssociatedValueEnum(_: _tmp_value) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_asyncRoundTripOptionalAssociatedValueEnum") +@_cdecl("bjs_asyncRoundTripOptionalAssociatedValueEnum") +public func _bjs_asyncRoundTripOptionalAssociatedValueEnum(_ valueIsSome: Int32, _ valueCaseId: Int32) -> Int32 { + #if arch(wasm32) + let _tmp_value = Optional.bridgeJSLiftParameter(valueIsSome, valueCaseId) + return _bjs_makePromise(resolve: Promise_resolve_Sq18AsyncPayloadResultO, reject: Promise_reject) { + return await asyncRoundTripOptionalAssociatedValueEnum(_: _tmp_value) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@JSFunction func Promise_reject(_ promise: JSObject, _ value: JSValue) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_reject_TestModule") +fileprivate func promise_reject_TestModule_extern(_ promise: Int32, _ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void +#else +fileprivate func promise_reject_TestModule_extern(_ promise: Int32, _ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_reject_TestModule(_ promise: Int32, _ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void { + return promise_reject_TestModule_extern(promise, valueKind, valuePayload1, valuePayload2) +} + +func _$Promise_reject(_ promise: JSObject, _ value: JSValue) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let (valueKind, valuePayload1, valuePayload2) = value.bridgeJSLowerParameter() + promise_reject_TestModule(promiseValue, valueKind, valuePayload1, valuePayload2) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_18AsyncPayloadResultO(_ promise: JSObject, _ value: AsyncPayloadResult) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_TestModule_18AsyncPayloadResultO") +fileprivate func promise_resolve_TestModule_18AsyncPayloadResultO_extern(_ promise: Int32, _ value: Int32) -> Void +#else +fileprivate func promise_resolve_TestModule_18AsyncPayloadResultO_extern(_ promise: Int32, _ value: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_TestModule_18AsyncPayloadResultO(_ promise: Int32, _ value: Int32) -> Void { + return promise_resolve_TestModule_18AsyncPayloadResultO_extern(promise, value) +} + +func _$Promise_resolve_18AsyncPayloadResultO(_ promise: JSObject, _ value: AsyncPayloadResult) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueCaseId = value.bridgeJSLowerParameter() + promise_resolve_TestModule_18AsyncPayloadResultO(promiseValue, valueCaseId) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_Sq18AsyncPayloadResultO(_ promise: JSObject, _ value: Optional) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_TestModule_Sq18AsyncPayloadResultO") +fileprivate func promise_resolve_TestModule_Sq18AsyncPayloadResultO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueCaseId: Int32) -> Void +#else +fileprivate func promise_resolve_TestModule_Sq18AsyncPayloadResultO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueCaseId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_TestModule_Sq18AsyncPayloadResultO(_ promise: Int32, _ valueIsSome: Int32, _ valueCaseId: Int32) -> Void { + return promise_resolve_TestModule_Sq18AsyncPayloadResultO_extern(promise, valueIsSome, valueCaseId) +} + +func _$Promise_resolve_Sq18AsyncPayloadResultO(_ promise: JSObject, _ value: Optional) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let (valueIsSome, valueCaseId) = value.bridgeJSLowerParameter() + promise_resolve_TestModule_Sq18AsyncPayloadResultO(promiseValue, valueIsSome, valueCaseId) + if let error = _swift_js_take_exception() { throw error } +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValueImport.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValueImport.json new file mode 100644 index 000000000..23cb1b0f0 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValueImport.json @@ -0,0 +1,194 @@ +{ + "exported" : { + "classes" : [ + + ], + "enums" : [ + { + "cases" : [ + { + "associatedValues" : [ + { + "type" : { + "string" : { + + } + } + } + ], + "name" : "start" + }, + { + "associatedValues" : [ + { + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "name" : "stop" + }, + { + "associatedValues" : [ + + ], + "name" : "idle" + } + ], + "emitStyle" : "const", + "name" : "PayloadSignal", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "PayloadSignal", + "tsFullPath" : "PayloadSignal" + } + ], + "exposeToGlobal" : false, + "functions" : [ + + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "imported" : { + "children" : [ + { + "functions" : [ + + ], + "types" : [ + { + "accessLevel" : "internal", + "getters" : [ + + ], + "methods" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "send", + "parameters" : [ + { + "name" : "signal", + "type" : { + "associatedValueEnum" : { + "_0" : "PayloadSignal" + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "current", + "parameters" : [ + + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "PayloadSignal" + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "roundTripOptional", + "parameters" : [ + { + "name" : "signal", + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "PayloadSignal" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "PayloadSignal" + } + }, + "_1" : "null" + } + } + } + ], + "name" : "PayloadSignalControls", + "setters" : [ + + ], + "staticMethods" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "roundTrip", + "parameters" : [ + { + "name" : "signal", + "type" : { + "associatedValueEnum" : { + "_0" : "PayloadSignal" + } + } + } + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "PayloadSignal" + } + } + } + ] + } + ] + } + ] + }, + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValueImport.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValueImport.swift new file mode 100644 index 000000000..5e1db5c72 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValueImport.swift @@ -0,0 +1,112 @@ +extension PayloadSignal: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> PayloadSignal { + switch caseId { + case 0: + return .start(String.bridgeJSStackPop()) + case 1: + return .stop(Int.bridgeJSStackPop()) + case 2: + return .idle + default: + fatalError("Unknown PayloadSignal case ID: \(caseId)") + } + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { + switch self { + case .start(let param0): + param0.bridgeJSStackPush() + return Int32(0) + case .stop(let param0): + param0.bridgeJSStackPush() + return Int32(1) + case .idle: + return Int32(2) + } + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_PayloadSignalControls_roundTrip_static") +fileprivate func bjs_PayloadSignalControls_roundTrip_static_extern(_ signal: Int32) -> Int32 +#else +fileprivate func bjs_PayloadSignalControls_roundTrip_static_extern(_ signal: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_PayloadSignalControls_roundTrip_static(_ signal: Int32) -> Int32 { + return bjs_PayloadSignalControls_roundTrip_static_extern(signal) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_PayloadSignalControls_send") +fileprivate func bjs_PayloadSignalControls_send_extern(_ self: Int32, _ signal: Int32) -> Void +#else +fileprivate func bjs_PayloadSignalControls_send_extern(_ self: Int32, _ signal: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_PayloadSignalControls_send(_ self: Int32, _ signal: Int32) -> Void { + return bjs_PayloadSignalControls_send_extern(self, signal) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_PayloadSignalControls_current") +fileprivate func bjs_PayloadSignalControls_current_extern(_ self: Int32) -> Int32 +#else +fileprivate func bjs_PayloadSignalControls_current_extern(_ self: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_PayloadSignalControls_current(_ self: Int32) -> Int32 { + return bjs_PayloadSignalControls_current_extern(self) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_PayloadSignalControls_roundTripOptional") +fileprivate func bjs_PayloadSignalControls_roundTripOptional_extern(_ self: Int32, _ signalIsSome: Int32, _ signalCaseId: Int32) -> Int32 +#else +fileprivate func bjs_PayloadSignalControls_roundTripOptional_extern(_ self: Int32, _ signalIsSome: Int32, _ signalCaseId: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_PayloadSignalControls_roundTripOptional(_ self: Int32, _ signalIsSome: Int32, _ signalCaseId: Int32) -> Int32 { + return bjs_PayloadSignalControls_roundTripOptional_extern(self, signalIsSome, signalCaseId) +} + +func _$PayloadSignalControls_roundTrip(_ signal: PayloadSignal) throws(JSException) -> PayloadSignal { + let signalCaseId = signal.bridgeJSLowerParameter() + let ret = bjs_PayloadSignalControls_roundTrip_static(signalCaseId) + if let error = _swift_js_take_exception() { + throw error + } + return PayloadSignal.bridgeJSLiftReturn(ret) +} + +func _$PayloadSignalControls_send(_ self: JSObject, _ signal: PayloadSignal) throws(JSException) -> Void { + let selfValue = self.bridgeJSLowerParameter() + let signalCaseId = signal.bridgeJSLowerParameter() + bjs_PayloadSignalControls_send(selfValue, signalCaseId) + if let error = _swift_js_take_exception() { + throw error + } +} + +func _$PayloadSignalControls_current(_ self: JSObject) throws(JSException) -> PayloadSignal { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_PayloadSignalControls_current(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return PayloadSignal.bridgeJSLiftReturn(ret) +} + +func _$PayloadSignalControls_roundTripOptional(_ self: JSObject, _ signal: Optional) throws(JSException) -> Optional { + let selfValue = self.bridgeJSLowerParameter() + let (signalIsSome, signalCaseId) = signal.bridgeJSLowerParameter() + let ret = bjs_PayloadSignalControls_roundTripOptional(selfValue, signalIsSome, signalCaseId) + if let error = _swift_js_take_exception() { + throw error + } + return Optional.bridgeJSLiftReturn(ret) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.d.ts new file mode 100644 index 000000000..d25336ef7 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.d.ts @@ -0,0 +1,33 @@ +// 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`. + +export const AsyncPayloadResultValues: { + readonly Tag: { + readonly Success: 0; + readonly Failure: 1; + readonly Idle: 2; + }; +}; + +export type AsyncPayloadResultTag = + { tag: typeof AsyncPayloadResultValues.Tag.Success; param0: string } | { tag: typeof AsyncPayloadResultValues.Tag.Failure; param0: number } | { tag: typeof AsyncPayloadResultValues.Tag.Idle } + +export type AsyncPayloadResultObject = typeof AsyncPayloadResultValues; + +export type Exports = { + asyncRoundTripAssociatedValueEnum(value: AsyncPayloadResultTag): Promise; + asyncRoundTripOptionalAssociatedValueEnum(value: AsyncPayloadResultTag | null): Promise; + AsyncPayloadResult: AsyncPayloadResultObject +} +export type Imports = { +} +export function createInstantiator(options: { + imports: Imports; +}, swift: any): Promise<{ + addImports: (importObject: WebAssembly.Imports) => void; + setInstance: (instance: WebAssembly.Instance) => void; + createExports: (instance: WebAssembly.Instance) => Exports; +}>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js new file mode 100644 index 000000000..69e4a4928 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js @@ -0,0 +1,414 @@ +// 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`. + +export const AsyncPayloadResultValues = { + Tag: { + Success: 0, + Failure: 1, + Idle: 2, + }, +}; +export async function createInstantiator(options, swift) { + let instance; + let memory; + let setException; + let decodeString; + const textDecoder = new TextDecoder("utf-8"); + const textEncoder = new TextEncoder("utf-8"); + let tmpRetString; + let tmpRetBytes; + let tmpRetException; + let tmpRetOptionalBool; + let tmpRetOptionalInt; + let tmpRetOptionalFloat; + let tmpRetOptionalDouble; + let tmpRetOptionalHeapObject; + let strStack = []; + let i32Stack = []; + let i64Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; + let taStack = []; + const enumHelpers = {}; + const structHelpers = {}; + + let _exports = null; + let bjs = null; + function __bjs_jsValueLower(value) { + let kind; + let payload1; + let payload2; + if (value === null) { + kind = 4; + payload1 = 0; + payload2 = 0; + } else { + switch (typeof value) { + case "boolean": + kind = 0; + payload1 = value ? 1 : 0; + payload2 = 0; + break; + case "number": + kind = 2; + payload1 = 0; + payload2 = value; + break; + case "string": + kind = 1; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "undefined": + kind = 5; + payload1 = 0; + payload2 = 0; + break; + case "object": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "function": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "symbol": + kind = 7; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "bigint": + kind = 8; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + default: + throw new TypeError("Unsupported JSValue type"); + } + } + return [kind, payload1, payload2]; + } + function __bjs_jsValueLift(kind, payload1, payload2) { + let jsValue; + switch (kind) { + case 0: + jsValue = payload1 !== 0; + break; + case 1: + jsValue = swift.memory.getObject(payload1); + break; + case 2: + jsValue = payload2; + break; + case 3: + jsValue = swift.memory.getObject(payload1); + break; + case 4: + jsValue = null; + break; + case 5: + jsValue = undefined; + break; + case 7: + jsValue = swift.memory.getObject(payload1); + break; + case 8: + jsValue = swift.memory.getObject(payload1); + break; + default: + throw new TypeError("Unsupported JSValue kind " + kind); + } + return jsValue; + } + + const __bjs_createAsyncPayloadResultValuesHelpers = () => ({ + lower: (value) => { + const enumTag = value.tag; + switch (enumTag) { + case AsyncPayloadResultValues.Tag.Success: { + const bytes = textEncoder.encode(value.param0); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + return AsyncPayloadResultValues.Tag.Success; + } + case AsyncPayloadResultValues.Tag.Failure: { + i32Stack.push((value.param0 | 0)); + return AsyncPayloadResultValues.Tag.Failure; + } + case AsyncPayloadResultValues.Tag.Idle: { + return AsyncPayloadResultValues.Tag.Idle; + } + default: throw new Error("Unknown AsyncPayloadResultValues tag: " + String(enumTag)); + } + }, + lift: (tag) => { + tag = tag | 0; + switch (tag) { + case AsyncPayloadResultValues.Tag.Success: { + const string = strStack.pop(); + return { tag: AsyncPayloadResultValues.Tag.Success, param0: string }; + } + case AsyncPayloadResultValues.Tag.Failure: { + const int = i32Stack.pop(); + return { tag: AsyncPayloadResultValues.Tag.Failure, param0: int }; + } + case AsyncPayloadResultValues.Tag.Idle: return { tag: AsyncPayloadResultValues.Tag.Idle }; + default: throw new Error("Unknown AsyncPayloadResultValues tag returned from Swift: " + String(tag)); + } + } + }); + + return { + /** + * @param {WebAssembly.Imports} importObject + */ + addImports: (importObject, importsContext) => { + bjs = {}; + importObject["bjs"] = bjs; + bjs["swift_js_return_string"] = function(ptr, len) { + tmpRetString = decodeString(ptr, len); + } + bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { + const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); + const bytes = new Uint8Array(memory.buffer, bytesPtr); + bytes.set(source); + } + bjs["swift_js_make_js_string"] = function(ptr, len) { + return swift.memory.retain(decodeString(ptr, len)); + } + bjs["swift_js_init_memory_with_result"] = function(ptr, len) { + const target = new Uint8Array(memory.buffer, ptr, len); + target.set(tmpRetBytes); + tmpRetBytes = undefined; + } + bjs["swift_js_throw"] = function(id) { + tmpRetException = swift.memory.retainByRef(id); + } + bjs["swift_js_retain"] = function(id) { + return swift.memory.retainByRef(id); + } + bjs["swift_js_release"] = function(id) { + swift.memory.release(id); + } + bjs["swift_js_push_i32"] = function(v) { + i32Stack.push(v | 0); + } + bjs["swift_js_push_f32"] = function(v) { + f32Stack.push(Math.fround(v)); + } + bjs["swift_js_push_f64"] = function(v) { + f64Stack.push(v); + } + bjs["swift_js_push_string"] = function(ptr, len) { + const value = decodeString(ptr, len); + strStack.push(value); + } + bjs["swift_js_pop_i32"] = function() { + return i32Stack.pop(); + } + bjs["swift_js_pop_f32"] = function() { + return f32Stack.pop(); + } + bjs["swift_js_pop_f64"] = function() { + return f64Stack.pop(); + } + bjs["swift_js_push_pointer"] = function(pointer) { + ptrStack.push(pointer); + } + bjs["swift_js_pop_pointer"] = function() { + return ptrStack.pop(); + } + bjs["swift_js_push_i64"] = function(v) { + i64Stack.push(v); + } + bjs["swift_js_pop_i64"] = function() { + return i64Stack.pop(); + } + const taCtors = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array]; + bjs["swift_js_push_typed_array"] = function(kind, ptr, count) { + const Ctor = taCtors[kind]; + const byteLen = count * Ctor.BYTES_PER_ELEMENT; + const copy = memory.buffer.slice(ptr, ptr + byteLen); + taStack.push(Array.from(new Ctor(copy))); + } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } + bjs["promise_resolve_TestModule_18AsyncPayloadResultO"] = function(promise, value) { + try { + const enumValue = enumHelpers.AsyncPayloadResult.lift(value); + swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(enumValue); + } catch (error) { + setException(error); + } + } + bjs["promise_resolve_TestModule_Sq18AsyncPayloadResultO"] = function(promise, valueIsSome, valueCaseId) { + try { + let optResult; + if (valueIsSome) { + const enumValue = enumHelpers.AsyncPayloadResult.lift(valueCaseId); + optResult = enumValue; + } else { + optResult = null; + } + swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(optResult); + } catch (error) { + setException(error); + } + } + bjs["promise_reject_TestModule"] = function(promise, valueKind, valuePayload1, valuePayload2) { + try { + const jsValue = __bjs_jsValueLift(valueKind, valuePayload1, valuePayload2); + swift.memory.getObject(promise)[__bjs_promiseSettlers].reject(jsValue); + } catch (error) { + setException(error); + } + } + bjs["swift_js_return_optional_bool"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalBool = null; + } else { + tmpRetOptionalBool = value !== 0; + } + } + bjs["swift_js_return_optional_int"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalInt = null; + } else { + tmpRetOptionalInt = value | 0; + } + } + bjs["swift_js_return_optional_float"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalFloat = null; + } else { + tmpRetOptionalFloat = Math.fround(value); + } + } + bjs["swift_js_return_optional_double"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalDouble = null; + } else { + tmpRetOptionalDouble = value; + } + } + bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = decodeString(ptr, len); + } + } + bjs["swift_js_return_optional_object"] = function(isSome, objectId) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = swift.memory.getObject(objectId); + } + } + bjs["swift_js_return_optional_heap_object"] = function(isSome, pointer) { + if (isSome === 0) { + tmpRetOptionalHeapObject = null; + } else { + tmpRetOptionalHeapObject = pointer; + } + } + bjs["swift_js_get_optional_int_presence"] = function() { + return tmpRetOptionalInt != null ? 1 : 0; + } + bjs["swift_js_get_optional_int_value"] = function() { + const value = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; + return value; + } + bjs["swift_js_get_optional_string"] = function() { + const str = tmpRetString; + tmpRetString = undefined; + if (str == null) { + return -1; + } else { + const bytes = textEncoder.encode(str); + tmpRetBytes = bytes; + return bytes.length; + } + } + bjs["swift_js_get_optional_float_presence"] = function() { + return tmpRetOptionalFloat != null ? 1 : 0; + } + bjs["swift_js_get_optional_float_value"] = function() { + const value = tmpRetOptionalFloat; + tmpRetOptionalFloat = undefined; + return value; + } + bjs["swift_js_get_optional_double_presence"] = function() { + return tmpRetOptionalDouble != null ? 1 : 0; + } + bjs["swift_js_get_optional_double_value"] = function() { + const value = tmpRetOptionalDouble; + tmpRetOptionalDouble = undefined; + return value; + } + bjs["swift_js_get_optional_heap_object_pointer"] = function() { + const pointer = tmpRetOptionalHeapObject; + tmpRetOptionalHeapObject = undefined; + return pointer || 0; + } + bjs["swift_js_closure_unregister"] = function(funcRef) {} + }, + setInstance: (i) => { + instance = i; + memory = instance.exports.memory; + + decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + + setException = (error) => { + instance.exports._swift_js_exception.value = swift.memory.retain(error) + } + }, + /** @param {WebAssembly.Instance} instance */ + createExports: (instance) => { + const js = swift.memory.heap; + const AsyncPayloadResultHelpers = __bjs_createAsyncPayloadResultValuesHelpers(); + enumHelpers.AsyncPayloadResult = AsyncPayloadResultHelpers; + + const exports = { + asyncRoundTripAssociatedValueEnum: function bjs_asyncRoundTripAssociatedValueEnum(value) { + const valueCaseId = enumHelpers.AsyncPayloadResult.lower(value); + const ret = instance.exports.bjs_asyncRoundTripAssociatedValueEnum(valueCaseId); + const ret1 = swift.memory.getObject(ret); + swift.memory.release(ret); + return ret1; + }, + asyncRoundTripOptionalAssociatedValueEnum: function bjs_asyncRoundTripOptionalAssociatedValueEnum(value) { + const isSome = value != null; + let result; + if (isSome) { + const valueCaseId = enumHelpers.AsyncPayloadResult.lower(value); + result = valueCaseId; + } else { + result = 0; + } + const ret = instance.exports.bjs_asyncRoundTripOptionalAssociatedValueEnum(+isSome, result); + const ret1 = swift.memory.getObject(ret); + swift.memory.release(ret); + return ret1; + }, + AsyncPayloadResult: AsyncPayloadResultValues, + }; + _exports = exports; + return exports; + }, + } +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.d.ts new file mode 100644 index 000000000..d29256af4 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.d.ts @@ -0,0 +1,39 @@ +// 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`. + +export const PayloadSignalValues: { + readonly Tag: { + readonly Start: 0; + readonly Stop: 1; + readonly Idle: 2; + }; +}; + +export type PayloadSignalTag = + { tag: typeof PayloadSignalValues.Tag.Start; param0: string } | { tag: typeof PayloadSignalValues.Tag.Stop; param0: number } | { tag: typeof PayloadSignalValues.Tag.Idle } + +export type PayloadSignalObject = typeof PayloadSignalValues; + +export interface PayloadSignalControls { + send(signal: PayloadSignalTag): void; + current(): PayloadSignalTag; + roundTripOptional(signal: PayloadSignalTag | null): PayloadSignalTag | null; +} +export type Exports = { + PayloadSignal: PayloadSignalObject +} +export type Imports = { + PayloadSignalControls: { + roundTrip(signal: PayloadSignalTag): PayloadSignalTag; + } +} +export function createInstantiator(options: { + imports: Imports; +}, swift: any): Promise<{ + addImports: (importObject: WebAssembly.Imports) => void; + setInstance: (instance: WebAssembly.Instance) => void; + createExports: (instance: WebAssembly.Instance) => Exports; +}>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js new file mode 100644 index 000000000..1688dc94d --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js @@ -0,0 +1,323 @@ +// 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`. + +export const PayloadSignalValues = { + Tag: { + Start: 0, + Stop: 1, + Idle: 2, + }, +}; +export async function createInstantiator(options, swift) { + let instance; + let memory; + let setException; + let decodeString; + const textDecoder = new TextDecoder("utf-8"); + const textEncoder = new TextEncoder("utf-8"); + let tmpRetString; + let tmpRetBytes; + let tmpRetException; + let tmpRetOptionalBool; + let tmpRetOptionalInt; + let tmpRetOptionalFloat; + let tmpRetOptionalDouble; + let tmpRetOptionalHeapObject; + let strStack = []; + let i32Stack = []; + let i64Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; + let taStack = []; + const enumHelpers = {}; + const structHelpers = {}; + + let _exports = null; + let bjs = null; + const __bjs_createPayloadSignalValuesHelpers = () => ({ + lower: (value) => { + const enumTag = value.tag; + switch (enumTag) { + case PayloadSignalValues.Tag.Start: { + const bytes = textEncoder.encode(value.param0); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + return PayloadSignalValues.Tag.Start; + } + case PayloadSignalValues.Tag.Stop: { + i32Stack.push((value.param0 | 0)); + return PayloadSignalValues.Tag.Stop; + } + case PayloadSignalValues.Tag.Idle: { + return PayloadSignalValues.Tag.Idle; + } + default: throw new Error("Unknown PayloadSignalValues tag: " + String(enumTag)); + } + }, + lift: (tag) => { + tag = tag | 0; + switch (tag) { + case PayloadSignalValues.Tag.Start: { + const string = strStack.pop(); + return { tag: PayloadSignalValues.Tag.Start, param0: string }; + } + case PayloadSignalValues.Tag.Stop: { + const int = i32Stack.pop(); + return { tag: PayloadSignalValues.Tag.Stop, param0: int }; + } + case PayloadSignalValues.Tag.Idle: return { tag: PayloadSignalValues.Tag.Idle }; + default: throw new Error("Unknown PayloadSignalValues tag returned from Swift: " + String(tag)); + } + } + }); + + return { + /** + * @param {WebAssembly.Imports} importObject + */ + addImports: (importObject, importsContext) => { + bjs = {}; + importObject["bjs"] = bjs; + bjs["swift_js_return_string"] = function(ptr, len) { + tmpRetString = decodeString(ptr, len); + } + bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { + const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); + const bytes = new Uint8Array(memory.buffer, bytesPtr); + bytes.set(source); + } + bjs["swift_js_make_js_string"] = function(ptr, len) { + return swift.memory.retain(decodeString(ptr, len)); + } + bjs["swift_js_init_memory_with_result"] = function(ptr, len) { + const target = new Uint8Array(memory.buffer, ptr, len); + target.set(tmpRetBytes); + tmpRetBytes = undefined; + } + bjs["swift_js_throw"] = function(id) { + tmpRetException = swift.memory.retainByRef(id); + } + bjs["swift_js_retain"] = function(id) { + return swift.memory.retainByRef(id); + } + bjs["swift_js_release"] = function(id) { + swift.memory.release(id); + } + bjs["swift_js_push_i32"] = function(v) { + i32Stack.push(v | 0); + } + bjs["swift_js_push_f32"] = function(v) { + f32Stack.push(Math.fround(v)); + } + bjs["swift_js_push_f64"] = function(v) { + f64Stack.push(v); + } + bjs["swift_js_push_string"] = function(ptr, len) { + const value = decodeString(ptr, len); + strStack.push(value); + } + bjs["swift_js_pop_i32"] = function() { + return i32Stack.pop(); + } + bjs["swift_js_pop_f32"] = function() { + return f32Stack.pop(); + } + bjs["swift_js_pop_f64"] = function() { + return f64Stack.pop(); + } + bjs["swift_js_push_pointer"] = function(pointer) { + ptrStack.push(pointer); + } + bjs["swift_js_pop_pointer"] = function() { + return ptrStack.pop(); + } + bjs["swift_js_push_i64"] = function(v) { + i64Stack.push(v); + } + bjs["swift_js_pop_i64"] = function() { + return i64Stack.pop(); + } + const taCtors = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array]; + bjs["swift_js_push_typed_array"] = function(kind, ptr, count) { + const Ctor = taCtors[kind]; + const byteLen = count * Ctor.BYTES_PER_ELEMENT; + const copy = memory.buffer.slice(ptr, ptr + byteLen); + taStack.push(Array.from(new Ctor(copy))); + } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } + bjs["swift_js_return_optional_bool"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalBool = null; + } else { + tmpRetOptionalBool = value !== 0; + } + } + bjs["swift_js_return_optional_int"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalInt = null; + } else { + tmpRetOptionalInt = value | 0; + } + } + bjs["swift_js_return_optional_float"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalFloat = null; + } else { + tmpRetOptionalFloat = Math.fround(value); + } + } + bjs["swift_js_return_optional_double"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalDouble = null; + } else { + tmpRetOptionalDouble = value; + } + } + bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = decodeString(ptr, len); + } + } + bjs["swift_js_return_optional_object"] = function(isSome, objectId) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = swift.memory.getObject(objectId); + } + } + bjs["swift_js_return_optional_heap_object"] = function(isSome, pointer) { + if (isSome === 0) { + tmpRetOptionalHeapObject = null; + } else { + tmpRetOptionalHeapObject = pointer; + } + } + bjs["swift_js_get_optional_int_presence"] = function() { + return tmpRetOptionalInt != null ? 1 : 0; + } + bjs["swift_js_get_optional_int_value"] = function() { + const value = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; + return value; + } + bjs["swift_js_get_optional_string"] = function() { + const str = tmpRetString; + tmpRetString = undefined; + if (str == null) { + return -1; + } else { + const bytes = textEncoder.encode(str); + tmpRetBytes = bytes; + return bytes.length; + } + } + bjs["swift_js_get_optional_float_presence"] = function() { + return tmpRetOptionalFloat != null ? 1 : 0; + } + bjs["swift_js_get_optional_float_value"] = function() { + const value = tmpRetOptionalFloat; + tmpRetOptionalFloat = undefined; + return value; + } + bjs["swift_js_get_optional_double_presence"] = function() { + return tmpRetOptionalDouble != null ? 1 : 0; + } + bjs["swift_js_get_optional_double_value"] = function() { + const value = tmpRetOptionalDouble; + tmpRetOptionalDouble = undefined; + return value; + } + bjs["swift_js_get_optional_heap_object_pointer"] = function() { + const pointer = tmpRetOptionalHeapObject; + tmpRetOptionalHeapObject = undefined; + return pointer || 0; + } + bjs["swift_js_closure_unregister"] = function(funcRef) {} + const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; + TestModule["bjs_PayloadSignalControls_roundTrip_static"] = function bjs_PayloadSignalControls_roundTrip_static(signal) { + try { + const enumValue = enumHelpers.PayloadSignal.lift(signal); + let ret = imports.PayloadSignalControls.roundTrip(enumValue); + const caseId = enumHelpers.PayloadSignal.lower(ret); + return caseId; + } catch (error) { + setException(error); + } + } + TestModule["bjs_PayloadSignalControls_send"] = function bjs_PayloadSignalControls_send(self, signal) { + try { + const enumValue = enumHelpers.PayloadSignal.lift(signal); + swift.memory.getObject(self).send(enumValue); + } catch (error) { + setException(error); + } + } + TestModule["bjs_PayloadSignalControls_current"] = function bjs_PayloadSignalControls_current(self) { + try { + let ret = swift.memory.getObject(self).current(); + const caseId = enumHelpers.PayloadSignal.lower(ret); + return caseId; + } catch (error) { + setException(error); + } + } + TestModule["bjs_PayloadSignalControls_roundTripOptional"] = function bjs_PayloadSignalControls_roundTripOptional(self, signalIsSome, signalCaseId) { + try { + let optResult; + if (signalIsSome) { + const enumValue = enumHelpers.PayloadSignal.lift(signalCaseId); + optResult = enumValue; + } else { + optResult = null; + } + let ret = swift.memory.getObject(self).roundTripOptional(optResult); + const isSome = ret != null; + if (isSome) { + const caseId = enumHelpers.PayloadSignal.lower(ret); + return caseId; + } else { + return -1; + } + } catch (error) { + setException(error); + } + } + }, + setInstance: (i) => { + instance = i; + memory = instance.exports.memory; + + decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + + setException = (error) => { + instance.exports._swift_js_exception.value = swift.memory.retain(error) + } + }, + /** @param {WebAssembly.Instance} instance */ + createExports: (instance) => { + const js = swift.memory.heap; + const PayloadSignalHelpers = __bjs_createPayloadSignalValuesHelpers(); + enumHelpers.PayloadSignal = PayloadSignalHelpers; + + const exports = { + PayloadSignal: PayloadSignalValues, + }; + _exports = exports; + return exports; + }, + } +} \ No newline at end of file diff --git a/Tests/BridgeJSRuntimeTests/AsyncImportTests.swift b/Tests/BridgeJSRuntimeTests/AsyncImportTests.swift index 041f251f4..a092d111c 100644 --- a/Tests/BridgeJSRuntimeTests/AsyncImportTests.swift +++ b/Tests/BridgeJSRuntimeTests/AsyncImportTests.swift @@ -1,6 +1,12 @@ import Testing import JavaScriptKit +@JS enum AsyncImportedPayloadResult: Equatable { + case success(String) + case failure(Int) + case idle +} + @JSClass struct AsyncImportImports { @JSFunction static func jsAsyncRoundTripVoid() async throws(JSException) @JSFunction static func jsAsyncRoundTripNumber(_ v: Double) async throws(JSException) -> Double @@ -12,6 +18,12 @@ import JavaScriptKit @JSFunction static func jsAsyncRoundTripIntArray(_ values: [Double]) async throws(JSException) -> [Double] @JSFunction static func jsAsyncRoundTripStringArray(_ values: [String]) async throws(JSException) -> [String] @JSFunction static func jsAsyncRoundTripFeatureFlag(_ v: FeatureFlag) async throws(JSException) -> FeatureFlag + @JSFunction static func jsAsyncRoundTripAssociatedValueEnum( + _ v: AsyncImportedPayloadResult + ) async throws(JSException) -> AsyncImportedPayloadResult + @JSFunction static func jsAsyncRoundTripOptionalAssociatedValueEnum( + _ v: AsyncImportedPayloadResult? + ) async throws(JSException) -> AsyncImportedPayloadResult? } @Suite struct AsyncImportTests { @@ -69,6 +81,29 @@ import JavaScriptKit try #expect(await AsyncImportImports.jsAsyncRoundTripFeatureFlag(v) == v) } + @Test func asyncRoundTripAssociatedValueEnum() async throws { + let values: [AsyncImportedPayloadResult] = [ + .success("ok"), + .failure(7), + .idle, + ] + for value in values { + try #expect(await AsyncImportImports.jsAsyncRoundTripAssociatedValueEnum(value) == value) + } + } + + @Test func asyncRoundTripOptionalAssociatedValueEnum() async throws { + let values: [AsyncImportedPayloadResult?] = [ + .some(.success("ok")), + .some(.failure(7)), + .some(.idle), + nil, + ] + for value in values { + try #expect(await AsyncImportImports.jsAsyncRoundTripOptionalAssociatedValueEnum(value) == value) + } + } + // MARK: - Structured return type @Test func fetchWeatherData() async throws { diff --git a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift index a0453b8f8..282b7cc60 100644 --- a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift @@ -334,6 +334,16 @@ extension StaticCalculator { @JS func asyncRoundTripOptionalFileSize(_ v: FileSize?) async -> FileSize? { v } +@JS enum AsyncPayloadResult: Equatable { + case success(String) + case failure(Int) + case idle +} + +@JS func asyncRoundTripAssociatedValueEnum(_ v: AsyncPayloadResult) async -> AsyncPayloadResult { v } + +@JS func asyncRoundTripOptionalAssociatedValueEnum(_ v: AsyncPayloadResult?) async -> AsyncPayloadResult? { v } + @JS func setHttpStatus(_ status: HttpStatus) -> HttpStatus { return status } diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 78bac8952..c02cb72f7 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -1924,6 +1924,67 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11 #endif } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y_extern(_ callback: Int32, _ param0: Int32) -> Void +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y_extern(_ callback: Int32, _ param0: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y(_ callback: Int32, _ param0: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending AsyncImportedPayloadResult) -> Void { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let param0CaseId = param0.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y(callbackValue, param0CaseId) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (sending AsyncImportedPayloadResult) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending AsyncImportedPayloadResult) -> Void) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending AsyncImportedPayloadResult) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(AsyncImportedPayloadResult.bridgeJSLiftParameter(param0)) + #else + fatalError("Only available on WebAssembly") + #endif +} + #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y") fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y_extern(_ callback: Int32, _ param0Kind: Int32, _ param0Payload1: Int32, _ param0Payload2: Float64) -> Void @@ -2352,6 +2413,67 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd #endif } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0CaseId: Int32) -> Void +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0CaseId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y(_ callback: Int32, _ param0IsSome: Int32, _ param0CaseId: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y_extern(callback, param0IsSome, param0CaseId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending Optional) -> Void { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let (param0IsSome, param0CaseId) = param0.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y(callbackValue, param0IsSome, param0CaseId) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (sending Optional) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Optional) -> Void) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0CaseId: Int32) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending Optional) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(Optional.bridgeJSLiftParameter(param0IsSome, param0CaseId)) + #else + fatalError("Only available on WebAssembly") + #endif +} + #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y") fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void @@ -3816,6 +3938,34 @@ public func _bjs_ArraySupportExports_static_multiOptionalArraySecond() -> Void { #endif } +extension AsyncImportedPayloadResult: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> AsyncImportedPayloadResult { + switch caseId { + case 0: + return .success(String.bridgeJSStackPop()) + case 1: + return .failure(Int.bridgeJSStackPop()) + case 2: + return .idle + default: + fatalError("Unknown AsyncImportedPayloadResult case ID: \(caseId)") + } + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { + switch self { + case .success(let param0): + param0.bridgeJSStackPush() + return Int32(0) + case .failure(let param0): + param0.bridgeJSStackPush() + return Int32(1) + case .idle: + return Int32(2) + } + } +} + @_expose(wasm, "bjs_DefaultArgumentExports_static_testStringDefault") @_cdecl("bjs_DefaultArgumentExports_static_testStringDefault") public func _bjs_DefaultArgumentExports_static_testStringDefault(_ messageBytes: Int32, _ messageLength: Int32) -> Void { @@ -4127,6 +4277,34 @@ extension TSDirection: _BridgedSwiftCaseEnum { extension TSTheme: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } +extension AsyncPayloadResult: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> AsyncPayloadResult { + switch caseId { + case 0: + return .success(String.bridgeJSStackPop()) + case 1: + return .failure(Int.bridgeJSStackPop()) + case 2: + return .idle + default: + fatalError("Unknown AsyncPayloadResult case ID: \(caseId)") + } + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { + switch self { + case .success(let param0): + param0.bridgeJSStackPush() + return Int32(0) + case .failure(let param0): + param0.bridgeJSStackPush() + return Int32(1) + case .idle: + return Int32(2) + } + } +} + @_expose(wasm, "bjs_Utils_StringUtils_static_uppercase") @_cdecl("bjs_Utils_StringUtils_static_uppercase") public func _bjs_Utils_StringUtils_static_uppercase(_ textBytes: Int32, _ textLength: Int32) -> Void { @@ -4870,6 +5048,34 @@ extension LightColor: _BridgedSwiftCaseEnum { } } +extension ImportedPayloadSignal: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> ImportedPayloadSignal { + switch caseId { + case 0: + return .start(String.bridgeJSStackPop()) + case 1: + return .stop(Int.bridgeJSStackPop()) + case 2: + return .idle + default: + fatalError("Unknown ImportedPayloadSignal case ID: \(caseId)") + } + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { + switch self { + case .start(let param0): + param0.bridgeJSStackPush() + return Int32(0) + case .stop(let param0): + param0.bridgeJSStackPush() + return Int32(1) + case .idle: + return Int32(2) + } + } +} + @_expose(wasm, "bjs_IntegerTypesSupportExports_static_roundTripInt") @_cdecl("bjs_IntegerTypesSupportExports_static_roundTripInt") public func _bjs_IntegerTypesSupportExports_static_roundTripInt(_ v: Int32) -> Int32 { @@ -7543,6 +7749,32 @@ public func _bjs_asyncRoundTripOptionalFileSize(_ vIsSome: Int32, _ vValue: Int6 #endif } +@_expose(wasm, "bjs_asyncRoundTripAssociatedValueEnum") +@_cdecl("bjs_asyncRoundTripAssociatedValueEnum") +public func _bjs_asyncRoundTripAssociatedValueEnum(_ v: Int32) -> Int32 { + #if arch(wasm32) + let _tmp_v = AsyncPayloadResult.bridgeJSLiftParameter(v) + return _bjs_makePromise(resolve: Promise_resolve_18AsyncPayloadResultO, reject: Promise_reject) { + return await asyncRoundTripAssociatedValueEnum(_: _tmp_v) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_asyncRoundTripOptionalAssociatedValueEnum") +@_cdecl("bjs_asyncRoundTripOptionalAssociatedValueEnum") +public func _bjs_asyncRoundTripOptionalAssociatedValueEnum(_ vIsSome: Int32, _ vCaseId: Int32) -> Int32 { + #if arch(wasm32) + let _tmp_v = Optional.bridgeJSLiftParameter(vIsSome, vCaseId) + return _bjs_makePromise(resolve: Promise_resolve_Sq18AsyncPayloadResultO, reject: Promise_reject) { + return await asyncRoundTripOptionalAssociatedValueEnum(_: _tmp_v) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_setHttpStatus") @_cdecl("bjs_setHttpStatus") public func _bjs_setHttpStatus(_ status: Int32) -> Int32 { @@ -11797,6 +12029,48 @@ func _$Promise_resolve_Sq8FileSizeO(_ promise: JSObject, _ value: Optional Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_18AsyncPayloadResultO_extern(_ promise: Int32, _ value: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_18AsyncPayloadResultO(_ promise: Int32, _ value: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_18AsyncPayloadResultO_extern(promise, value) +} + +func _$Promise_resolve_18AsyncPayloadResultO(_ promise: JSObject, _ value: AsyncPayloadResult) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueCaseId = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_18AsyncPayloadResultO(promiseValue, valueCaseId) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_Sq18AsyncPayloadResultO(_ promise: JSObject, _ value: Optional) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sq18AsyncPayloadResultO") +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq18AsyncPayloadResultO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueCaseId: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq18AsyncPayloadResultO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueCaseId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq18AsyncPayloadResultO(_ promise: Int32, _ valueIsSome: Int32, _ valueCaseId: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_Sq18AsyncPayloadResultO_extern(promise, valueIsSome, valueCaseId) +} + +func _$Promise_resolve_Sq18AsyncPayloadResultO(_ promise: JSObject, _ value: Optional) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let (valueIsSome, valueCaseId) = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_Sq18AsyncPayloadResultO(promiseValue, valueIsSome, valueCaseId) + if let error = _swift_js_take_exception() { throw error } +} + @JSFunction func Promise_resolve_11PublicPointV(_ promise: JSObject, _ value: PublicPoint) throws(JSException) #if arch(wasm32) @@ -12421,6 +12695,30 @@ fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripFeatureFlag_static_exter return bjs_AsyncImportImports_jsAsyncRoundTripFeatureFlag_static_extern(resolveRef, rejectRef, vBytes, vLength) } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_AsyncImportImports_jsAsyncRoundTripAssociatedValueEnum_static") +fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripAssociatedValueEnum_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ v: Int32) -> Void +#else +fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripAssociatedValueEnum_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ v: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripAssociatedValueEnum_static(_ resolveRef: Int32, _ rejectRef: Int32, _ v: Int32) -> Void { + return bjs_AsyncImportImports_jsAsyncRoundTripAssociatedValueEnum_static_extern(resolveRef, rejectRef, v) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_AsyncImportImports_jsAsyncRoundTripOptionalAssociatedValueEnum_static") +fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripOptionalAssociatedValueEnum_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ vIsSome: Int32, _ vCaseId: Int32) -> Void +#else +fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripOptionalAssociatedValueEnum_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ vIsSome: Int32, _ vCaseId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripOptionalAssociatedValueEnum_static(_ resolveRef: Int32, _ rejectRef: Int32, _ vIsSome: Int32, _ vCaseId: Int32) -> Void { + return bjs_AsyncImportImports_jsAsyncRoundTripOptionalAssociatedValueEnum_static_extern(resolveRef, rejectRef, vIsSome, vCaseId) +} + func _$AsyncImportImports_jsAsyncRoundTripVoid() async throws(JSException) -> Void { try await _bjs_awaitPromise(makeResolveClosure: { JSTypedClosure<() -> Void>($0) @@ -12542,6 +12840,30 @@ func _$AsyncImportImports_jsAsyncRoundTripFeatureFlag(_ v: FeatureFlag) async th return resolved } +func _$AsyncImportImports_jsAsyncRoundTripAssociatedValueEnum(_ v: AsyncImportedPayloadResult) async throws(JSException) -> AsyncImportedPayloadResult { + let resolved = try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending AsyncImportedPayloadResult) -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + let vCaseId = v.bridgeJSLowerParameter() + bjs_AsyncImportImports_jsAsyncRoundTripAssociatedValueEnum_static(resolveRef, rejectRef, vCaseId) + } + return resolved +} + +func _$AsyncImportImports_jsAsyncRoundTripOptionalAssociatedValueEnum(_ v: Optional) async throws(JSException) -> Optional { + let resolved = try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending Optional) -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + let (vIsSome, vCaseId) = v.bridgeJSLowerParameter() + bjs_AsyncImportImports_jsAsyncRoundTripOptionalAssociatedValueEnum_static(resolveRef, rejectRef, vIsSome, vCaseId) + } + return resolved +} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportImports_jsApplyVoid_static") fileprivate func bjs_ClosureSupportImports_jsApplyVoid_static_extern(_ callback: Int32) -> Void @@ -14079,6 +14401,48 @@ func _$jsRoundTripLightColor(_ value: LightColor) throws(JSException) -> LightCo return LightColor.bridgeJSLiftReturn(ret) } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripImportedPayloadSignal") +fileprivate func bjs_jsRoundTripImportedPayloadSignal_extern(_ value: Int32) -> Int32 +#else +fileprivate func bjs_jsRoundTripImportedPayloadSignal_extern(_ value: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsRoundTripImportedPayloadSignal(_ value: Int32) -> Int32 { + return bjs_jsRoundTripImportedPayloadSignal_extern(value) +} + +func _$jsRoundTripImportedPayloadSignal(_ value: ImportedPayloadSignal) throws(JSException) -> ImportedPayloadSignal { + let valueCaseId = value.bridgeJSLowerParameter() + let ret = bjs_jsRoundTripImportedPayloadSignal(valueCaseId) + if let error = _swift_js_take_exception() { + throw error + } + return ImportedPayloadSignal.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripOptionalImportedPayloadSignal") +fileprivate func bjs_jsRoundTripOptionalImportedPayloadSignal_extern(_ valueIsSome: Int32, _ valueCaseId: Int32) -> Int32 +#else +fileprivate func bjs_jsRoundTripOptionalImportedPayloadSignal_extern(_ valueIsSome: Int32, _ valueCaseId: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsRoundTripOptionalImportedPayloadSignal(_ valueIsSome: Int32, _ valueCaseId: Int32) -> Int32 { + return bjs_jsRoundTripOptionalImportedPayloadSignal_extern(valueIsSome, valueCaseId) +} + +func _$jsRoundTripOptionalImportedPayloadSignal(_ value: Optional) throws(JSException) -> Optional { + let (valueIsSome, valueCaseId) = value.bridgeJSLowerParameter() + let ret = bjs_jsRoundTripOptionalImportedPayloadSignal(valueIsSome, valueCaseId) + if let error = _swift_js_take_exception() { + throw error + } + return Optional.bridgeJSLiftReturn(ret) +} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsTranslatePoint") fileprivate func bjs_jsTranslatePoint_extern(_ point: Int32, _ dx: Int32, _ dy: Int32) -> Int32 diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index 6535e9fc1..a51e6bafd 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -6550,6 +6550,53 @@ "swiftCallName" : "ArraySupportExports", "tsFullPath" : "ArraySupportExports" }, + { + "cases" : [ + { + "associatedValues" : [ + { + "type" : { + "string" : { + + } + } + } + ], + "name" : "success" + }, + { + "associatedValues" : [ + { + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "name" : "failure" + }, + { + "associatedValues" : [ + + ], + "name" : "idle" + } + ], + "emitStyle" : "const", + "name" : "AsyncImportedPayloadResult", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "AsyncImportedPayloadResult", + "tsFullPath" : "AsyncImportedPayloadResult" + }, { "cases" : [ @@ -7715,6 +7762,53 @@ "swiftCallName" : "TSTheme", "tsFullPath" : "TSTheme" }, + { + "cases" : [ + { + "associatedValues" : [ + { + "type" : { + "string" : { + + } + } + } + ], + "name" : "success" + }, + { + "associatedValues" : [ + { + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "name" : "failure" + }, + { + "associatedValues" : [ + + ], + "name" : "idle" + } + ], + "emitStyle" : "const", + "name" : "AsyncPayloadResult", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "AsyncPayloadResult", + "tsFullPath" : "AsyncPayloadResult" + }, { "cases" : [ @@ -9326,6 +9420,53 @@ "swiftCallName" : "LightColor", "tsFullPath" : "LightColor" }, + { + "cases" : [ + { + "associatedValues" : [ + { + "type" : { + "string" : { + + } + } + } + ], + "name" : "start" + }, + { + "associatedValues" : [ + { + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "name" : "stop" + }, + { + "associatedValues" : [ + + ], + "name" : "idle" + } + ], + "emitStyle" : "const", + "name" : "ImportedPayloadSignal", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "ImportedPayloadSignal", + "tsFullPath" : "ImportedPayloadSignal" + }, { "cases" : [ @@ -12984,6 +13125,66 @@ } } }, + { + "abiName" : "bjs_asyncRoundTripAssociatedValueEnum", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncRoundTripAssociatedValueEnum", + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "associatedValueEnum" : { + "_0" : "AsyncPayloadResult" + } + } + } + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "AsyncPayloadResult" + } + } + }, + { + "abiName" : "bjs_asyncRoundTripOptionalAssociatedValueEnum", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncRoundTripOptionalAssociatedValueEnum", + "parameters" : [ + { + "label" : "_", + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "AsyncPayloadResult" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "AsyncPayloadResult" + } + }, + "_1" : "null" + } + } + }, { "abiName" : "bjs_setHttpStatus", "effects" : { @@ -18442,6 +18643,64 @@ "_1" : "String" } } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsAsyncRoundTripAssociatedValueEnum", + "parameters" : [ + { + "name" : "v", + "type" : { + "associatedValueEnum" : { + "_0" : "AsyncImportedPayloadResult" + } + } + } + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "AsyncImportedPayloadResult" + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsAsyncRoundTripOptionalAssociatedValueEnum", + "parameters" : [ + { + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "AsyncImportedPayloadResult" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "AsyncImportedPayloadResult" + } + }, + "_1" : "null" + } + } } ] } @@ -20406,6 +20665,64 @@ "_0" : "LightColor" } } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsRoundTripImportedPayloadSignal", + "parameters" : [ + { + "name" : "value", + "type" : { + "associatedValueEnum" : { + "_0" : "ImportedPayloadSignal" + } + } + } + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "ImportedPayloadSignal" + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsRoundTripOptionalImportedPayloadSignal", + "parameters" : [ + { + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "ImportedPayloadSignal" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "ImportedPayloadSignal" + } + }, + "_1" : "null" + } + } } ], "types" : [ diff --git a/Tests/BridgeJSRuntimeTests/ImportAPITests.swift b/Tests/BridgeJSRuntimeTests/ImportAPITests.swift index 2bb9158b9..9cf77ed9d 100644 --- a/Tests/BridgeJSRuntimeTests/ImportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ImportAPITests.swift @@ -7,7 +7,19 @@ import JavaScriptKit case green } +@JS enum ImportedPayloadSignal: Equatable { + case start(String) + case stop(Int) + case idle +} + @JSFunction func jsRoundTripLightColor(_ value: LightColor) throws(JSException) -> LightColor +@JSFunction func jsRoundTripImportedPayloadSignal( + _ value: ImportedPayloadSignal +) throws(JSException) -> ImportedPayloadSignal +@JSFunction func jsRoundTripOptionalImportedPayloadSignal( + _ value: ImportedPayloadSignal? +) throws(JSException) -> ImportedPayloadSignal? class ImportAPITests: XCTestCase { func testRoundTripVoid() throws { @@ -80,6 +92,29 @@ class ImportAPITests: XCTestCase { } } + func testRoundTripAssociatedValueEnum() throws { + let values: [ImportedPayloadSignal] = [ + .start("go"), + .stop(42), + .idle, + ] + for value in values { + try XCTAssertEqual(jsRoundTripImportedPayloadSignal(value), value) + } + } + + func testRoundTripOptionalAssociatedValueEnum() throws { + let values: [ImportedPayloadSignal?] = [ + .some(.start("go")), + .some(.stop(42)), + .some(.idle), + nil, + ] + for value in values { + try XCTAssertEqual(jsRoundTripOptionalImportedPayloadSignal(value), value) + } + } + func ensureThrows(_ f: (Bool) throws(JSException) -> T) throws { do { _ = try f(true) diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/AsyncImportTests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/AsyncImportTests.mjs index 1a767b184..9be7af1be 100644 --- a/Tests/BridgeJSRuntimeTests/JavaScript/AsyncImportTests.mjs +++ b/Tests/BridgeJSRuntimeTests/JavaScript/AsyncImportTests.mjs @@ -1,7 +1,7 @@ // @ts-check import assert from 'node:assert'; -import { ThemeValues, DirectionValues, FileSizeValues } from '../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.js'; +import { ThemeValues, DirectionValues, FileSizeValues, AsyncPayloadResultValues } from '../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.js'; /** * @returns {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Imports["AsyncImportImports"]} @@ -38,6 +38,12 @@ export function getImports(importsContext) { jsAsyncRoundTripFeatureFlag: (v) => { return Promise.resolve(v); }, + jsAsyncRoundTripAssociatedValueEnum: (v) => { + return Promise.resolve(v); + }, + jsAsyncRoundTripOptionalAssociatedValueEnum: (v) => { + return Promise.resolve(v); + }, }; } @@ -124,4 +130,15 @@ export async function runAsyncWorksTests(exports) { assert.equal(await exports.asyncRoundTripFileSize(FileSizeValues.Large), FileSizeValues.Large); assert.equal(await exports.asyncRoundTripOptionalFileSize(FileSizeValues.Tiny), FileSizeValues.Tiny); assert.equal(await exports.asyncRoundTripOptionalFileSize(null), null); + + const asyncPayloadSuccess = { tag: AsyncPayloadResultValues.Tag.Success, param0: "ok" }; + const asyncPayloadFailure = { tag: AsyncPayloadResultValues.Tag.Failure, param0: 7 }; + const asyncPayloadIdle = { tag: AsyncPayloadResultValues.Tag.Idle }; + assert.deepEqual(await exports.asyncRoundTripAssociatedValueEnum(asyncPayloadSuccess), asyncPayloadSuccess); + assert.deepEqual(await exports.asyncRoundTripAssociatedValueEnum(asyncPayloadFailure), asyncPayloadFailure); + assert.deepEqual(await exports.asyncRoundTripAssociatedValueEnum(asyncPayloadIdle), asyncPayloadIdle); + assert.deepEqual(await exports.asyncRoundTripOptionalAssociatedValueEnum(asyncPayloadSuccess), asyncPayloadSuccess); + assert.deepEqual(await exports.asyncRoundTripOptionalAssociatedValueEnum(asyncPayloadFailure), asyncPayloadFailure); + assert.deepEqual(await exports.asyncRoundTripOptionalAssociatedValueEnum(asyncPayloadIdle), asyncPayloadIdle); + assert.equal(await exports.asyncRoundTripOptionalAssociatedValueEnum(null), null); } diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index 0f83da53c..bf3073c62 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -91,6 +91,12 @@ export async function setupOptions(options, context) { "jsRoundTripLightColor": (value) => { return value; }, + "jsRoundTripImportedPayloadSignal": (value) => { + return value; + }, + "jsRoundTripOptionalImportedPayloadSignal": (value) => { + return value; + }, "jsEchoJSValue": (v) => { return v; }, From fa13f45eae06bcabf1c714bdccc0a0462fd047db Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Thu, 11 Jun 2026 11:42:34 +0200 Subject: [PATCH 13/50] BridgeJS: Support throws and async for closures --- .../Sources/BridgeJSCore/ClosureCodegen.swift | 106 +- .../Sources/BridgeJSCore/ImportTS.swift | 9 +- .../BridgeJSCore/SwiftToSkeleton.swift | 51 +- .../Sources/BridgeJSLink/BridgeJSLink.swift | 6 +- .../BridgeJSSkeleton/BridgeJSSkeleton.swift | 80 +- .../ClosureAsyncDiagnosticsTests.swift | 151 +++ .../ClosureManglingTests.swift | 30 + .../ClosureThrowsDiagnosticsTests.swift | 56 ++ .../Inputs/MacroSwift/SwiftClosure.swift | 11 + .../MacroSwift/SwiftClosureImports.swift | 4 + .../BridgeJSCodegenTests/SwiftClosure.json | 227 +++++ .../BridgeJSCodegenTests/SwiftClosure.swift | 844 ++++++++++++++++ .../SwiftClosureImports.json | 105 ++ .../SwiftClosureImports.swift | 340 +++++++ .../BridgeJSLinkTests/SwiftClosure.d.ts | 6 + .../BridgeJSLinkTests/SwiftClosure.js | 368 +++++++ .../SwiftClosureImports.d.ts | 2 + .../BridgeJSLinkTests/SwiftClosureImports.js | 208 ++++ .../Bringing-Swift-Closures-to-JavaScript.md | 42 + .../Exporting-Swift-Closure.md | 143 ++- .../ClosureAsyncAPIs.swift | 89 ++ .../ClosureThrowsAPIs.swift | 31 + .../Generated/BridgeJS.swift | 922 +++++++++++++++++- .../Generated/JavaScript/BridgeJS.json | 446 +++++++++ .../JavaScript/ClosureAsyncTests.mjs | 137 +++ .../JavaScript/ClosureThrowsTests.mjs | 57 ++ Tests/prelude.mjs | 4 + 27 files changed, 4364 insertions(+), 111 deletions(-) create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/ClosureAsyncDiagnosticsTests.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/ClosureManglingTests.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/ClosureThrowsDiagnosticsTests.swift create mode 100644 Tests/BridgeJSRuntimeTests/ClosureAsyncAPIs.swift create mode 100644 Tests/BridgeJSRuntimeTests/ClosureThrowsAPIs.swift create mode 100644 Tests/BridgeJSRuntimeTests/JavaScript/ClosureAsyncTests.mjs create mode 100644 Tests/BridgeJSRuntimeTests/JavaScript/ClosureThrowsTests.mjs diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift index 45cfb73f1..d4e65c631 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift @@ -16,7 +16,7 @@ public struct ClosureCodegen { let closureParams = signature.parameters.map { "\(sendingPrefix)\($0.closureSwiftType)" }.joined( separator: ", " ) - let swiftEffects = (signature.isAsync ? " async" : "") + (signature.isThrows ? " throws" : "") + let swiftEffects = (signature.isAsync ? " async" : "") + (signature.isThrows ? " throws(JSException)" : "") let swiftReturnType = signature.returnType.closureSwiftType return "(\(closureParams))\(swiftEffects) -> \(swiftReturnType)" } @@ -73,7 +73,17 @@ public struct ClosureCodegen { helperEnumDeclPrinter.indent { helperEnumDeclPrinter.write("let callback = JSObject.bridgeJSLiftParameter(callbackId)") let parameters: String - if signature.parameters.isEmpty { + if signature.isThrows || signature.isAsync { + let sendingPrefix = signature.sendingParameters ? "sending " : "" + let typedParams = + signature.parameters.enumerated().map { index, paramType in + "param\(index): \(sendingPrefix)\(paramType.closureSwiftType)" + }.joined(separator: ", ") + let returnType = signature.returnType.closureSwiftType + let effects = + (signature.isAsync ? " async" : "") + (signature.isThrows ? " throws(JSException)" : "") + parameters = " (\(typedParams))\(effects) -> \(returnType)" + } else if signature.parameters.isEmpty { parameters = "" } else if signature.parameters.count == 1 { parameters = " param0" @@ -146,9 +156,17 @@ public struct ClosureCodegen { liftedParams.append("\(paramType.swiftType).bridgeJSLiftParameter(\(argNames.joined(separator: ", ")))") } - let closureCallExpr = ExprSyntax("closure(\(raw: liftedParams.joined(separator: ", ")))") + let tryPrefix = signature.isThrows ? "try " : "" + let closureCallExpr = ExprSyntax("\(raw: tryPrefix)closure(\(raw: liftedParams.joined(separator: ", ")))") + let asyncTryPrefix = (signature.isThrows ? "try " : "") + "await " + let asyncClosureCallExpr = ExprSyntax( + "\(raw: asyncTryPrefix)closure(\(raw: liftedParams.joined(separator: ", ")))" + ) - let abiReturnWasmType = try signature.returnType.loweringReturnInfo().returnType + let abiReturnWasmType = + signature.isAsync + ? try BridgeType.jsObject(nil).loweringReturnInfo().returnType + : try signature.returnType.loweringReturnInfo().returnType // Build signature using SwiftSignatureBuilder let funcSignature = SwiftSignatureBuilder.buildABIFunctionSignature( @@ -156,12 +174,7 @@ public struct ClosureCodegen { 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") + let emitCallAndLower: (CodeFragmentPrinter) -> Void = { printer in if signature.returnType == .void { printer.write(closureCallExpr.description) } else { @@ -189,6 +202,79 @@ public struct ClosureCodegen { } } + let emitAsyncCallAndLower: (CodeFragmentPrinter) -> Void = { printer in + printer.write("let closure = Unmanaged<\(boxType)>.fromOpaque(boxPtr).takeUnretainedValue().closure") + let resolveType = signature.returnType + let resolveName = "Promise_resolve_\(resolveType.mangleTypeName)" + let rejectName = "Promise_reject" + let closureHead: String + if signature.isThrows { + let returnSpelling = resolveType == .void ? "" : " -> \(resolveType.closureSwiftType)" + closureHead = " () async throws(JSException)\(returnSpelling) in" + } else { + closureHead = "" + } + printer.write("return _bjs_makePromise(resolve: \(resolveName), reject: \(rejectName)) {\(closureHead)") + printer.indent { + if resolveType == .void { + printer.write(asyncClosureCallExpr.description) + } else { + printer.write("return \(asyncClosureCallExpr)") + } + } + printer.write("}") + } + + let catchPlaceholderStmt = abiReturnWasmType?.swiftReturnPlaceholderStmt + + // Build function declaration using helper + let funcDecl = SwiftCodePattern.buildExposedFunctionDecl( + abiName: abiName, + signature: funcSignature + ) { printer in + if signature.isAsync { + emitAsyncCallAndLower(printer) + } else if signature.isThrows { + printer.write( + "let closure = Unmanaged<\(boxType)>.fromOpaque(boxPtr).takeUnretainedValue().closure" + ) + printer.write("do {") + printer.indent { + emitCallAndLower(printer) + } + printer.write("} catch let error {") + printer.indent { + printer.write("if let error = error.thrownValue.object {") + printer.indent { + printer.write("withExtendedLifetime(error) {") + printer.indent { + printer.write("_swift_js_throw(Int32(bitPattern: $0.id))") + } + printer.write("}") + } + printer.write("} else {") + printer.indent { + printer.write("let jsError = JSError(message: error.description)") + printer.write("withExtendedLifetime(jsError.jsObject) {") + printer.indent { + printer.write("_swift_js_throw(Int32(bitPattern: $0.id))") + } + printer.write("}") + } + printer.write("}") + if let catchPlaceholderStmt { + printer.write(catchPlaceholderStmt) + } + } + printer.write("}") + } else { + printer.write( + "let closure = Unmanaged<\(boxType)>.fromOpaque(boxPtr).takeUnretainedValue().closure" + ) + emitCallAndLower(printer) + } + } + return DeclSyntax(funcDecl) } diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift index a6a73b8f7..2912ce698 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift @@ -272,9 +272,7 @@ public struct ImportTS { } } - // Add exception check for ImportTS context (skipped for async, where - // errors are funneled through the JS-side reject path) - if !effects.isAsync && context == .importTS { + if !effects.isAsync && (context == .importTS || effects.isThrows) { body.write("if let error = _swift_js_take_exception() { throw error }") } } @@ -323,18 +321,19 @@ public struct ImportTS { let innerBody = body body = CodeFragmentPrinter() + let tryKeyword = effects.isThrows ? "try" : "try!" let rejectFactory = "makeRejectClosure: { JSTypedClosure<(sending JSValue) -> Void>($0) }" if returnType == .void { let resolveFactory = "makeResolveClosure: { JSTypedClosure<() -> Void>($0) }" body.write( - "try await _bjs_awaitPromise(\(resolveFactory), \(rejectFactory)) { resolveRef, rejectRef in" + "\(tryKeyword) await _bjs_awaitPromise(\(resolveFactory), \(rejectFactory)) { resolveRef, rejectRef in" ) } else { let resolveSwiftType = returnType.closureSwiftType let resolveFactory = "makeResolveClosure: { JSTypedClosure<(sending \(resolveSwiftType)) -> Void>($0) }" body.write( - "let resolved = try await _bjs_awaitPromise(\(resolveFactory), \(rejectFactory)) { resolveRef, rejectRef in" + "let resolved = \(tryKeyword) await _bjs_awaitPromise(\(resolveFactory), \(rejectFactory)) { resolveRef, rejectRef in" ) } body.indent { diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index 57b9a57df..18bde3c7f 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -191,7 +191,40 @@ public final class SwiftToSkeleton { } let isAsync = functionType.effectSpecifiers?.asyncSpecifier != nil - let isThrows = functionType.effectSpecifiers?.throwsClause != nil + + if isAsync, !returnType.isAsyncResolvable { + errors.append( + DiagnosticError( + node: functionType, + message: + "Returning '\(returnType.swiftType)' from an async closure is not yet supported", + hint: + "Return a type lowerable through the async resolve ABI " + + "(String/Int/Bool/Double/Float/raw-value or case-only enum/@JS struct/JSObject/Optional/Array/Dictionary), " + + "or make the closure non-async." + ) + ) + return nil + } + + var isThrows = false + if let throwsClause = functionType.effectSpecifiers?.throwsClause { + guard let thrownType = throwsClause.type, + thrownType.trimmedDescription == "JSException" + else { + errors.append( + DiagnosticError( + node: throwsClause, + message: + "Only JSException is supported for thrown type of Swift closures, " + + "got \(throwsClause.type?.trimmedDescription ?? "unspecified")", + hint: "Annotate the closure as `throws(JSException)`" + ) + ) + return nil + } + isThrows = true + } return .closure( ClosureSignature( @@ -1028,22 +1061,6 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { guard let type = resolvedType else { continue // Skip unsupported types } - if case .closure(let signature, _) = type { - if signature.isAsync { - diagnose( - node: param.type, - message: "Async is not supported for Swift closures yet." - ) - continue - } - if signature.isThrows { - diagnose( - node: param.type, - message: "Throws is not supported for Swift closures yet." - ) - continue - } - } if case .nullable(let wrappedType, _) = type, wrappedType.isOptional { diagnoseNestedOptional(node: param.type, type: param.type.trimmedDescription) continue diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index 9a8442435..a9acf048e 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -894,7 +894,7 @@ public struct BridgeJSLink { ) throws -> [String] { let printer = CodeFragmentPrinter() let builder = ExportedThunkBuilder( - effects: Effects(isAsync: false, isThrows: true), + effects: Effects(isAsync: signature.isAsync, isThrows: signature.isAsync ? signature.isThrows : true), hasDirectAccessToSwiftClass: false, intrinsicRegistry: intrinsicRegistry ) @@ -3743,7 +3743,9 @@ extension BridgeType { let paramTypes = signature.parameters.enumerated().map { index, param in "arg\(index): \(param.tsType)" }.joined(separator: ", ") - return "(\(paramTypes)) => \(signature.returnType.tsType)" + let returnTS = + signature.isAsync ? "Promise<\(signature.returnType.tsType)>" : signature.returnType.tsType + return "(\(paramTypes)) => \(returnTS)" case .array(let elementType): let inner = elementType.tsType if inner.contains("|") || inner.contains("=>") { diff --git a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift index 830132481..3e95b46a7 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift @@ -157,7 +157,8 @@ public struct ClosureSignature: Codable, Equatable, Hashable, Sendable { ? "y" : parameters.map { $0.mangleTypeName }.joined() let sendingPart = sendingParameters ? "s" : "" - let signaturePart = "\(sendingPart)\(paramPart)_\(returnType.mangleTypeName)" + let effects = (isAsync ? "Ya" : "") + (isThrows ? "K" : "") + let signaturePart = "\(sendingPart)\(effects)\(paramPart)_\(returnType.mangleTypeName)" self.mangleName = "\(moduleName.count)\(moduleName)\(signaturePart)" } } @@ -1049,8 +1050,31 @@ public struct ExportedSkeleton: Codable { for enumDef in enums { for method in enumDef.staticMethods { consider(method.returnType, method.effects) } } + for returnType in asyncClosureResolveReturnTypes { + consider(returnType, Effects(isAsync: true, isThrows: false)) + } return result } + + private var asyncClosureResolveReturnTypes: [BridgeType] { + var collector = AsyncClosureReturnTypeCollector() + var walker = BridgeSkeletonWalker(visitor: collector) + walker.walk(self) + return walker.visitor.returnTypes + } +} + +private struct AsyncClosureReturnTypeCollector: BridgeSkeletonVisitor { + private(set) var returnTypes: [BridgeType] = [] + + mutating func visitClosure( + _ signature: ClosureSignature, + useJSTypedClosure: Bool, + accessLevel: BridgeJSAccessLevel + ) { + guard signature.isAsync else { return } + returnTypes.append(signature.returnType) + } } // MARK: - Imported Skeleton @@ -1424,11 +1448,18 @@ public struct ClosureSignatureCollectorVisitor: BridgeSkeletonVisitor { accessLevel: BridgeJSAccessLevel ) { recordSignature(signature, accessLevel: accessLevel) + + if signature.isAsync { + recordInjectedSignatures( + forReturnType: signature.returnType, + accessLevel: accessLevel + ) + } } /// Insert `signature` at `accessLevel`, or upgrade the existing level to /// the more permissive of the two. Centralizing the merge here keeps - /// `visitClosure` and `recordInjectedSignature` in lockstep — if the + /// `visitClosure` and `recordInjectedSignatures` in lockstep - if the /// merge policy ever needs to change (e.g. adding a diagnostic for /// conflicting levels), there's only one place to update. private mutating func recordSignature( @@ -1444,56 +1475,48 @@ public struct ClosureSignatureCollectorVisitor: BridgeSkeletonVisitor { public mutating func visitImportedFunction(_ function: ImportedFunctionSkeleton) { guard function.effects.isAsync else { return } - // When async imports exist, inject closure signatures for the typed resolve - // and reject callbacks used by _bjs_awaitPromise. - // - Reject always uses (sending JSValue) -> Void - // - Resolve uses a typed closure matching the return type (or () -> Void for void) - // All async callback closures use `sending` parameters so values can be - // transferred through the checked continuation without Sendable constraints. + recordInjectedSignatures( + forReturnType: function.returnType, + accessLevel: function.accessLevel + ) + } + private mutating func recordInjectedSignatures( + forReturnType returnType: BridgeType, + accessLevel: BridgeJSAccessLevel + ) { // Reject callback - recordInjectedSignature( + recordSignature( ClosureSignature( parameters: [.jsValue], returnType: .void, moduleName: moduleName, sendingParameters: true ), - for: function + accessLevel: accessLevel ) // Resolve callback (typed per return type) - if function.returnType == .void { - recordInjectedSignature( + if returnType == .void { + recordSignature( ClosureSignature( parameters: [], returnType: .void, moduleName: moduleName ), - for: function + accessLevel: accessLevel ) } else { - recordInjectedSignature( + recordSignature( ClosureSignature( - parameters: [function.returnType], + parameters: [returnType], returnType: .void, moduleName: moduleName, sendingParameters: true ), - for: function + accessLevel: accessLevel ) } } - - /// Inject a closure signature derived from an async import (e.g. Promise - /// resolve/reject callbacks). The injected signature inherits the access - /// level of the originating function so its synthesized init matches the - /// visibility of the async API surface. - private mutating func recordInjectedSignature( - _ signature: ClosureSignature, - for function: ImportedFunctionSkeleton - ) { - recordSignature(signature, accessLevel: function.accessLevel) - } } // MARK: - Unified Skeleton @@ -1678,7 +1701,8 @@ extension BridgeType { signature.parameters.isEmpty ? "y" : signature.parameters.map { $0.mangleTypeName }.joined() - return "K\(params)_\(signature.returnType.mangleTypeName)\(useJSTypedClosure ? "J" : "")" + let effects = (signature.isAsync ? "Ya" : "") + (signature.isThrows ? "K" : "") + return "K\(effects)\(params)_\(signature.returnType.mangleTypeName)\(useJSTypedClosure ? "J" : "")" case .array(let elementType): // Array mangling: "Sa" prefix followed by element type return "Sa\(elementType.mangleTypeName)" diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/ClosureAsyncDiagnosticsTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/ClosureAsyncDiagnosticsTests.swift new file mode 100644 index 000000000..55d9e1bd3 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/ClosureAsyncDiagnosticsTests.swift @@ -0,0 +1,151 @@ +import Foundation +import SwiftParser +import SwiftSyntax +import Testing + +@testable import BridgeJSCore +@testable import BridgeJSSkeleton + +@Suite struct ClosureAsyncDiagnosticsTests { + @Test + func parsesAsyncClosureParameter() throws { + let app = try resolveApp( + source: """ + @JS public func process(_ cb: (Int) async -> String) {} + """ + ) + let function = try #require(app.exported?.functions.first(where: { $0.name == "process" })) + let parameter = try #require(function.parameters.first) + guard case .closure(let signature, _) = parameter.type else { + Issue.record("Expected closure parameter type, got \(parameter.type)") + return + } + #expect(signature.isAsync) + } + + @Test + func collectsResolveRejectSignaturesForAsyncClosure() throws { + let app = try resolveApp( + source: """ + @JS public func process(_ cb: (Int) async -> String) {} + """ + ) + let signatures = collectSignatures(from: app) + + let reject = ClosureSignature( + parameters: [.jsValue], + returnType: .void, + moduleName: "App", + sendingParameters: true + ) + let resolve = ClosureSignature( + parameters: [.string], + returnType: .void, + moduleName: "App", + sendingParameters: true + ) + + #expect(signatures.contains(reject)) + #expect(signatures.contains(resolve)) + } + + @Test + func collectsVoidResolveSignatureForVoidReturningAsyncClosure() throws { + let app = try resolveApp( + source: """ + @JS public func process(_ cb: (Int) async -> Void) {} + """ + ) + let signatures = collectSignatures(from: app) + + let reject = ClosureSignature( + parameters: [.jsValue], + returnType: .void, + moduleName: "App", + sendingParameters: true + ) + let voidResolve = ClosureSignature( + parameters: [], + returnType: .void, + moduleName: "App" + ) + + #expect(signatures.contains(reject)) + #expect(signatures.contains(voidResolve)) + } + + @Test + func supportsAsyncClosureReturningJSStruct() throws { + let app = try resolveApp( + source: """ + @JS struct Point { var x: Int } + @JS public func makePoint() -> JSTypedClosure<(Int) async -> Point> { + fatalError() + } + """ + ) + let resolveTypes = try #require(app.exported?.asyncPromiseResolveReturnTypes) + #expect(resolveTypes.contains { $0.mangleTypeName == "5PointV" }) + } + + @Test + func supportsAsyncThrowsClosureReturningJSStruct() throws { + let app = try resolveApp( + source: """ + @JS struct Point { var x: Int } + @JS public func makePoint() -> JSTypedClosure<(Int) async throws(JSException) -> Point> { + fatalError() + } + """ + ) + let resolveTypes = try #require(app.exported?.asyncPromiseResolveReturnTypes) + #expect(resolveTypes.contains { $0.mangleTypeName == "5PointV" }) + } + + @Test + func supportsAsyncClosureReturningAssociatedValueEnum() throws { + let app = try resolveApp( + source: """ + @JS enum Shape { case circle(radius: Double); case square(side: Double) } + @JS public func process(_ cb: (Int) async -> Shape) {} + """ + ) + let resolveTypes = try #require(app.exported?.asyncPromiseResolveReturnTypes) + #expect(resolveTypes.contains { $0.mangleTypeName == "5ShapeO" }) + } + + @Test + func supportsAsyncThrowsClosureReturningAssociatedValueEnum() throws { + let app = try resolveApp( + source: """ + @JS enum Shape { case circle(radius: Double); case square(side: Double) } + @JS public func makeShape() -> JSTypedClosure<(Int) async throws(JSException) -> Shape> { + fatalError() + } + """ + ) + let resolveTypes = try #require(app.exported?.asyncPromiseResolveReturnTypes) + #expect(resolveTypes.contains { $0.mangleTypeName == "5ShapeO" }) + } + + // MARK: - Utilities + + private func collectSignatures(from skeleton: BridgeJSSkeleton) -> Set { + let collector = ClosureSignatureCollectorVisitor(moduleName: skeleton.moduleName) + var walker = BridgeSkeletonWalker(visitor: collector) + walker.walk(skeleton) + return walker.visitor.signatures + } + + private func resolveApp(source appSource: String) throws -> BridgeJSSkeleton { + let swiftAPI = SwiftToSkeleton( + progress: .silent, + moduleName: "App", + exposeToGlobal: false, + externalModuleIndex: ExternalModuleIndex(dependencies: []) + ) + let sourceFile = Parser.parse(source: appSource) + swiftAPI.addSourceFile(sourceFile, inputFilePath: "App.swift") + return try swiftAPI.finalize() + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/ClosureManglingTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/ClosureManglingTests.swift new file mode 100644 index 000000000..3675c805a --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/ClosureManglingTests.swift @@ -0,0 +1,30 @@ +import Testing + +@testable import BridgeJSSkeleton + +@Suite struct ClosureManglingTests { + private func sig(async a: Bool, throws t: Bool) -> ClosureSignature { + ClosureSignature( + parameters: [.integer(.int)], + returnType: .integer(.int), + moduleName: "M", + isAsync: a, + isThrows: t + ) + } + + @Test func effectsDisambiguateMangle() { + let plain = sig(async: false, throws: false).mangleName + let thr = sig(async: false, throws: true).mangleName + let asy = sig(async: true, throws: false).mangleName + let both = sig(async: true, throws: true).mangleName + #expect(Set([plain, thr, asy, both]).count == 4) + #expect(thr.contains("K")) + #expect(asy.contains("Ya")) + if let ya = both.range(of: "Ya"), let k = both.range(of: "K") { + #expect(ya.lowerBound < k.lowerBound) + } else { + Issue.record("expected both Ya and K in async-throws mangle") + } + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/ClosureThrowsDiagnosticsTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/ClosureThrowsDiagnosticsTests.swift new file mode 100644 index 000000000..eb41d0132 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/ClosureThrowsDiagnosticsTests.swift @@ -0,0 +1,56 @@ +import Foundation +import SwiftParser +import SwiftSyntax +import Testing + +@testable import BridgeJSCore +@testable import BridgeJSSkeleton + +@Suite struct ClosureThrowsDiagnosticsTests { + @Test + func parsesThrowsJSExceptionClosureParameter() throws { + let app = try resolveApp( + source: """ + @JS public func process(_ cb: (Int) throws(JSException) -> Int) {} + """ + ) + let function = try #require(app.exported?.functions.first(where: { $0.name == "process" })) + let parameter = try #require(function.parameters.first) + guard case .closure(let signature, _) = parameter.type else { + Issue.record("Expected closure parameter type, got \(parameter.type)") + return + } + #expect(signature.isThrows) + #expect(!signature.isAsync) + } + + @Test + func rejectsPlainThrowsClosureParameter() throws { + do { + _ = try resolveApp( + source: """ + @JS public func process(_ cb: (Int) throws -> Int) {} + """ + ) + Issue.record("Expected a plain-throws closure diagnostic, but resolution succeeded") + } catch let error as BridgeJSCoreDiagnosticError { + let combined = error.diagnostics.map(\.diagnostic.message).joined(separator: "\n") + #expect(combined.contains("JSException")) + #expect(!combined.contains("Throws is not supported for Swift closures yet.")) + } + } + + // MARK: - Utilities + + private func resolveApp(source appSource: String) throws -> BridgeJSSkeleton { + let swiftAPI = SwiftToSkeleton( + progress: .silent, + moduleName: "App", + exposeToGlobal: false, + externalModuleIndex: ExternalModuleIndex(dependencies: []) + ) + let sourceFile = Parser.parse(source: appSource) + swiftAPI.addSourceFile(sourceFile, inputFilePath: "App.swift") + return try swiftAPI.finalize() + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClosure.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClosure.swift index 6872d7989..cdd756d51 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClosure.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClosure.swift @@ -38,6 +38,17 @@ import JavaScriptKit @JS func roundtripPerson(_ personClosure: (Person) -> Person) -> (Person) -> Person @JS func roundtripOptionalPerson(_ personClosure: (Person?) -> Person?) -> (Person?) -> Person? +@JS func makeThrowingParser() -> JSTypedClosure<(String) throws(JSException) -> Int> +@JS func validateWith(_ validate: (String) throws(JSException) -> Bool) + +@JS func makeFetcher() -> JSTypedClosure<(String) async throws(JSException) -> String> + +@JS func makeAsyncEcho() -> JSTypedClosure<(String) async -> String> + +@JS func makeAnimalLoader() -> JSTypedClosure<(String) async -> Animal> + +@JS func makeResultLoader() -> JSTypedClosure<(Bool) async throws(JSException) -> APIResult> + @JS func roundtripDirection(_ callback: (Direction) -> Direction) -> (Direction) -> Direction @JS func roundtripTheme(_ callback: (Theme) -> Theme) -> (Theme) -> Theme @JS func roundtripHttpStatus(_ callback: (HttpStatus) -> HttpStatus) -> (HttpStatus) -> HttpStatus diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClosureImports.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClosureImports.swift index d9f92fffb..88be5420e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClosureImports.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftClosureImports.swift @@ -1,3 +1,7 @@ @JSFunction func applyInt(_ value: Int, _ transform: (Int) -> Int) throws(JSException) -> Int @JSFunction func makeAdder(_ base: Int) throws(JSException) -> (Int) -> Int + +@JS func runValidator(_ cb: (String) throws(JSException) -> Bool) + +@JS func loadEach(_ fetch: (String) async throws(JSException) -> String) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.json index ac18f6dc2..b1e306c07 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.json @@ -1330,6 +1330,233 @@ } } }, + { + "abiName" : "bjs_makeThrowingParser", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "makeThrowingParser", + "parameters" : [ + + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : true, + "mangleName" : "10TestModuleKSS_Si", + "moduleName" : "TestModule", + "parameters" : [ + { + "string" : { + + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : true + } + } + }, + { + "abiName" : "bjs_validateWith", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "validateWith", + "parameters" : [ + { + "label" : "_", + "name" : "validate", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : true, + "mangleName" : "10TestModuleKSS_Sb", + "moduleName" : "TestModule", + "parameters" : [ + { + "string" : { + + } + } + ], + "returnType" : { + "bool" : { + + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_makeFetcher", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "makeFetcher", + "parameters" : [ + + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : true, + "isThrows" : true, + "mangleName" : "10TestModuleYaKSS_SS", + "moduleName" : "TestModule", + "parameters" : [ + { + "string" : { + + } + } + ], + "returnType" : { + "string" : { + + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : true + } + } + }, + { + "abiName" : "bjs_makeAsyncEcho", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "makeAsyncEcho", + "parameters" : [ + + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : true, + "isThrows" : false, + "mangleName" : "10TestModuleYaSS_SS", + "moduleName" : "TestModule", + "parameters" : [ + { + "string" : { + + } + } + ], + "returnType" : { + "string" : { + + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : true + } + } + }, + { + "abiName" : "bjs_makeAnimalLoader", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "makeAnimalLoader", + "parameters" : [ + + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : true, + "isThrows" : false, + "mangleName" : "10TestModuleYaSS_6AnimalV", + "moduleName" : "TestModule", + "parameters" : [ + { + "string" : { + + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "Animal" + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : true + } + } + }, + { + "abiName" : "bjs_makeResultLoader", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "makeResultLoader", + "parameters" : [ + + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : true, + "isThrows" : true, + "mangleName" : "10TestModuleYaKSb_9APIResultO", + "moduleName" : "TestModule", + "parameters" : [ + { + "bool" : { + + } + } + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "APIResult" + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : true + } + } + }, { "abiName" : "bjs_roundtripDirection", "effects" : { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift index 4eb7c8da4..f8f2c76a0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift @@ -379,6 +379,172 @@ public func _invoke_swift_closure_TestModule_10TestModule9DirectionO_9DirectionO #endif } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleKSS_Sb") +fileprivate func invoke_js_callback_TestModule_10TestModuleKSS_Sb_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 +#else +fileprivate func invoke_js_callback_TestModule_10TestModuleKSS_Sb_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleKSS_Sb(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { + return invoke_js_callback_TestModule_10TestModuleKSS_Sb_extern(callback, param0Bytes, param0Length) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModuleKSS_Sb") +fileprivate func make_swift_closure_TestModule_10TestModuleKSS_Sb_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModuleKSS_Sb_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModuleKSS_Sb(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModuleKSS_Sb_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModuleKSS_Sb { + static func bridgeJSLift(_ callbackId: Int32) -> (String) throws(JSException) -> Bool { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] (param0: String) throws(JSException) -> Bool in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let ret = invoke_js_callback_TestModule_10TestModuleKSS_Sb(callbackValue, param0Bytes, param0Length) + return ret + } + let ret = ret0 + if let error = _swift_js_take_exception() { + throw error + } + return Bool.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (String) throws(JSException) -> Bool { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (String) throws(JSException) -> Bool) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModuleKSS_Sb, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuleKSS_Sb") +@_cdecl("invoke_swift_closure_TestModule_10TestModuleKSS_Sb") +public func _invoke_swift_closure_TestModule_10TestModuleKSS_Sb(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(String) throws(JSException) -> Bool>>.fromOpaque(boxPtr).takeUnretainedValue().closure + do { + let result = try closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) + return result.bridgeJSLowerReturn() + } catch let error { + if let error = error.thrownValue.object { + withExtendedLifetime(error) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } else { + let jsError = JSError(message: error.description) + withExtendedLifetime(jsError.jsObject) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } + return 0 + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleKSS_Si") +fileprivate func invoke_js_callback_TestModule_10TestModuleKSS_Si_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 +#else +fileprivate func invoke_js_callback_TestModule_10TestModuleKSS_Si_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleKSS_Si(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { + return invoke_js_callback_TestModule_10TestModuleKSS_Si_extern(callback, param0Bytes, param0Length) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModuleKSS_Si") +fileprivate func make_swift_closure_TestModule_10TestModuleKSS_Si_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModuleKSS_Si_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModuleKSS_Si(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModuleKSS_Si_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModuleKSS_Si { + static func bridgeJSLift(_ callbackId: Int32) -> (String) throws(JSException) -> Int { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] (param0: String) throws(JSException) -> Int in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let ret = invoke_js_callback_TestModule_10TestModuleKSS_Si(callbackValue, param0Bytes, param0Length) + return ret + } + let ret = ret0 + if let error = _swift_js_take_exception() { + throw error + } + return Int.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (String) throws(JSException) -> Int { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (String) throws(JSException) -> Int) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModuleKSS_Si, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuleKSS_Si") +@_cdecl("invoke_swift_closure_TestModule_10TestModuleKSS_Si") +public func _invoke_swift_closure_TestModule_10TestModuleKSS_Si(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(String) throws(JSException) -> Int>>.fromOpaque(boxPtr).takeUnretainedValue().closure + do { + let result = try closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) + return result.bridgeJSLowerReturn() + } catch let error { + if let error = error.thrownValue.object { + withExtendedLifetime(error) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } else { + let jsError = JSError(message: error.description) + withExtendedLifetime(jsError.jsObject) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } + return 0 + } + #else + fatalError("Only available on WebAssembly") + #endif +} + #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleSS_SS") fileprivate func invoke_js_callback_TestModule_10TestModuleSS_SS_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 @@ -1392,6 +1558,534 @@ public func _invoke_swift_closure_TestModule_10TestModuleSqSi_SqSi(_ boxPtr: Uns #endif } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleYaKSS_SS") +fileprivate func invoke_js_callback_TestModule_10TestModuleYaKSS_SS_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModuleYaKSS_SS_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleYaKSS_SS(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModuleYaKSS_SS_extern(resolveRef, rejectRef, callback, param0Bytes, param0Length) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModuleYaKSS_SS") +fileprivate func make_swift_closure_TestModule_10TestModuleYaKSS_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModuleYaKSS_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModuleYaKSS_SS(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModuleYaKSS_SS_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModuleYaKSS_SS { + static func bridgeJSLift(_ callbackId: Int32) -> (String) async throws(JSException) -> String { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] (param0: String) async throws(JSException) -> String in + #if arch(wasm32) + let resolved = try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending String) -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + let callbackValue = callback.bridgeJSLowerParameter() + param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + invoke_js_callback_TestModule_10TestModuleYaKSS_SS(resolveRef, rejectRef, callbackValue, param0Bytes, param0Length) + } + } + return resolved + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (String) async throws(JSException) -> String { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (String) async throws(JSException) -> String) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModuleYaKSS_SS, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuleYaKSS_SS") +@_cdecl("invoke_swift_closure_TestModule_10TestModuleYaKSS_SS") +public func _invoke_swift_closure_TestModule_10TestModuleYaKSS_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(String) async throws(JSException) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure + return _bjs_makePromise(resolve: Promise_resolve_SS, reject: Promise_reject) { () async throws(JSException) -> String in + return try await closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleYaKSb_9APIResultO") +fileprivate func invoke_js_callback_TestModule_10TestModuleYaKSb_9APIResultO_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0: Int32) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModuleYaKSb_9APIResultO_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleYaKSb_9APIResultO(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModuleYaKSb_9APIResultO_extern(resolveRef, rejectRef, callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModuleYaKSb_9APIResultO") +fileprivate func make_swift_closure_TestModule_10TestModuleYaKSb_9APIResultO_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModuleYaKSb_9APIResultO_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModuleYaKSb_9APIResultO(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModuleYaKSb_9APIResultO_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModuleYaKSb_9APIResultO { + static func bridgeJSLift(_ callbackId: Int32) -> (Bool) async throws(JSException) -> APIResult { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] (param0: Bool) async throws(JSException) -> APIResult in + #if arch(wasm32) + let resolved = try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending APIResult) -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + let callbackValue = callback.bridgeJSLowerParameter() + let param0Value = param0.bridgeJSLowerParameter() + invoke_js_callback_TestModule_10TestModuleYaKSb_9APIResultO(resolveRef, rejectRef, callbackValue, param0Value) + } + return resolved + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (Bool) async throws(JSException) -> APIResult { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Bool) async throws(JSException) -> APIResult) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModuleYaKSb_9APIResultO, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuleYaKSb_9APIResultO") +@_cdecl("invoke_swift_closure_TestModule_10TestModuleYaKSb_9APIResultO") +public func _invoke_swift_closure_TestModule_10TestModuleYaKSb_9APIResultO(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Int32 { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Bool) async throws(JSException) -> APIResult>>.fromOpaque(boxPtr).takeUnretainedValue().closure + return _bjs_makePromise(resolve: Promise_resolve_9APIResultO, reject: Promise_reject) { () async throws(JSException) -> APIResult in + return try await closure(Bool.bridgeJSLiftParameter(param0)) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleYaSS_6AnimalV") +fileprivate func invoke_js_callback_TestModule_10TestModuleYaSS_6AnimalV_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModuleYaSS_6AnimalV_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleYaSS_6AnimalV(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModuleYaSS_6AnimalV_extern(resolveRef, rejectRef, callback, param0Bytes, param0Length) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModuleYaSS_6AnimalV") +fileprivate func make_swift_closure_TestModule_10TestModuleYaSS_6AnimalV_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModuleYaSS_6AnimalV_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModuleYaSS_6AnimalV(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModuleYaSS_6AnimalV_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModuleYaSS_6AnimalV { + static func bridgeJSLift(_ callbackId: Int32) -> (String) async -> Animal { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] (param0: String) async -> Animal in + #if arch(wasm32) + let resolved = try! await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending Animal) -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + let callbackValue = callback.bridgeJSLowerParameter() + param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + invoke_js_callback_TestModule_10TestModuleYaSS_6AnimalV(resolveRef, rejectRef, callbackValue, param0Bytes, param0Length) + } + } + return resolved + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (String) async -> Animal { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (String) async -> Animal) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModuleYaSS_6AnimalV, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuleYaSS_6AnimalV") +@_cdecl("invoke_swift_closure_TestModule_10TestModuleYaSS_6AnimalV") +public func _invoke_swift_closure_TestModule_10TestModuleYaSS_6AnimalV(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(String) async -> Animal>>.fromOpaque(boxPtr).takeUnretainedValue().closure + return _bjs_makePromise(resolve: Promise_resolve_6AnimalV, reject: Promise_reject) { + return await closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleYaSS_SS") +fileprivate func invoke_js_callback_TestModule_10TestModuleYaSS_SS_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModuleYaSS_SS_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleYaSS_SS(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModuleYaSS_SS_extern(resolveRef, rejectRef, callback, param0Bytes, param0Length) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModuleYaSS_SS") +fileprivate func make_swift_closure_TestModule_10TestModuleYaSS_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModuleYaSS_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModuleYaSS_SS(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModuleYaSS_SS_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModuleYaSS_SS { + static func bridgeJSLift(_ callbackId: Int32) -> (String) async -> String { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] (param0: String) async -> String in + #if arch(wasm32) + let resolved = try! await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending String) -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + let callbackValue = callback.bridgeJSLowerParameter() + param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + invoke_js_callback_TestModule_10TestModuleYaSS_SS(resolveRef, rejectRef, callbackValue, param0Bytes, param0Length) + } + } + return resolved + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (String) async -> String { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (String) async -> String) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModuleYaSS_SS, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuleYaSS_SS") +@_cdecl("invoke_swift_closure_TestModule_10TestModuleYaSS_SS") +public func _invoke_swift_closure_TestModule_10TestModuleYaSS_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(String) async -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure + return _bjs_makePromise(resolve: Promise_resolve_SS, reject: Promise_reject) { + return await closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModules6AnimalV_y") +fileprivate func invoke_js_callback_TestModule_10TestModules6AnimalV_y_extern(_ callback: Int32) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModules6AnimalV_y_extern(_ callback: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModules6AnimalV_y(_ callback: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModules6AnimalV_y_extern(callback) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModules6AnimalV_y") +fileprivate func make_swift_closure_TestModule_10TestModules6AnimalV_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModules6AnimalV_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModules6AnimalV_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModules6AnimalV_y_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModules6AnimalV_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending Animal) -> Void { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let _ = param0.bridgeJSLowerParameter() + invoke_js_callback_TestModule_10TestModules6AnimalV_y(callbackValue) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (sending Animal) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Animal) -> Void) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModules6AnimalV_y, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModules6AnimalV_y") +@_cdecl("invoke_swift_closure_TestModule_10TestModules6AnimalV_y") +public func _invoke_swift_closure_TestModule_10TestModules6AnimalV_y(_ boxPtr: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending Animal) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(Animal.bridgeJSLiftParameter()) + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModules7JSValueV_y") +fileprivate func invoke_js_callback_TestModule_10TestModules7JSValueV_y_extern(_ callback: Int32, _ param0Kind: Int32, _ param0Payload1: Int32, _ param0Payload2: Float64) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModules7JSValueV_y_extern(_ callback: Int32, _ param0Kind: Int32, _ param0Payload1: Int32, _ param0Payload2: Float64) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModules7JSValueV_y(_ callback: Int32, _ param0Kind: Int32, _ param0Payload1: Int32, _ param0Payload2: Float64) -> Void { + return invoke_js_callback_TestModule_10TestModules7JSValueV_y_extern(callback, param0Kind, param0Payload1, param0Payload2) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModules7JSValueV_y") +fileprivate func make_swift_closure_TestModule_10TestModules7JSValueV_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModules7JSValueV_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModules7JSValueV_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModules7JSValueV_y_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModules7JSValueV_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending JSValue) -> Void { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let (param0Kind, param0Payload1, param0Payload2) = param0.bridgeJSLowerParameter() + invoke_js_callback_TestModule_10TestModules7JSValueV_y(callbackValue, param0Kind, param0Payload1, param0Payload2) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (sending JSValue) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending JSValue) -> Void) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModules7JSValueV_y, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModules7JSValueV_y") +@_cdecl("invoke_swift_closure_TestModule_10TestModules7JSValueV_y") +public func _invoke_swift_closure_TestModule_10TestModules7JSValueV_y(_ boxPtr: UnsafeMutableRawPointer, _ param0Kind: Int32, _ param0Payload1: Int32, _ param0Payload2: Float64) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending JSValue) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(JSValue.bridgeJSLiftParameter(param0Kind, param0Payload1, param0Payload2)) + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModules9APIResultO_y") +fileprivate func invoke_js_callback_TestModule_10TestModules9APIResultO_y_extern(_ callback: Int32, _ param0: Int32) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModules9APIResultO_y_extern(_ callback: Int32, _ param0: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModules9APIResultO_y(_ callback: Int32, _ param0: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModules9APIResultO_y_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModules9APIResultO_y") +fileprivate func make_swift_closure_TestModule_10TestModules9APIResultO_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModules9APIResultO_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModules9APIResultO_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModules9APIResultO_y_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModules9APIResultO_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending APIResult) -> Void { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let param0CaseId = param0.bridgeJSLowerParameter() + invoke_js_callback_TestModule_10TestModules9APIResultO_y(callbackValue, param0CaseId) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (sending APIResult) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending APIResult) -> Void) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModules9APIResultO_y, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModules9APIResultO_y") +@_cdecl("invoke_swift_closure_TestModule_10TestModules9APIResultO_y") +public func _invoke_swift_closure_TestModule_10TestModules9APIResultO_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending APIResult) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(APIResult.bridgeJSLiftParameter(param0)) + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModulesSS_y") +fileprivate func invoke_js_callback_TestModule_10TestModulesSS_y_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModulesSS_y_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModulesSS_y(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModulesSS_y_extern(callback, param0Bytes, param0Length) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModulesSS_y") +fileprivate func make_swift_closure_TestModule_10TestModulesSS_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModulesSS_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModulesSS_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModulesSS_y_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModulesSS_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending String) -> Void { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + invoke_js_callback_TestModule_10TestModulesSS_y(callbackValue, param0Bytes, param0Length) + } + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (sending String) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending String) -> Void) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModulesSS_y, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModulesSS_y") +@_cdecl("invoke_swift_closure_TestModule_10TestModulesSS_y") +public func _invoke_swift_closure_TestModule_10TestModulesSS_y(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending String) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) + #else + fatalError("Only available on WebAssembly") + #endif +} + extension Direction: _BridgedSwiftCaseEnum { @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { return bridgeJSRawValue @@ -1695,6 +2389,71 @@ public func _bjs_roundtripOptionalPerson(_ personClosure: Int32) -> Int32 { #endif } +@_expose(wasm, "bjs_makeThrowingParser") +@_cdecl("bjs_makeThrowingParser") +public func _bjs_makeThrowingParser() -> Int32 { + #if arch(wasm32) + let ret = makeThrowingParser() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_validateWith") +@_cdecl("bjs_validateWith") +public func _bjs_validateWith(_ validate: Int32) -> Void { + #if arch(wasm32) + validateWith(_: _BJS_Closure_10TestModuleKSS_Sb.bridgeJSLift(validate)) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_makeFetcher") +@_cdecl("bjs_makeFetcher") +public func _bjs_makeFetcher() -> Int32 { + #if arch(wasm32) + let ret = makeFetcher() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_makeAsyncEcho") +@_cdecl("bjs_makeAsyncEcho") +public func _bjs_makeAsyncEcho() -> Int32 { + #if arch(wasm32) + let ret = makeAsyncEcho() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_makeAnimalLoader") +@_cdecl("bjs_makeAnimalLoader") +public func _bjs_makeAnimalLoader() -> Int32 { + #if arch(wasm32) + let ret = makeAnimalLoader() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_makeResultLoader") +@_cdecl("bjs_makeResultLoader") +public func _bjs_makeResultLoader() -> Int32 { + #if arch(wasm32) + let ret = makeResultLoader() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_roundtripDirection") @_cdecl("bjs_roundtripDirection") public func _bjs_roundtripDirection(_ callback: Int32) -> Int32 { @@ -1876,4 +2635,89 @@ fileprivate func _bjs_TestProcessor_wrap_extern(_ pointer: UnsafeMutableRawPoint #endif @inline(never) fileprivate func _bjs_TestProcessor_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { return _bjs_TestProcessor_wrap_extern(pointer) +} + +@JSFunction func Promise_reject(_ promise: JSObject, _ value: JSValue) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_reject_TestModule") +fileprivate func promise_reject_TestModule_extern(_ promise: Int32, _ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void +#else +fileprivate func promise_reject_TestModule_extern(_ promise: Int32, _ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_reject_TestModule(_ promise: Int32, _ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void { + return promise_reject_TestModule_extern(promise, valueKind, valuePayload1, valuePayload2) +} + +func _$Promise_reject(_ promise: JSObject, _ value: JSValue) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let (valueKind, valuePayload1, valuePayload2) = value.bridgeJSLowerParameter() + promise_reject_TestModule(promiseValue, valueKind, valuePayload1, valuePayload2) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_SS(_ promise: JSObject, _ value: String) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_TestModule_SS") +fileprivate func promise_resolve_TestModule_SS_extern(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void +#else +fileprivate func promise_resolve_TestModule_SS_extern(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_TestModule_SS(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + return promise_resolve_TestModule_SS_extern(promise, valueBytes, valueLength) +} + +func _$Promise_resolve_SS(_ promise: JSObject, _ value: String) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + value.bridgeJSWithLoweredParameter { (valueBytes, valueLength) in + promise_resolve_TestModule_SS(promiseValue, valueBytes, valueLength) + } + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_6AnimalV(_ promise: JSObject, _ value: Animal) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_TestModule_6AnimalV") +fileprivate func promise_resolve_TestModule_6AnimalV_extern(_ promise: Int32, _ value: Int32) -> Void +#else +fileprivate func promise_resolve_TestModule_6AnimalV_extern(_ promise: Int32, _ value: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_TestModule_6AnimalV(_ promise: Int32, _ value: Int32) -> Void { + return promise_resolve_TestModule_6AnimalV_extern(promise, value) +} + +func _$Promise_resolve_6AnimalV(_ promise: JSObject, _ value: Animal) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueObjectId = value.bridgeJSLowerParameter() + promise_resolve_TestModule_6AnimalV(promiseValue, valueObjectId) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_9APIResultO(_ promise: JSObject, _ value: APIResult) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_TestModule_9APIResultO") +fileprivate func promise_resolve_TestModule_9APIResultO_extern(_ promise: Int32, _ value: Int32) -> Void +#else +fileprivate func promise_resolve_TestModule_9APIResultO_extern(_ promise: Int32, _ value: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_TestModule_9APIResultO(_ promise: Int32, _ value: Int32) -> Void { + return promise_resolve_TestModule_9APIResultO_extern(promise, value) +} + +func _$Promise_resolve_9APIResultO(_ promise: JSObject, _ value: APIResult) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueCaseId = value.bridgeJSLowerParameter() + promise_resolve_TestModule_9APIResultO(promiseValue, valueCaseId) + if let error = _swift_js_take_exception() { throw error } } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.json index a84441bb4..d1cda5c7d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.json @@ -1,4 +1,109 @@ { + "exported" : { + "classes" : [ + + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_runValidator", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "runValidator", + "parameters" : [ + { + "label" : "_", + "name" : "cb", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : true, + "mangleName" : "10TestModuleKSS_Sb", + "moduleName" : "TestModule", + "parameters" : [ + { + "string" : { + + } + } + ], + "returnType" : { + "bool" : { + + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_loadEach", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "loadEach", + "parameters" : [ + { + "label" : "_", + "name" : "fetch", + "type" : { + "closure" : { + "_0" : { + "isAsync" : true, + "isThrows" : true, + "mangleName" : "10TestModuleYaKSS_SS", + "moduleName" : "TestModule", + "parameters" : [ + { + "string" : { + + } + } + ], + "returnType" : { + "string" : { + + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "void" : { + + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, "imported" : { "children" : [ { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.swift index f87c8ecca..93c534c12 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.swift @@ -1,3 +1,86 @@ +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleKSS_Sb") +fileprivate func invoke_js_callback_TestModule_10TestModuleKSS_Sb_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 +#else +fileprivate func invoke_js_callback_TestModule_10TestModuleKSS_Sb_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleKSS_Sb(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { + return invoke_js_callback_TestModule_10TestModuleKSS_Sb_extern(callback, param0Bytes, param0Length) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModuleKSS_Sb") +fileprivate func make_swift_closure_TestModule_10TestModuleKSS_Sb_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModuleKSS_Sb_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModuleKSS_Sb(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModuleKSS_Sb_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModuleKSS_Sb { + static func bridgeJSLift(_ callbackId: Int32) -> (String) throws(JSException) -> Bool { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] (param0: String) throws(JSException) -> Bool in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let ret = invoke_js_callback_TestModule_10TestModuleKSS_Sb(callbackValue, param0Bytes, param0Length) + return ret + } + let ret = ret0 + if let error = _swift_js_take_exception() { + throw error + } + return Bool.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (String) throws(JSException) -> Bool { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (String) throws(JSException) -> Bool) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModuleKSS_Sb, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuleKSS_Sb") +@_cdecl("invoke_swift_closure_TestModule_10TestModuleKSS_Sb") +public func _invoke_swift_closure_TestModule_10TestModuleKSS_Sb(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(String) throws(JSException) -> Bool>>.fromOpaque(boxPtr).takeUnretainedValue().closure + do { + let result = try closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) + return result.bridgeJSLowerReturn() + } catch let error { + if let error = error.thrownValue.object { + withExtendedLifetime(error) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } else { + let jsError = JSError(message: error.description) + withExtendedLifetime(jsError.jsObject) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } + return 0 + } + #else + fatalError("Only available on WebAssembly") + #endif +} + #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleSi_Si") fileprivate func invoke_js_callback_TestModule_10TestModuleSi_Si_extern(_ callback: Int32, _ param0: Int32) -> Int32 @@ -61,6 +144,263 @@ public func _invoke_swift_closure_TestModule_10TestModuleSi_Si(_ boxPtr: UnsafeM #endif } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleYaKSS_SS") +fileprivate func invoke_js_callback_TestModule_10TestModuleYaKSS_SS_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModuleYaKSS_SS_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleYaKSS_SS(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModuleYaKSS_SS_extern(resolveRef, rejectRef, callback, param0Bytes, param0Length) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModuleYaKSS_SS") +fileprivate func make_swift_closure_TestModule_10TestModuleYaKSS_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModuleYaKSS_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModuleYaKSS_SS(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModuleYaKSS_SS_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModuleYaKSS_SS { + static func bridgeJSLift(_ callbackId: Int32) -> (String) async throws(JSException) -> String { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] (param0: String) async throws(JSException) -> String in + #if arch(wasm32) + let resolved = try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending String) -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + let callbackValue = callback.bridgeJSLowerParameter() + param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + invoke_js_callback_TestModule_10TestModuleYaKSS_SS(resolveRef, rejectRef, callbackValue, param0Bytes, param0Length) + } + } + return resolved + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (String) async throws(JSException) -> String { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (String) async throws(JSException) -> String) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModuleYaKSS_SS, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuleYaKSS_SS") +@_cdecl("invoke_swift_closure_TestModule_10TestModuleYaKSS_SS") +public func _invoke_swift_closure_TestModule_10TestModuleYaKSS_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(String) async throws(JSException) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure + return _bjs_makePromise(resolve: Promise_resolve_SS, reject: Promise_reject) { () async throws(JSException) -> String in + return try await closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModules7JSValueV_y") +fileprivate func invoke_js_callback_TestModule_10TestModules7JSValueV_y_extern(_ callback: Int32, _ param0Kind: Int32, _ param0Payload1: Int32, _ param0Payload2: Float64) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModules7JSValueV_y_extern(_ callback: Int32, _ param0Kind: Int32, _ param0Payload1: Int32, _ param0Payload2: Float64) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModules7JSValueV_y(_ callback: Int32, _ param0Kind: Int32, _ param0Payload1: Int32, _ param0Payload2: Float64) -> Void { + return invoke_js_callback_TestModule_10TestModules7JSValueV_y_extern(callback, param0Kind, param0Payload1, param0Payload2) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModules7JSValueV_y") +fileprivate func make_swift_closure_TestModule_10TestModules7JSValueV_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModules7JSValueV_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModules7JSValueV_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModules7JSValueV_y_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModules7JSValueV_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending JSValue) -> Void { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let (param0Kind, param0Payload1, param0Payload2) = param0.bridgeJSLowerParameter() + invoke_js_callback_TestModule_10TestModules7JSValueV_y(callbackValue, param0Kind, param0Payload1, param0Payload2) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (sending JSValue) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending JSValue) -> Void) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModules7JSValueV_y, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModules7JSValueV_y") +@_cdecl("invoke_swift_closure_TestModule_10TestModules7JSValueV_y") +public func _invoke_swift_closure_TestModule_10TestModules7JSValueV_y(_ boxPtr: UnsafeMutableRawPointer, _ param0Kind: Int32, _ param0Payload1: Int32, _ param0Payload2: Float64) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending JSValue) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(JSValue.bridgeJSLiftParameter(param0Kind, param0Payload1, param0Payload2)) + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModulesSS_y") +fileprivate func invoke_js_callback_TestModule_10TestModulesSS_y_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void +#else +fileprivate func invoke_js_callback_TestModule_10TestModulesSS_y_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModulesSS_y(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModulesSS_y_extern(callback, param0Bytes, param0Length) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModulesSS_y") +fileprivate func make_swift_closure_TestModule_10TestModulesSS_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModulesSS_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModulesSS_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModulesSS_y_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModulesSS_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending String) -> Void { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + invoke_js_callback_TestModule_10TestModulesSS_y(callbackValue, param0Bytes, param0Length) + } + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (sending String) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending String) -> Void) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModulesSS_y, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModulesSS_y") +@_cdecl("invoke_swift_closure_TestModule_10TestModulesSS_y") +public func _invoke_swift_closure_TestModule_10TestModulesSS_y(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending String) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_runValidator") +@_cdecl("bjs_runValidator") +public func _bjs_runValidator(_ cb: Int32) -> Void { + #if arch(wasm32) + runValidator(_: _BJS_Closure_10TestModuleKSS_Sb.bridgeJSLift(cb)) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_loadEach") +@_cdecl("bjs_loadEach") +public func _bjs_loadEach(_ fetch: Int32) -> Void { + #if arch(wasm32) + loadEach(_: _BJS_Closure_10TestModuleYaKSS_SS.bridgeJSLift(fetch)) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@JSFunction func Promise_reject(_ promise: JSObject, _ value: JSValue) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_reject_TestModule") +fileprivate func promise_reject_TestModule_extern(_ promise: Int32, _ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void +#else +fileprivate func promise_reject_TestModule_extern(_ promise: Int32, _ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_reject_TestModule(_ promise: Int32, _ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void { + return promise_reject_TestModule_extern(promise, valueKind, valuePayload1, valuePayload2) +} + +func _$Promise_reject(_ promise: JSObject, _ value: JSValue) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let (valueKind, valuePayload1, valuePayload2) = value.bridgeJSLowerParameter() + promise_reject_TestModule(promiseValue, valueKind, valuePayload1, valuePayload2) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_SS(_ promise: JSObject, _ value: String) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_TestModule_SS") +fileprivate func promise_resolve_TestModule_SS_extern(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void +#else +fileprivate func promise_resolve_TestModule_SS_extern(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_TestModule_SS(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + return promise_resolve_TestModule_SS_extern(promise, valueBytes, valueLength) +} + +func _$Promise_resolve_SS(_ promise: JSObject, _ value: String) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + value.bridgeJSWithLoweredParameter { (valueBytes, valueLength) in + promise_resolve_TestModule_SS(promiseValue, valueBytes, valueLength) + } + if let error = _swift_js_take_exception() { throw error } +} + #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_applyInt") fileprivate func bjs_applyInt_extern(_ value: Int32, _ transform: Int32) -> Int32 diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.d.ts index d024be7dd..be62eeedd 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.d.ts @@ -84,6 +84,12 @@ export type Exports = { roundtripOptionalDouble(doubleClosure: (arg0: number | null) => number | null): (arg0: number | null) => number | null; roundtripPerson(personClosure: (arg0: Person) => Person): (arg0: Person) => Person; roundtripOptionalPerson(personClosure: (arg0: Person | null) => Person | null): (arg0: Person | null) => Person | null; + makeThrowingParser(): (arg0: string) => number; + validateWith(validate: (arg0: string) => boolean): void; + makeFetcher(): (arg0: string) => Promise; + makeAsyncEcho(): (arg0: string) => Promise; + makeAnimalLoader(): (arg0: string) => Promise; + makeResultLoader(): (arg0: boolean) => Promise; roundtripDirection(callback: (arg0: DirectionTag) => DirectionTag): (arg0: DirectionTag) => DirectionTag; roundtripTheme(callback: (arg0: ThemeTag) => ThemeTag): (arg0: ThemeTag) => ThemeTag; roundtripHttpStatus(callback: (arg0: HttpStatusTag) => HttpStatusTag): (arg0: HttpStatusTag) => HttpStatusTag; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js index cdd80e90a..4f0770092 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js @@ -61,6 +61,95 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + function __bjs_jsValueLower(value) { + let kind; + let payload1; + let payload2; + if (value === null) { + kind = 4; + payload1 = 0; + payload2 = 0; + } else { + switch (typeof value) { + case "boolean": + kind = 0; + payload1 = value ? 1 : 0; + payload2 = 0; + break; + case "number": + kind = 2; + payload1 = 0; + payload2 = value; + break; + case "string": + kind = 1; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "undefined": + kind = 5; + payload1 = 0; + payload2 = 0; + break; + case "object": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "function": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "symbol": + kind = 7; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "bigint": + kind = 8; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + default: + throw new TypeError("Unsupported JSValue type"); + } + } + return [kind, payload1, payload2]; + } + function __bjs_jsValueLift(kind, payload1, payload2) { + let jsValue; + switch (kind) { + case 0: + jsValue = payload1 !== 0; + break; + case 1: + jsValue = swift.memory.getObject(payload1); + break; + case 2: + jsValue = payload2; + break; + case 3: + jsValue = swift.memory.getObject(payload1); + break; + case 4: + jsValue = null; + break; + case 5: + jsValue = undefined; + break; + case 7: + jsValue = swift.memory.getObject(payload1); + break; + case 8: + jsValue = swift.memory.getObject(payload1); + break; + default: + throw new TypeError("Unsupported JSValue kind " + kind); + } + return jsValue; + } + const swiftClosureRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { if (state.unregistered) { return; } instance?.exports?.bjs_release_swift_closure(state.pointer); @@ -248,6 +337,39 @@ export async function createInstantiator(options, swift) { promise[__bjs_promiseSettlers] = { resolve, reject }; return swift.memory.retain(promise); } + bjs["promise_resolve_TestModule_SS"] = function(promise, valueBytes, valueCount) { + try { + const string = decodeString(valueBytes, valueCount); + swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(string); + } catch (error) { + setException(error); + } + } + bjs["promise_resolve_TestModule_6AnimalV"] = function(promise, value) { + try { + const value1 = swift.memory.getObject(value); + swift.memory.release(value); + swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(value1); + } catch (error) { + setException(error); + } + } + bjs["promise_resolve_TestModule_9APIResultO"] = function(promise, value) { + try { + const enumValue = enumHelpers.APIResult.lift(value); + swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(enumValue); + } catch (error) { + setException(error); + } + } + bjs["promise_reject_TestModule"] = function(promise, valueKind, valuePayload1, valuePayload2) { + try { + const jsValue = __bjs_jsValueLift(valueKind, valuePayload1, valuePayload2); + swift.memory.getObject(promise)[__bjs_promiseSettlers].reject(jsValue); + } catch (error) { + setException(error); + } + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; @@ -490,6 +612,58 @@ export async function createInstantiator(options, swift) { }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModule9DirectionO_9DirectionO); } + bjs["invoke_js_callback_TestModule_10TestModuleKSS_Sb"] = function(callbackId, param0Bytes, param0Count) { + try { + const callback = swift.memory.getObject(callbackId); + const string = decodeString(param0Bytes, param0Count); + let ret = callback(string); + return ret ? 1 : 0; + } catch (error) { + setException(error); + return 0 + } + } + bjs["make_swift_closure_TestModule_10TestModuleKSS_Sb"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModuleKSS_Sb = function(param0) { + const param0Bytes = textEncoder.encode(param0); + const param0Id = swift.memory.retain(param0Bytes); + const ret = instance.exports.invoke_swift_closure_TestModule_10TestModuleKSS_Sb(boxPtr, param0Id, param0Bytes.length); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + return ret !== 0; + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleKSS_Sb); + } + bjs["invoke_js_callback_TestModule_10TestModuleKSS_Si"] = function(callbackId, param0Bytes, param0Count) { + try { + const callback = swift.memory.getObject(callbackId); + const string = decodeString(param0Bytes, param0Count); + let ret = callback(string); + return ret; + } catch (error) { + setException(error); + return 0 + } + } + bjs["make_swift_closure_TestModule_10TestModuleKSS_Si"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModuleKSS_Si = function(param0) { + const param0Bytes = textEncoder.encode(param0); + const param0Id = swift.memory.retain(param0Bytes); + const ret = instance.exports.invoke_swift_closure_TestModule_10TestModuleKSS_Si(boxPtr, param0Id, param0Bytes.length); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + return ret; + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleKSS_Si); + } bjs["invoke_js_callback_TestModule_10TestModuleSS_SS"] = function(callbackId, param0Bytes, param0Count) { try { const callback = swift.memory.getObject(callbackId); @@ -970,6 +1144,176 @@ export async function createInstantiator(options, swift) { }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSqSi_SqSi); } + bjs["invoke_js_callback_TestModule_10TestModuleYaKSS_SS"] = function(resolveRef, rejectRef, callbackId, param0Bytes, param0Count) { + const resolve = swift.memory.getObject(resolveRef); + const reject = swift.memory.getObject(rejectRef); + const callback = swift.memory.getObject(callbackId); + const string = decodeString(param0Bytes, param0Count); + callback(string).then(resolve, reject); + } + bjs["make_swift_closure_TestModule_10TestModuleYaKSS_SS"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModuleYaKSS_SS = function(param0) { + const param0Bytes = textEncoder.encode(param0); + const param0Id = swift.memory.retain(param0Bytes); + const ret = instance.exports.invoke_swift_closure_TestModule_10TestModuleYaKSS_SS(boxPtr, param0Id, param0Bytes.length); + const ret1 = swift.memory.getObject(ret); + swift.memory.release(ret); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + return ret1; + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleYaKSS_SS); + } + bjs["invoke_js_callback_TestModule_10TestModuleYaKSb_9APIResultO"] = function(resolveRef, rejectRef, callbackId, param0) { + const resolve = swift.memory.getObject(resolveRef); + const reject = swift.memory.getObject(rejectRef); + const callback = swift.memory.getObject(callbackId); + callback(param0 !== 0).then(resolve, reject); + } + bjs["make_swift_closure_TestModule_10TestModuleYaKSb_9APIResultO"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModuleYaKSb_9APIResultO = function(param0) { + const ret = instance.exports.invoke_swift_closure_TestModule_10TestModuleYaKSb_9APIResultO(boxPtr, param0); + const ret1 = swift.memory.getObject(ret); + swift.memory.release(ret); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + return ret1; + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleYaKSb_9APIResultO); + } + bjs["invoke_js_callback_TestModule_10TestModuleYaSS_6AnimalV"] = function(resolveRef, rejectRef, callbackId, param0Bytes, param0Count) { + const resolve = swift.memory.getObject(resolveRef); + const reject = swift.memory.getObject(rejectRef); + const callback = swift.memory.getObject(callbackId); + const string = decodeString(param0Bytes, param0Count); + callback(string).then(resolve, reject); + } + bjs["make_swift_closure_TestModule_10TestModuleYaSS_6AnimalV"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModuleYaSS_6AnimalV = function(param0) { + const param0Bytes = textEncoder.encode(param0); + const param0Id = swift.memory.retain(param0Bytes); + const ret = instance.exports.invoke_swift_closure_TestModule_10TestModuleYaSS_6AnimalV(boxPtr, param0Id, param0Bytes.length); + const ret1 = swift.memory.getObject(ret); + swift.memory.release(ret); + return ret1; + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleYaSS_6AnimalV); + } + bjs["invoke_js_callback_TestModule_10TestModuleYaSS_SS"] = function(resolveRef, rejectRef, callbackId, param0Bytes, param0Count) { + const resolve = swift.memory.getObject(resolveRef); + const reject = swift.memory.getObject(rejectRef); + const callback = swift.memory.getObject(callbackId); + const string = decodeString(param0Bytes, param0Count); + callback(string).then(resolve, reject); + } + bjs["make_swift_closure_TestModule_10TestModuleYaSS_SS"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModuleYaSS_SS = function(param0) { + const param0Bytes = textEncoder.encode(param0); + const param0Id = swift.memory.retain(param0Bytes); + const ret = instance.exports.invoke_swift_closure_TestModule_10TestModuleYaSS_SS(boxPtr, param0Id, param0Bytes.length); + const ret1 = swift.memory.getObject(ret); + swift.memory.release(ret); + return ret1; + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleYaSS_SS); + } + bjs["invoke_js_callback_TestModule_10TestModules6AnimalV_y"] = function(callbackId) { + try { + const callback = swift.memory.getObject(callbackId); + const structValue = structHelpers.Animal.lift(); + callback(structValue); + } catch (error) { + setException(error); + } + } + bjs["make_swift_closure_TestModule_10TestModules6AnimalV_y"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModules6AnimalV_y = function(param0) { + structHelpers.Animal.lower(param0); + instance.exports.invoke_swift_closure_TestModule_10TestModules6AnimalV_y(boxPtr); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModules6AnimalV_y); + } + bjs["invoke_js_callback_TestModule_10TestModules7JSValueV_y"] = function(callbackId, param0Kind, param0Payload1, param0Payload2) { + try { + const callback = swift.memory.getObject(callbackId); + const jsValue = __bjs_jsValueLift(param0Kind, param0Payload1, param0Payload2); + callback(jsValue); + } catch (error) { + setException(error); + } + } + bjs["make_swift_closure_TestModule_10TestModules7JSValueV_y"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModules7JSValueV_y = function(param0) { + const [param0Kind, param0Payload1, param0Payload2] = __bjs_jsValueLower(param0); + instance.exports.invoke_swift_closure_TestModule_10TestModules7JSValueV_y(boxPtr, param0Kind, param0Payload1, param0Payload2); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModules7JSValueV_y); + } + bjs["invoke_js_callback_TestModule_10TestModules9APIResultO_y"] = function(callbackId, param0) { + try { + const callback = swift.memory.getObject(callbackId); + const enumValue = enumHelpers.APIResult.lift(param0); + callback(enumValue); + } catch (error) { + setException(error); + } + } + bjs["make_swift_closure_TestModule_10TestModules9APIResultO_y"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModules9APIResultO_y = function(param0) { + const param0CaseId = enumHelpers.APIResult.lower(param0); + instance.exports.invoke_swift_closure_TestModule_10TestModules9APIResultO_y(boxPtr, param0CaseId); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModules9APIResultO_y); + } + bjs["invoke_js_callback_TestModule_10TestModulesSS_y"] = function(callbackId, param0Bytes, param0Count) { + try { + const callback = swift.memory.getObject(callbackId); + const string = decodeString(param0Bytes, param0Count); + callback(string); + } catch (error) { + setException(error); + } + } + bjs["make_swift_closure_TestModule_10TestModulesSS_y"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModulesSS_y = function(param0) { + const param0Bytes = textEncoder.encode(param0); + const param0Id = swift.memory.retain(param0Bytes); + instance.exports.invoke_swift_closure_TestModule_10TestModulesSS_y(boxPtr, param0Id, param0Bytes.length); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModulesSS_y); + } // Wrapper functions for module: TestModule if (!importObject["TestModule"]) { importObject["TestModule"] = {}; @@ -1149,6 +1493,30 @@ export async function createInstantiator(options, swift) { const ret = instance.exports.bjs_roundtripOptionalPerson(callbackId); return swift.memory.getObject(ret); }, + makeThrowingParser: function bjs_makeThrowingParser() { + const ret = instance.exports.bjs_makeThrowingParser(); + return swift.memory.getObject(ret); + }, + validateWith: function bjs_validateWith(validate) { + const callbackId = swift.memory.retain(validate); + instance.exports.bjs_validateWith(callbackId); + }, + makeFetcher: function bjs_makeFetcher() { + const ret = instance.exports.bjs_makeFetcher(); + return swift.memory.getObject(ret); + }, + makeAsyncEcho: function bjs_makeAsyncEcho() { + const ret = instance.exports.bjs_makeAsyncEcho(); + return swift.memory.getObject(ret); + }, + makeAnimalLoader: function bjs_makeAnimalLoader() { + const ret = instance.exports.bjs_makeAnimalLoader(); + return swift.memory.getObject(ret); + }, + makeResultLoader: function bjs_makeResultLoader() { + const ret = instance.exports.bjs_makeResultLoader(); + return swift.memory.getObject(ret); + }, roundtripDirection: function bjs_roundtripDirection(callback) { const callbackId = swift.memory.retain(callback); const ret = instance.exports.bjs_roundtripDirection(callbackId); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.d.ts index ebf493910..b66f960f8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.d.ts @@ -5,6 +5,8 @@ // `swift package bridge-js`. export type Exports = { + runValidator(cb: (arg0: string) => boolean): void; + loadEach(fetch: (arg0: string) => Promise): void; } export type Imports = { applyInt(value: number, transform: (arg0: number) => number): number; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js index 6fd627dcb..0cc8fd287 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js @@ -31,6 +31,95 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + function __bjs_jsValueLower(value) { + let kind; + let payload1; + let payload2; + if (value === null) { + kind = 4; + payload1 = 0; + payload2 = 0; + } else { + switch (typeof value) { + case "boolean": + kind = 0; + payload1 = value ? 1 : 0; + payload2 = 0; + break; + case "number": + kind = 2; + payload1 = 0; + payload2 = value; + break; + case "string": + kind = 1; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "undefined": + kind = 5; + payload1 = 0; + payload2 = 0; + break; + case "object": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "function": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "symbol": + kind = 7; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "bigint": + kind = 8; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + default: + throw new TypeError("Unsupported JSValue type"); + } + } + return [kind, payload1, payload2]; + } + function __bjs_jsValueLift(kind, payload1, payload2) { + let jsValue; + switch (kind) { + case 0: + jsValue = payload1 !== 0; + break; + case 1: + jsValue = swift.memory.getObject(payload1); + break; + case 2: + jsValue = payload2; + break; + case 3: + jsValue = swift.memory.getObject(payload1); + break; + case 4: + jsValue = null; + break; + case 5: + jsValue = undefined; + break; + case 7: + jsValue = swift.memory.getObject(payload1); + break; + case 8: + jsValue = swift.memory.getObject(payload1); + break; + default: + throw new TypeError("Unsupported JSValue kind " + kind); + } + return jsValue; + } + const swiftClosureRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { if (state.unregistered) { return; } instance?.exports?.bjs_release_swift_closure(state.pointer); @@ -139,6 +228,22 @@ export async function createInstantiator(options, swift) { promise[__bjs_promiseSettlers] = { resolve, reject }; return swift.memory.retain(promise); } + bjs["promise_resolve_TestModule_SS"] = function(promise, valueBytes, valueCount) { + try { + const string = decodeString(valueBytes, valueCount); + swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(string); + } catch (error) { + setException(error); + } + } + bjs["promise_reject_TestModule"] = function(promise, valueKind, valuePayload1, valuePayload2) { + try { + const jsValue = __bjs_jsValueLift(valueKind, valuePayload1, valuePayload2); + swift.memory.getObject(promise)[__bjs_promiseSettlers].reject(jsValue); + } catch (error) { + setException(error); + } + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; @@ -233,6 +338,32 @@ export async function createInstantiator(options, swift) { const func = swift.memory.getObject(funcRef); func.__unregister(); } + bjs["invoke_js_callback_TestModule_10TestModuleKSS_Sb"] = function(callbackId, param0Bytes, param0Count) { + try { + const callback = swift.memory.getObject(callbackId); + const string = decodeString(param0Bytes, param0Count); + let ret = callback(string); + return ret ? 1 : 0; + } catch (error) { + setException(error); + return 0 + } + } + bjs["make_swift_closure_TestModule_10TestModuleKSS_Sb"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModuleKSS_Sb = function(param0) { + const param0Bytes = textEncoder.encode(param0); + const param0Id = swift.memory.retain(param0Bytes); + const ret = instance.exports.invoke_swift_closure_TestModule_10TestModuleKSS_Sb(boxPtr, param0Id, param0Bytes.length); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + return ret !== 0; + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleKSS_Sb); + } bjs["invoke_js_callback_TestModule_10TestModuleSi_Si"] = function(callbackId, param0) { try { const callback = swift.memory.getObject(callbackId); @@ -256,6 +387,75 @@ export async function createInstantiator(options, swift) { }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSi_Si); } + bjs["invoke_js_callback_TestModule_10TestModuleYaKSS_SS"] = function(resolveRef, rejectRef, callbackId, param0Bytes, param0Count) { + const resolve = swift.memory.getObject(resolveRef); + const reject = swift.memory.getObject(rejectRef); + const callback = swift.memory.getObject(callbackId); + const string = decodeString(param0Bytes, param0Count); + callback(string).then(resolve, reject); + } + bjs["make_swift_closure_TestModule_10TestModuleYaKSS_SS"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModuleYaKSS_SS = function(param0) { + const param0Bytes = textEncoder.encode(param0); + const param0Id = swift.memory.retain(param0Bytes); + const ret = instance.exports.invoke_swift_closure_TestModule_10TestModuleYaKSS_SS(boxPtr, param0Id, param0Bytes.length); + const ret1 = swift.memory.getObject(ret); + swift.memory.release(ret); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + return ret1; + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleYaKSS_SS); + } + bjs["invoke_js_callback_TestModule_10TestModules7JSValueV_y"] = function(callbackId, param0Kind, param0Payload1, param0Payload2) { + try { + const callback = swift.memory.getObject(callbackId); + const jsValue = __bjs_jsValueLift(param0Kind, param0Payload1, param0Payload2); + callback(jsValue); + } catch (error) { + setException(error); + } + } + bjs["make_swift_closure_TestModule_10TestModules7JSValueV_y"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModules7JSValueV_y = function(param0) { + const [param0Kind, param0Payload1, param0Payload2] = __bjs_jsValueLower(param0); + instance.exports.invoke_swift_closure_TestModule_10TestModules7JSValueV_y(boxPtr, param0Kind, param0Payload1, param0Payload2); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModules7JSValueV_y); + } + bjs["invoke_js_callback_TestModule_10TestModulesSS_y"] = function(callbackId, param0Bytes, param0Count) { + try { + const callback = swift.memory.getObject(callbackId); + const string = decodeString(param0Bytes, param0Count); + callback(string); + } catch (error) { + setException(error); + } + } + bjs["make_swift_closure_TestModule_10TestModulesSS_y"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModulesSS_y = function(param0) { + const param0Bytes = textEncoder.encode(param0); + const param0Id = swift.memory.retain(param0Bytes); + instance.exports.invoke_swift_closure_TestModule_10TestModulesSS_y(boxPtr, param0Id, param0Bytes.length); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModulesSS_y); + } const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; TestModule["bjs_applyInt"] = function bjs_applyInt(value, transform) { try { @@ -293,6 +493,14 @@ export async function createInstantiator(options, swift) { createExports: (instance) => { const js = swift.memory.heap; const exports = { + runValidator: function bjs_runValidator(cb) { + const callbackId = swift.memory.retain(cb); + instance.exports.bjs_runValidator(callbackId); + }, + loadEach: function bjs_loadEach(fetch) { + const callbackId = swift.memory.retain(fetch); + instance.exports.bjs_loadEach(callbackId); + }, }; _exports = exports; return exports; diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Bringing-Swift-Closures-to-JavaScript.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Bringing-Swift-Closures-to-JavaScript.md index ce1d9d555..2d0c94152 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Bringing-Swift-Closures-to-JavaScript.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Bringing-Swift-Closures-to-JavaScript.md @@ -38,6 +38,48 @@ let log = JSTypedClosure<(String) -> Void> { print($0) } defer { log.release() } ``` +## Throwing typed closures + +A ``JSTypedClosure`` signature can be `throws(JSException)`. Exceptions propagate across the boundary: a Swift closure that throws surfaces as a thrown JS error (caught with `try/catch` in JavaScript), and a throwing JS callback surfaces back into Swift as a `JSException`. + +```swift +import JavaScriptKit + +let parse = JSTypedClosure<(String) throws(JSException) -> Int> { text in + guard let value = Int(text) else { + throw JSException(JSError(message: "Not a number: \(text)").jsValue) + } + return value +} +defer { parse.release() } +``` + +Only `throws(JSException)` is supported. Plain `throws` is rejected at build time with a diagnostic, consistent with the rest of BridgeJS (see ). + +## Async typed closures + +A ``JSTypedClosure`` signature can be `async`. JavaScript receives a function that returns a `Promise`, so the TypeScript shape is `(args) => Promise`. Supported return types mirror `async` functions: `ConvertibleToJSValue` types, `@JS struct`, raw-value / case-only enums, `Void`, and their `Optional` / `Array` / `Dictionary` compositions. Unsupported async return types (associated-value enums, protocols, namespace enums) are diagnosed at build time. + +```swift +import JavaScriptKit + +let fetchCount = JSTypedClosure<(String) async -> Int> { endpoint in + try? await Task.sleep(nanoseconds: 10_000_000) + return endpoint.count +} +defer { fetchCount.release() } +``` + +```javascript +const count = await fetchCount("/items"); // Promise +``` + +> Important: Async closures require the JavaScript event loop executor, exactly like `async` functions. Call `JavaScriptEventLoop.installGlobalExecutor()` once during startup before invoking them. There is no special handling for closures. + +**Cancellation is a non-goal.** There is no propagation between a Swift `Task` and a JavaScript `Promise` in either direction. + +> Note: The reject path of async throwing typed closures is affected by a Swift compiler bug ([swiftlang/swift#89320](https://github.com/swiftlang/swift/issues/89320)). See for details. + ## Lifetime and release() A ``JSTypedClosure`` keeps the Swift closure alive and exposes a JavaScript function that calls into it. To avoid leaks and use-after-free: diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Closure.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Closure.md index adb9ab33b..4dd08faa8 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Closure.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Closure.md @@ -103,6 +103,144 @@ This differs from structs and arrays, which use copy semantics and transfer data When you **return** a closure to JavaScript, we recommend using ``JSTypedClosure`` and calling `release()` when the closure is no longer needed, instead of returning a plain closure type. See . +## Throwing closures + +Closures can throw JavaScript errors across the boundary using `throws(JSException)`, in both directions. Exceptions propagate just like they do for throwing functions (see ). + +A Swift closure handed to JavaScript that throws surfaces as a thrown JS error, so JavaScript catches it with `try/catch`: + +```swift +import JavaScriptKit + +@JS func makeParser() -> (String) throws(JSException) -> Int { + return { text in + guard let value = Int(text) else { + throw JSException(JSError(message: "Not a number: \(text)").jsValue) + } + return value + } +} +``` + +```javascript +const parse = exports.makeParser(); +try { + console.log(parse("42")); // 42 + parse("oops"); // throws +} catch (e) { + console.error("parse failed:", e); +} +``` + +A throwing JavaScript callback passed into Swift surfaces back into Swift as a `JSException`, which the Swift call site rethrows: + +```swift +import JavaScriptKit + +@JS func runValidator(_ input: String, validate: (String) throws(JSException) -> Bool) throws(JSException) -> Bool { + return try validate(input) +} +``` + +```javascript +exports.runValidator("ok", (value) => { + if (value.length === 0) { + throw new Error("empty input"); + } + return true; +}); +``` + +Notes: +- Only `throws(JSException)` is supported. Plain `throws` is rejected at build time with a diagnostic. +- Thrown values are surfaced to JS as normal JS exceptions, and JS exceptions thrown by callbacks are surfaced into Swift as a `JSException`. + +## Async closures + +Closures can be `async` in both directions, just like `async` functions (see ). An async closure is exposed to JavaScript as a function that returns a `Promise`, so its TypeScript shape is `(args) => Promise`. + +> Important: Async closures require the JavaScript event loop executor to be installed, exactly like `async` functions. Call `JavaScriptEventLoop.installGlobalExecutor()` once during startup before invoking async closures. + +### Direction A - Swift awaits a JavaScript async callback + +A Swift `@JS func` can take a JavaScript async callback typed as `(A) async throws(JSException) -> R`. Swift `await`s the `Promise` the callback returns. Both resolution and rejection work: a rejected `Promise` surfaces into Swift as a `JSException`. + +```swift +import JavaScriptKit + +@JS func loadAll(_ keys: [String], fetch: (String) async throws(JSException) -> String) async throws(JSException) -> [String] { + var results: [String] = [] + for key in keys { + results.append(try await fetch(key)) + } + return results +} +``` + +```javascript +const values = await exports.loadAll(["a", "b"], async (key) => { + const response = await fetch(`/items/${key}`); + if (!response.ok) throw new Error(`failed: ${key}`); // rejects → JSException in Swift + return response.text(); +}); +``` + +### Direction B - a Swift async closure handed to JavaScript + +A Swift async closure returned to JavaScript (as a plain async closure type or a ``JSTypedClosure``) becomes a function JavaScript `await`s. Supported return types mirror async functions: `ConvertibleToJSValue` types, `@JS struct`, raw-value / case-only enums, `Void`, and their `Optional` / `Array` / `Dictionary` compositions. Unsupported async return types (associated-value enums, protocols, namespace enums) are diagnosed at build time. + +```swift +import JavaScriptKit + +@JS struct Point { + let x: Double + let y: Double +} + +// Async closure returning a @JS struct +@JS func makePointLoader() -> JSTypedClosure<(Double, Double) async -> Point> { + let loader = JSTypedClosure<(Double, Double) async -> Point> { x, y in + try? await Task.sleep(nanoseconds: 10_000_000) + return Point(x: x, y: y) + } + return loader +} + +// Async closure returning Void +@JS func makeLogger() -> JSTypedClosure<(String) async -> Void> { + return JSTypedClosure<(String) async -> Void> { message in + try? await Task.sleep(nanoseconds: 10_000_000) + print(message) + } +} +``` + +```javascript +const loadPoint = exports.makePointLoader(); +const point = await loadPoint(1, 2); // Promise +console.log(point.x, point.y); // 1 2 +loadPoint.release(); + +const log = exports.makeLogger(); +await log("hello"); // Promise +log.release(); +``` + +The generated TypeScript declarations: + +```typescript +export type Exports = { + makePointLoader(): (arg0: number, arg1: number) => Promise; + makeLogger(): (arg0: string) => Promise; +} +``` + +Notes: +- The same `JavaScriptEventLoop.installGlobalExecutor()` requirement applies as for async functions; there is no special handling for closures. +- **Cancellation is a non-goal.** There is no propagation between a Swift `Task` and a JavaScript `Promise` in either direction; cancelling one side does not cancel the other. + +> Warning: When an async throwing closure handed to JavaScript throws, the error is currently lost instead of rejecting the `Promise` with it, due to a Swift compiler bug on `wasm32` ([swiftlang/swift#89320](https://github.com/swiftlang/swift/issues/89320), fix in progress in [swiftlang/swift#89715](https://github.com/swiftlang/swift/pull/89715)). Closures that capture state are unaffected, as are throwing JavaScript callbacks passed into Swift. + ## Supported Features | Swift Feature | Status | @@ -112,8 +250,9 @@ When you **return** a closure to JavaScript, we recommend using ``JSTypedClosure | `@escaping` closures | ✅ | | Optional types in closures | ✅ | | Closure-typed `@JS` properties | ❌ | -| Async closures | ❌ | -| Throwing closures | ❌ | +| Async closures `(A) async -> B` | ✅ | +| Async throwing closures `(A) async throws(JSException) -> B` | ✅ (reject path of closures handed to JS pending [swiftlang/swift#89320](https://github.com/swiftlang/swift/issues/89320)) | +| Throwing closures `(A) throws(JSException) -> B` | ✅ | ## See Also diff --git a/Tests/BridgeJSRuntimeTests/ClosureAsyncAPIs.swift b/Tests/BridgeJSRuntimeTests/ClosureAsyncAPIs.swift new file mode 100644 index 000000000..678981ede --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/ClosureAsyncAPIs.swift @@ -0,0 +1,89 @@ +import XCTest +import JavaScriptKit +import JavaScriptEventLoop + +// MARK: - Direction A: Swift awaits a JS async callback + +@JS func awaitAsyncCallback(_ fetch: (String) async throws(JSException) -> String) async throws(JSException) -> String { + let resolved = try await fetch("request") + return "swift-saw:\(resolved)" +} + +// MARK: - Direction B: a Swift async closure handed to JS + +@JS func makeAsyncParser() -> JSTypedClosure<(String) async throws(JSException) -> String> { + return JSTypedClosure { (text: String) async throws(JSException) -> String in + await Task.yield() + guard let value = Int(text) else { + throw JSException(JSError(message: "AsyncParseError: \(text)").jsValue) + } + return "parsed:\(value)" + } +} + +@JS func makeAsyncEcho() -> JSTypedClosure<(String) async -> String> { + return JSTypedClosure { (text: String) async -> String in + await Task.yield() + return "echo:\(text)" + } +} + +@JS func makeAsyncRecorder() -> JSTypedClosure<(String) async throws(JSException) -> Void> { + return JSTypedClosure { (text: String) async throws(JSException) -> Void in + await Task.yield() + if text == "boom" { + throw JSException(JSError(message: "AsyncRecorderError").jsValue) + } + AsyncRecorderState.lastRecorded = text + } +} + +@JS func lastRecordedValue() -> String { + return AsyncRecorderState.lastRecorded +} + +@JS func makeAsyncPayloadLoader() -> JSTypedClosure<(Bool) async throws(JSException) -> AsyncPayloadResult> { + return JSTypedClosure { (succeed: Bool) async throws(JSException) -> AsyncPayloadResult in + await Task.yield() + return succeed ? .success("loaded") : .failure(42) + } +} + +@JS func awaitPayloadCallback( + _ load: (Bool) async throws(JSException) -> AsyncPayloadResult +) async throws(JSException) -> String { + let first = try await load(true) + let second = try await load(false) + return "\(payloadSummary(first))|\(payloadSummary(second))" +} + +private func payloadSummary(_ result: AsyncPayloadResult) -> String { + switch result { + case .success(let value): return "success:\(value)" + case .failure(let code): return "failure:\(code)" + case .idle: return "idle" + } +} + +@JS func makeAsyncPointMaker() -> JSTypedClosure<(Double) async -> DataPoint> { + return JSTypedClosure { (seed: Double) async -> DataPoint in + await Task.yield() + return DataPoint(x: seed, y: seed * 2, label: "async:\(seed)", optCount: nil, optFlag: nil) + } +} + +enum AsyncRecorderState { + nonisolated(unsafe) static var lastRecorded: String = "" +} + +// MARK: - XCTest entry point + +final class ClosureAsyncTests: XCTestCase { + func testRunJsClosureAsyncTests() async throws { + try await ClosureAsyncImports.runJsClosureAsyncTests() + } +} + +@JSClass struct ClosureAsyncImports { + @JSFunction static func runJsClosureAsyncTests() async throws(JSException) +} diff --git a/Tests/BridgeJSRuntimeTests/ClosureThrowsAPIs.swift b/Tests/BridgeJSRuntimeTests/ClosureThrowsAPIs.swift new file mode 100644 index 000000000..472d57ad6 --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/ClosureThrowsAPIs.swift @@ -0,0 +1,31 @@ +import XCTest +import JavaScriptKit + +// MARK: - Direction B: Swift closure (throws) called from JS + +@JS func makeThrowingParser() -> JSTypedClosure<(String) throws(JSException) -> Int> { + return JSTypedClosure { (text: String) throws(JSException) -> Int in + guard let value = Int(text) else { + throw JSException(JSError(message: "ParseError: \(text)").jsValue) + } + return value + } +} + +// MARK: - Direction A: JS callback (throws) called from Swift + +@JS func runValidator(_ validate: (String) throws(JSException) -> Bool) throws(JSException) -> Bool { + return try validate("input") +} + +// MARK: - XCTest entry point + +final class ClosureThrowsTests: XCTestCase { + func testRunJsClosureThrowsTests() throws { + try ClosureThrowsImports.runJsClosureThrowsTests() + } +} + +@JSClass struct ClosureThrowsImports { + @JSFunction static func runJsClosureThrowsTests() throws(JSException) +} diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index c02cb72f7..b2afb6d5b 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -644,6 +644,172 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9Di #endif } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb_extern(callback, param0Bytes, param0Length) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestsKSS_Sb { + static func bridgeJSLift(_ callbackId: Int32) -> (String) throws(JSException) -> Bool { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] (param0: String) throws(JSException) -> Bool in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb(callbackValue, param0Bytes, param0Length) + return ret + } + let ret = ret0 + if let error = _swift_js_take_exception() { + throw error + } + return Bool.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (String) throws(JSException) -> Bool { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (String) throws(JSException) -> Bool) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(String) throws(JSException) -> Bool>>.fromOpaque(boxPtr).takeUnretainedValue().closure + do { + let result = try closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) + return result.bridgeJSLowerReturn() + } catch let error { + if let error = error.thrownValue.object { + withExtendedLifetime(error) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } else { + let jsError = JSError(message: error.description) + withExtendedLifetime(jsError.jsObject) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } + return 0 + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si_extern(callback, param0Bytes, param0Length) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestsKSS_Si { + static func bridgeJSLift(_ callbackId: Int32) -> (String) throws(JSException) -> Int { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] (param0: String) throws(JSException) -> Int in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si(callbackValue, param0Bytes, param0Length) + return ret + } + let ret = ret0 + if let error = _swift_js_take_exception() { + throw error + } + return Int.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (String) throws(JSException) -> Int { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (String) throws(JSException) -> Int) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(String) throws(JSException) -> Int>>.fromOpaque(boxPtr).takeUnretainedValue().closure + do { + let result = try closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) + return result.bridgeJSLowerReturn() + } catch let error { + if let error = error.thrownValue.object { + withExtendedLifetime(error) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } else { + let jsError = JSError(message: error.description) + withExtendedLifetime(jsError.jsObject) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } + return 0 + } + #else + fatalError("Only available on WebAssembly") + #endif +} + #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC") fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> UnsafeMutableRawPointer @@ -1688,26 +1854,370 @@ fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsS @_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS") fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestsSqSS_SS { + static func bridgeJSLift(_ callbackId: Int32) -> (Optional) -> String { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let ret0 = param0.bridgeJSWithLoweredParameter { (param0IsSome, param0Bytes, param0Length) in + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS(callbackValue, param0IsSome, param0Bytes, param0Length) + return ret + } + let ret = ret0 + return String.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (Optional) -> String { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Optional) -> String) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Bytes, param0Length)) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS_extern(callback, param0IsSome, param0Value) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestsSqSi_SS { + static func bridgeJSLift(_ callbackId: Int32) -> (Optional) -> String { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let (param0IsSome, param0Value) = param0.bridgeJSLowerParameter() + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS(callbackValue, param0IsSome, param0Value) + return String.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (Optional) -> String { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Optional) -> String) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Value: Int32) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS_extern(resolveRef, rejectRef, callback, param0Bytes, param0Length) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestsYaKSS_SS { + static func bridgeJSLift(_ callbackId: Int32) -> (String) async throws(JSException) -> String { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] (param0: String) async throws(JSException) -> String in + #if arch(wasm32) + let resolved = try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending String) -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + let callbackValue = callback.bridgeJSLowerParameter() + param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS(resolveRef, rejectRef, callbackValue, param0Bytes, param0Length) + } + } + return resolved + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (String) async throws(JSException) -> String { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (String) async throws(JSException) -> String) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(String) async throws(JSException) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure + return _bjs_makePromise(resolve: Promise_resolve_SS, reject: Promise_reject) { () async throws(JSException) -> String in + return try await closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y_extern(resolveRef, rejectRef, callback, param0Bytes, param0Length) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestsYaKSS_y { + static func bridgeJSLift(_ callbackId: Int32) -> (String) async throws(JSException) -> Void { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] (param0: String) async throws(JSException) -> Void in + #if arch(wasm32) + try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<() -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + let callbackValue = callback.bridgeJSLowerParameter() + param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y(resolveRef, rejectRef, callbackValue, param0Bytes, param0Length) + } + } + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (String) async throws(JSException) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (String) async throws(JSException) -> Void) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(String) async throws(JSException) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + return _bjs_makePromise(resolve: Promise_resolve_y, reject: Promise_reject) { () async throws(JSException) in + try await closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0: Int32) -> Void +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO_extern(resolveRef, rejectRef, callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO { + static func bridgeJSLift(_ callbackId: Int32) -> (Bool) async throws(JSException) -> AsyncPayloadResult { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] (param0: Bool) async throws(JSException) -> AsyncPayloadResult in + #if arch(wasm32) + let resolved = try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending AsyncPayloadResult) -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + let callbackValue = callback.bridgeJSLowerParameter() + let param0Value = param0.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO(resolveRef, rejectRef, callbackValue, param0Value) + } + return resolved + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (Bool) async throws(JSException) -> AsyncPayloadResult { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Bool) async throws(JSException) -> AsyncPayloadResult) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Int32 { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Bool) async throws(JSException) -> AsyncPayloadResult>>.fromOpaque(boxPtr).takeUnretainedValue().closure + return _bjs_makePromise(resolve: Promise_resolve_18AsyncPayloadResultO, reject: Promise_reject) { () async throws(JSException) -> AsyncPayloadResult in + return try await closure(Bool.bridgeJSLiftParameter(param0)) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS_extern(resolveRef, rejectRef, callback, param0Bytes, param0Length) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS_extern(boxPtr, file, line) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestsSqSS_SS { - static func bridgeJSLift(_ callbackId: Int32) -> (Optional) -> String { +private enum _BJS_Closure_20BridgeJSRuntimeTestsYaSS_SS { + static func bridgeJSLift(_ callbackId: Int32) -> (String) async -> String { let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] param0 in + return { [callback] (param0: String) async -> String in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() - let ret0 = param0.bridgeJSWithLoweredParameter { (param0IsSome, param0Bytes, param0Length) in - let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS(callbackValue, param0IsSome, param0Bytes, param0Length) - return ret + let resolved = try! await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending String) -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + let callbackValue = callback.bridgeJSLowerParameter() + param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS(resolveRef, rejectRef, callbackValue, param0Bytes, param0Length) + } } - let ret = ret0 - return String.bridgeJSLiftReturn(ret) + return resolved #else fatalError("Only available on WebAssembly") #endif @@ -1715,10 +2225,10 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSqSS_SS { } } -extension JSTypedClosure where Signature == (Optional) -> String { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Optional) -> String) { +extension JSTypedClosure where Signature == (String) async -> String { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (String) async -> String) { self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS, + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS, body: body, fileID: fileID, line: line @@ -1726,51 +2236,58 @@ extension JSTypedClosure where Signature == (Optional) -> String { } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Bytes, param0Length)) - return result.bridgeJSLowerReturn() + let closure = Unmanaged<_BridgeJSTypedClosureBox<(String) async -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure + return _bjs_makePromise(resolve: Promise_resolve_SS, reject: Promise_reject) { + return await closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) + } #else fatalError("Only available on WebAssembly") #endif } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0: Float64) -> Void #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0: Float64) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Int32) -> Int32 { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS_extern(callback, param0IsSome, param0Value) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0: Float64) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV_extern(resolveRef, rejectRef, callback, param0) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS_extern(boxPtr, file, line) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestsSqSi_SS { - static func bridgeJSLift(_ callbackId: Int32) -> (Optional) -> String { +private enum _BJS_Closure_20BridgeJSRuntimeTestsYaSd_9DataPointV { + static func bridgeJSLift(_ callbackId: Int32) -> (Double) async -> DataPoint { let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] param0 in + return { [callback] (param0: Double) async -> DataPoint in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() - let (param0IsSome, param0Value) = param0.bridgeJSLowerParameter() - let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS(callbackValue, param0IsSome, param0Value) - return String.bridgeJSLiftReturn(ret) + let resolved = try! await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending DataPoint) -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + let callbackValue = callback.bridgeJSLowerParameter() + let param0Value = param0.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV(resolveRef, rejectRef, callbackValue, param0Value) + } + return resolved #else fatalError("Only available on WebAssembly") #endif @@ -1778,10 +2295,10 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSqSi_SS { } } -extension JSTypedClosure where Signature == (Optional) -> String { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Optional) -> String) { +extension JSTypedClosure where Signature == (Double) async -> DataPoint { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Double) async -> DataPoint) { self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS, + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV, body: body, fileID: fileID, line: line @@ -1789,13 +2306,14 @@ extension JSTypedClosure where Signature == (Optional) -> String { } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Value: Int32) -> Void { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV(_ boxPtr: UnsafeMutableRawPointer, _ param0: Float64) -> Int32 { #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(Optional) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) - return result.bridgeJSLowerReturn() + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Double) async -> DataPoint>>.fromOpaque(boxPtr).takeUnretainedValue().closure + return _bjs_makePromise(resolve: Promise_resolve_9DataPointV, reject: Promise_reject) { + return await closure(Double.bridgeJSLiftParameter(param0)) + } #else fatalError("Only available on WebAssembly") #endif @@ -1924,6 +2442,67 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11 #endif } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y_extern(_ callback: Int32, _ param0: Int32) -> Void +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y_extern(_ callback: Int32, _ param0: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y(_ callback: Int32, _ param0: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending AsyncPayloadResult) -> Void { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let param0CaseId = param0.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y(callbackValue, param0CaseId) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (sending AsyncPayloadResult) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending AsyncPayloadResult) -> Void) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending AsyncPayloadResult) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(AsyncPayloadResult.bridgeJSLiftParameter(param0)) + #else + fatalError("Only available on WebAssembly") + #endif +} + #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y") fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y_extern(_ callback: Int32, _ param0: Int32) -> Void @@ -2046,6 +2625,67 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7J #endif } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y_extern(_ callback: Int32) -> Void +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y_extern(_ callback: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y(_ callback: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y_extern(callback) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestss9DataPointV_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending DataPoint) -> Void { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let _ = param0.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y(callbackValue) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (sending DataPoint) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending DataPoint) -> Void) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y(_ boxPtr: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending DataPoint) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(DataPoint.bridgeJSLiftParameter()) + #else + fatalError("Only available on WebAssembly") + #endif +} + #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y") fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void @@ -6974,6 +7614,132 @@ public func _bjs_ArrayMembers_firstString() -> Void { #endif } +@_expose(wasm, "bjs_awaitAsyncCallback") +@_cdecl("bjs_awaitAsyncCallback") +public func _bjs_awaitAsyncCallback(_ fetch: Int32) -> Int32 { + #if arch(wasm32) + return _bjs_makePromise(resolve: Promise_resolve_SS, reject: Promise_reject) { () async throws(JSException) -> String in + return try await awaitAsyncCallback(_: _BJS_Closure_20BridgeJSRuntimeTestsYaKSS_SS.bridgeJSLift(fetch)) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_makeAsyncParser") +@_cdecl("bjs_makeAsyncParser") +public func _bjs_makeAsyncParser() -> Int32 { + #if arch(wasm32) + let ret = makeAsyncParser() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_makeAsyncEcho") +@_cdecl("bjs_makeAsyncEcho") +public func _bjs_makeAsyncEcho() -> Int32 { + #if arch(wasm32) + let ret = makeAsyncEcho() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_makeAsyncRecorder") +@_cdecl("bjs_makeAsyncRecorder") +public func _bjs_makeAsyncRecorder() -> Int32 { + #if arch(wasm32) + let ret = makeAsyncRecorder() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_lastRecordedValue") +@_cdecl("bjs_lastRecordedValue") +public func _bjs_lastRecordedValue() -> Void { + #if arch(wasm32) + let ret = lastRecordedValue() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_makeAsyncPayloadLoader") +@_cdecl("bjs_makeAsyncPayloadLoader") +public func _bjs_makeAsyncPayloadLoader() -> Int32 { + #if arch(wasm32) + let ret = makeAsyncPayloadLoader() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_awaitPayloadCallback") +@_cdecl("bjs_awaitPayloadCallback") +public func _bjs_awaitPayloadCallback(_ load: Int32) -> Int32 { + #if arch(wasm32) + return _bjs_makePromise(resolve: Promise_resolve_SS, reject: Promise_reject) { () async throws(JSException) -> String in + return try await awaitPayloadCallback(_: _BJS_Closure_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO.bridgeJSLift(load)) + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_makeAsyncPointMaker") +@_cdecl("bjs_makeAsyncPointMaker") +public func _bjs_makeAsyncPointMaker() -> Int32 { + #if arch(wasm32) + let ret = makeAsyncPointMaker() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_makeThrowingParser") +@_cdecl("bjs_makeThrowingParser") +public func _bjs_makeThrowingParser() -> Int32 { + #if arch(wasm32) + let ret = makeThrowingParser() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_runValidator") +@_cdecl("bjs_runValidator") +public func _bjs_runValidator(_ validate: Int32) -> Int32 { + #if arch(wasm32) + do { + let ret = try runValidator(_: _BJS_Closure_20BridgeJSRuntimeTestsKSS_Sb.bridgeJSLift(validate)) + return ret.bridgeJSLowerReturn() + } catch let error { + if let error = error.thrownValue.object { + withExtendedLifetime(error) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } else { + let jsError = JSError(message: error.description) + withExtendedLifetime(jsError.jsObject) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } + return 0 + } + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_roundTripVoid") @_cdecl("bjs_roundTripVoid") public func _bjs_roundTripVoid() -> Void { @@ -12176,6 +12942,27 @@ func _$Promise_resolve_SD11PublicPointV(_ promise: JSObject, _ value: [String: P if let error = _swift_js_take_exception() { throw error } } +@JSFunction func Promise_resolve_9DataPointV(_ promise: JSObject, _ value: DataPoint) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_9DataPointV") +fileprivate func promise_resolve_BridgeJSRuntimeTests_9DataPointV_extern(_ promise: Int32, _ value: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_9DataPointV_extern(_ promise: Int32, _ value: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_9DataPointV(_ promise: Int32, _ value: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_9DataPointV_extern(promise, value) +} + +func _$Promise_resolve_9DataPointV(_ promise: JSObject, _ value: DataPoint) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueObjectId = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_9DataPointV(promiseValue, valueObjectId) + if let error = _swift_js_take_exception() { throw error } +} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ArrayElementObject_init") fileprivate func bjs_ArrayElementObject_init_extern(_ idBytes: Int32, _ idLength: Int32) -> Int32 @@ -12864,6 +13651,28 @@ func _$AsyncImportImports_jsAsyncRoundTripOptionalAssociatedValueEnum(_ v: Optio return resolved } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureAsyncImports_runJsClosureAsyncTests_static") +fileprivate func bjs_ClosureAsyncImports_runJsClosureAsyncTests_static_extern(_ resolveRef: Int32, _ rejectRef: Int32) -> Void +#else +fileprivate func bjs_ClosureAsyncImports_runJsClosureAsyncTests_static_extern(_ resolveRef: Int32, _ rejectRef: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ClosureAsyncImports_runJsClosureAsyncTests_static(_ resolveRef: Int32, _ rejectRef: Int32) -> Void { + return bjs_ClosureAsyncImports_runJsClosureAsyncTests_static_extern(resolveRef, rejectRef) +} + +func _$ClosureAsyncImports_runJsClosureAsyncTests() async throws(JSException) -> Void { + try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<() -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + bjs_ClosureAsyncImports_runJsClosureAsyncTests_static(resolveRef, rejectRef) + } +} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportImports_jsApplyVoid_static") fileprivate func bjs_ClosureSupportImports_jsApplyVoid_static_extern(_ callback: Int32) -> Void @@ -13246,6 +14055,25 @@ func _$ClosureSupportImports_runJsClosureSupportTests() throws(JSException) -> V } } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureThrowsImports_runJsClosureThrowsTests_static") +fileprivate func bjs_ClosureThrowsImports_runJsClosureThrowsTests_static_extern() -> Void +#else +fileprivate func bjs_ClosureThrowsImports_runJsClosureThrowsTests_static_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ClosureThrowsImports_runJsClosureThrowsTests_static() -> Void { + return bjs_ClosureThrowsImports_runJsClosureThrowsTests_static_extern() +} + +func _$ClosureThrowsImports_runJsClosureThrowsTests() throws(JSException) -> Void { + bjs_ClosureThrowsImports_runJsClosureThrowsTests_static() + if let error = _swift_js_take_exception() { + throw error + } +} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DefaultArgumentImports_runJsDefaultArgumentTests_static") fileprivate func bjs_DefaultArgumentImports_runJsDefaultArgumentTests_static_extern() -> Void diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index a51e6bafd..297ab5a07 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -11604,6 +11604,374 @@ ], "exposeToGlobal" : false, "functions" : [ + { + "abiName" : "bjs_awaitAsyncCallback", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "awaitAsyncCallback", + "parameters" : [ + { + "label" : "_", + "name" : "fetch", + "type" : { + "closure" : { + "_0" : { + "isAsync" : true, + "isThrows" : true, + "mangleName" : "20BridgeJSRuntimeTestsYaKSS_SS", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "string" : { + + } + } + ], + "returnType" : { + "string" : { + + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_makeAsyncParser", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "makeAsyncParser", + "parameters" : [ + + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : true, + "isThrows" : true, + "mangleName" : "20BridgeJSRuntimeTestsYaKSS_SS", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "string" : { + + } + } + ], + "returnType" : { + "string" : { + + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : true + } + } + }, + { + "abiName" : "bjs_makeAsyncEcho", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "makeAsyncEcho", + "parameters" : [ + + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : true, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsYaSS_SS", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "string" : { + + } + } + ], + "returnType" : { + "string" : { + + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : true + } + } + }, + { + "abiName" : "bjs_makeAsyncRecorder", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "makeAsyncRecorder", + "parameters" : [ + + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : true, + "isThrows" : true, + "mangleName" : "20BridgeJSRuntimeTestsYaKSS_y", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "string" : { + + } + } + ], + "returnType" : { + "void" : { + + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : true + } + } + }, + { + "abiName" : "bjs_lastRecordedValue", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "lastRecordedValue", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_makeAsyncPayloadLoader", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "makeAsyncPayloadLoader", + "parameters" : [ + + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : true, + "isThrows" : true, + "mangleName" : "20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "bool" : { + + } + } + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "AsyncPayloadResult" + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : true + } + } + }, + { + "abiName" : "bjs_awaitPayloadCallback", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "awaitPayloadCallback", + "parameters" : [ + { + "label" : "_", + "name" : "load", + "type" : { + "closure" : { + "_0" : { + "isAsync" : true, + "isThrows" : true, + "mangleName" : "20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "bool" : { + + } + } + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "AsyncPayloadResult" + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_makeAsyncPointMaker", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "makeAsyncPointMaker", + "parameters" : [ + + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : true, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsYaSd_9DataPointV", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "double" : { + + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "DataPoint" + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : true + } + } + }, + { + "abiName" : "bjs_makeThrowingParser", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "makeThrowingParser", + "parameters" : [ + + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : true, + "mangleName" : "20BridgeJSRuntimeTestsKSS_Si", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "string" : { + + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : true + } + } + }, + { + "abiName" : "bjs_runValidator", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "runValidator", + "parameters" : [ + { + "label" : "_", + "name" : "validate", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : true, + "mangleName" : "20BridgeJSRuntimeTestsKSS_Sb", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "string" : { + + } + } + ], + "returnType" : { + "bool" : { + + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "bool" : { + + } + } + }, { "abiName" : "bjs_roundTripVoid", "effects" : { @@ -18709,6 +19077,45 @@ { "functions" : [ + ], + "types" : [ + { + "accessLevel" : "internal", + "getters" : [ + + ], + "methods" : [ + + ], + "name" : "ClosureAsyncImports", + "setters" : [ + + ], + "staticMethods" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "runJsClosureAsyncTests", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + } + ] + } + ] + }, + { + "functions" : [ + ], "types" : [ { @@ -19527,6 +19934,45 @@ { "functions" : [ + ], + "types" : [ + { + "accessLevel" : "internal", + "getters" : [ + + ], + "methods" : [ + + ], + "name" : "ClosureThrowsImports", + "setters" : [ + + ], + "staticMethods" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "runJsClosureThrowsTests", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + } + ] + } + ] + }, + { + "functions" : [ + ], "types" : [ { diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/ClosureAsyncTests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/ClosureAsyncTests.mjs new file mode 100644 index 000000000..d7f249ec4 --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/JavaScript/ClosureAsyncTests.mjs @@ -0,0 +1,137 @@ +import assert from "node:assert"; +import { AsyncPayloadResultValues } from '../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.js'; + +/** + * @returns {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Imports["ClosureAsyncImports"]} + */ +export function getImports(importsContext) { + return { + runJsClosureAsyncTests: async () => { + const exports = importsContext.getExports(); + if (!exports) { + throw new Error("No exports!?"); + } + await runJsClosureAsyncTests(exports); + }, + }; +} + +/** @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports */ +export async function runJsClosureAsyncTests(exports) { + assert.equal( + await exports.awaitAsyncCallback(async (req) => { + await Promise.resolve(); + return `js-${req}`; + }), + "swift-saw:js-request", + ); + + let directionAReject = null; + try { + await exports.awaitAsyncCallback(async () => { + throw new Error("CallbackRejected"); + }); + assert.fail("Expected awaitAsyncCallback to reject when the JS callback rejects"); + } catch (error) { + directionAReject = error; + } + assert.notEqual(directionAReject, null); + assert.equal(directionAReject.message, "CallbackRejected"); + + const parser = exports.makeAsyncParser(); + + const parsed = parser("42"); + assert.ok(parsed instanceof Promise, "async closure must return a Promise"); + assert.equal(await parsed, "parsed:42"); + assert.equal(await parser("-7"), "parsed:-7"); + + // Blocked by swiftlang/swift#89320 (wasm32 typed-throws async miscompile for captureless closures); re-enable once swiftlang/swift#89715 lands. + const ASYNC_THROWS_CLOSURE_REJECT_BLOCKED = true; + if (!ASYNC_THROWS_CLOSURE_REJECT_BLOCKED) { + let directionBReject = null; + try { + await parser("not-a-number"); + assert.fail("Expected makeAsyncParser closure to reject for invalid input"); + } catch (error) { + directionBReject = error; + } + assert.notEqual(directionBReject, null); + assert.equal(directionBReject.message, "AsyncParseError: not-a-number"); + } + + assert.equal(await parser("100"), "parsed:100"); + + const echo = exports.makeAsyncEcho(); + const echoed = echo("hi"); + assert.ok(echoed instanceof Promise, "non-throwing async closure must return a Promise"); + assert.equal(await echoed, "echo:hi"); + + const recorder = exports.makeAsyncRecorder(); + const recorded = recorder("logged-value"); + assert.ok(recorded instanceof Promise, "Void async closure must return a Promise"); + assert.equal(await recorded, undefined); + assert.equal(exports.lastRecordedValue(), "logged-value"); + + if (!ASYNC_THROWS_CLOSURE_REJECT_BLOCKED) { + let voidReject = null; + try { + await recorder("boom"); + assert.fail("Expected makeAsyncRecorder closure to reject for 'boom'"); + } catch (error) { + voidReject = error; + } + assert.notEqual(voidReject, null); + assert.equal(voidReject.message, "AsyncRecorderError"); + } + + const payloadLoader = exports.makeAsyncPayloadLoader(); + const payloadPromise = payloadLoader(true); + assert.ok(payloadPromise instanceof Promise, "associated-value enum async closure must return a Promise"); + assert.deepEqual(await payloadPromise, { tag: AsyncPayloadResultValues.Tag.Success, param0: "loaded" }); + assert.deepEqual(await payloadLoader(false), { tag: AsyncPayloadResultValues.Tag.Failure, param0: 42 }); + + assert.equal( + await exports.awaitPayloadCallback(async (succeed) => { + await Promise.resolve(); + return succeed + ? { tag: AsyncPayloadResultValues.Tag.Success, param0: "js" } + : { tag: AsyncPayloadResultValues.Tag.Idle }; + }), + "success:js|idle", + ); + + const pointMaker = exports.makeAsyncPointMaker(); + const pointPromise = pointMaker(3); + assert.ok(pointPromise instanceof Promise, "struct-returning async closure must return a Promise"); + const point = await pointPromise; + assert.equal(point.x, 3); + assert.equal(point.y, 6); + assert.equal(point.label, "async:3.0"); + + { + const racer = exports.makeAsyncEcho(); + const inFlight = racer("race"); + if (typeof racer.release === "function") { + racer.release(); + } + if (typeof global !== "undefined" && typeof global.gc === "function") { + global.gc(); + } + assert.equal(await inFlight, "echo:race"); + } + + { + const concurrent = exports.makeAsyncEcho(); + const promises = []; + for (let i = 0; i < 16; i++) { + promises.push(concurrent("c" + i)); + } + const results = await Promise.all(promises); + for (let i = 0; i < 16; i++) { + assert.equal(results[i], "echo:c" + i); + } + if (typeof concurrent.release === "function") { + concurrent.release(); + } + } +} diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/ClosureThrowsTests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/ClosureThrowsTests.mjs new file mode 100644 index 000000000..94bd27d5c --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/JavaScript/ClosureThrowsTests.mjs @@ -0,0 +1,57 @@ +import assert from "node:assert"; + +/** + * @returns {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Imports["ClosureThrowsImports"]} + */ +export function getImports(importsContext) { + return { + runJsClosureThrowsTests: () => { + const exports = importsContext.getExports(); + if (!exports) { + throw new Error("No exports!?"); + } + runJsClosureThrowsTests(exports); + }, + }; +} + +/** @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports */ +export function runJsClosureThrowsTests(exports) { + const parser = exports.makeThrowingParser(); + + assert.equal(parser("42"), 42); + assert.equal(parser("-7"), -7); + + let caught = null; + try { + parser("not-a-number"); + assert.fail("Expected makeThrowingParser closure to throw for invalid input"); + } catch (error) { + caught = error; + } + assert.notEqual(caught, null); + assert.equal(caught.message, "ParseError: not-a-number"); + + assert.equal(parser("100"), 100); + + assert.equal( + exports.runValidator((value) => value === "input"), + true, + ); + assert.equal( + exports.runValidator((value) => value === "something-else"), + false, + ); + + let propagated = null; + try { + exports.runValidator(() => { + throw new Error("ValidatorError"); + }); + assert.fail("Expected runValidator to propagate the JS callback error"); + } catch (error) { + propagated = error; + } + assert.notEqual(propagated, null); + assert.equal(propagated.message, "ValidatorError"); +} diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index bf3073c62..658bceed9 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -6,6 +6,8 @@ import { import { ImportedFoo } from './BridgeJSRuntimeTests/JavaScript/Types.mjs'; import { runJsOptionalSupportTests } from './BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs'; import { getImports as getClosureSupportImports } from './BridgeJSRuntimeTests/JavaScript/ClosureSupportTests.mjs'; +import { getImports as getClosureThrowsImports } from './BridgeJSRuntimeTests/JavaScript/ClosureThrowsTests.mjs'; +import { getImports as getClosureAsyncImports } from './BridgeJSRuntimeTests/JavaScript/ClosureAsyncTests.mjs'; import { getImports as getSwiftClassSupportImports } from './BridgeJSRuntimeTests/JavaScript/SwiftClassSupportTests.mjs'; import { getImports as getOptionalSupportImports } from './BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs'; import { getImports as getArraySupportImports, ArrayElementObject } from './BridgeJSRuntimeTests/JavaScript/ArraySupportTests.mjs'; @@ -160,6 +162,8 @@ export async function setupOptions(options, context) { runJsOptionalSupportTests(exports); }, ClosureSupportImports: getClosureSupportImports(importsContext), + ClosureThrowsImports: getClosureThrowsImports(importsContext), + ClosureAsyncImports: getClosureAsyncImports(importsContext), SwiftClassSupportImports: getSwiftClassSupportImports(importsContext), OptionalSupportImports: getOptionalSupportImports(importsContext), ArraySupportImports: getArraySupportImports(importsContext), From c02073465631e595fecff9872db7450707b37b49 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Thu, 11 Jun 2026 11:42:34 +0200 Subject: [PATCH 14/50] BridgeJS: Warn on async throwing closures passed to JavaScript --- .../BridgeJS/Sources/BridgeJSCore/Misc.swift | 20 ++- .../BridgeJSCore/SwiftToSkeleton.swift | 53 +++++++- .../Sources/BridgeJSTool/BridgeJSTool.swift | 3 + .../BridgeJSToolInternal.swift | 5 + .../ClosureAsyncThrowsWarningTests.swift | 122 ++++++++++++++++++ .../Bringing-Swift-Closures-to-JavaScript.md | 2 +- .../Exporting-Swift-Closure.md | 2 +- 7 files changed, 197 insertions(+), 10 deletions(-) create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/ClosureAsyncThrowsWarningTests.swift diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/Misc.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/Misc.swift index 37040d7a6..8d7b7c902 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/Misc.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/Misc.swift @@ -137,14 +137,21 @@ import SwiftSyntax import class Foundation.ProcessInfo public struct DiagnosticError: Error { + public enum Severity: String, Sendable { + case error + case warning + } + public let node: Syntax public let message: String public let hint: String? + public let severity: Severity - public init(node: some SyntaxProtocol, message: String, hint: String? = nil) { + public init(node: some SyntaxProtocol, message: String, hint: String? = nil, severity: Severity = .error) { self.node = Syntax(node) self.message = message self.hint = hint + self.severity = severity } /// Formats the diagnostic error as a string. @@ -166,12 +173,14 @@ public struct DiagnosticError: Error { let lineNumberWidth = max(3, String(lines.count).count) + let severityLabel = severity.rawValue + let severityColor = severity == .warning ? ANSI.boldYellow : ANSI.boldRed let header: String = { guard colorize else { - return "\(displayFileName):\(startLocation.line):\(startLocation.column): error: \(message)" + return "\(displayFileName):\(startLocation.line):\(startLocation.column): \(severityLabel): \(message)" } return - "\(displayFileName):\(startLocation.line):\(startLocation.column): \(ANSI.boldRed)error: \(ANSI.boldDefault)\(message)\(ANSI.reset)" + "\(displayFileName):\(startLocation.line):\(startLocation.column): \(severityColor)\(severityLabel): \(ANSI.boldDefault)\(message)\(ANSI.reset)" }() let highlightStartColumn = min(max(1, startLocation.column), mainLine.utf8.count + 1) @@ -227,8 +236,8 @@ public struct DiagnosticError: Error { let pointerSpacing = max(0, highlightStartColumn - 1) let pointerMessage: String = { let pointer = String(repeating: " ", count: pointerSpacing) + "`- " - guard colorize else { return pointer + "error: \(message)" } - return pointer + "\(ANSI.boldRed)error: \(ANSI.boldDefault)\(message)\(ANSI.reset)" + guard colorize else { return pointer + "\(severityLabel): \(message)" } + return pointer + "\(severityColor)\(severityLabel): \(ANSI.boldDefault)\(message)\(ANSI.reset)" }() descriptionParts.append( Self.formatSourceLine( @@ -304,6 +313,7 @@ public struct BridgeJSCoreDiagnosticError: Swift.Error, CustomStringConvertible private enum ANSI { static let reset = "\u{001B}[0;0m" static let boldRed = "\u{001B}[1;31m" + static let boldYellow = "\u{001B}[1;33m" static let boldDefault = "\u{001B}[1;39m" static let cyan = "\u{001B}[0;36m" static let underline = "\u{001B}[4;39m" diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index 18bde3c7f..ab9175e16 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -24,6 +24,9 @@ public final class SwiftToSkeleton { private var sourceFiles: [(sourceFile: SourceFileSyntax, inputFilePath: String)] = [] private var usedExternalModules = Set() + /// Non-fatal diagnostics collected during `finalize()`. These do not fail the build. + public private(set) var warnings: [(file: String, diagnostic: DiagnosticError)] = [] + public init( progress: ProgressReporting, moduleName: String, @@ -87,10 +90,15 @@ public final class SwiftToSkeleton { ) importCollector.walk(sourceFile) - let importErrorsFatal = importCollector.errors.filter { !$0.message.contains("Unsupported type '") } - if !exportCollector.errors.isEmpty || !importErrorsFatal.isEmpty { + let exportErrors = exportCollector.errors.filter { $0.severity == .error } + let importErrorsFatal = importCollector.errors.filter { + $0.severity == .error && !$0.message.contains("Unsupported type '") + } + let fileWarnings = (exportCollector.errors + importCollector.errors).filter { $0.severity == .warning } + warnings.append(contentsOf: fileWarnings.map { (file: inputFilePath, diagnostic: $0) }) + if !exportErrors.isEmpty || !importErrorsFatal.isEmpty { perSourceErrors.append( - (inputFilePath: inputFilePath, errors: exportCollector.errors + importErrorsFatal) + (inputFilePath: inputFilePath, errors: exportErrors + importErrorsFatal) ) } @@ -602,6 +610,37 @@ private enum ExportSwiftConstants { static let supportedRawTypes = SwiftEnumRawType.supportedTypeNames } +/// Warns about Swift closures handed to JavaScript with an `async throws(JSException)` signature. +/// Captureless closure values lose their thrown error at runtime due to a Swift compiler bug. +private func asyncThrowsClosureWarning(node: some SyntaxProtocol) -> DiagnosticError { + DiagnosticError( + node: node, + message: + "async throwing closures passed to JavaScript may lose thrown errors due to a Swift compiler bug " + + "(swiftlang/swift#89320) unless the closure value captures state", + hint: + "Pass a closure that captures state, or see the BridgeJS closure documentation for details", + severity: .warning + ) +} + +extension BridgeType { + fileprivate var containsAsyncThrowsClosure: Bool { + switch self { + case .closure(let signature, _): + return signature.isAsync && signature.isThrows + case .nullable(let wrapped, _): + return wrapped.containsAsyncThrowsClosure + case .array(let element): + return element.containsAsyncThrowsClosure + case .dictionary(let value): + return value.containsAsyncThrowsClosure + default: + return false + } + } +} + extension AttributeSyntax { /// The attribute name as text when it is a simple identifier (e.g. "JS", "JSFunction"). /// Prefer this over `attributeName.trimmedDescription` for name checks to avoid unnecessary string work. @@ -1194,6 +1233,9 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { guard let type = resolvedType else { return nil } returnType = type + if returnType.containsAsyncThrowsClosure { + errors.append(asyncThrowsClosureWarning(node: returnClause.type)) + } } else { returnType = .void } @@ -2853,6 +2895,11 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { guard let bridgeType = withLookupErrors({ parent.lookupType(for: type, errors: &$0) }) else { return nil } + if case .closure(let signature, useJSTypedClosure: true) = bridgeType, + signature.isAsync, signature.isThrows + { + errors.append(asyncThrowsClosureWarning(node: type)) + } let nameToken = param.secondName ?? param.firstName let name = SwiftToSkeleton.normalizeIdentifier(nameToken.text) let labelToken = param.secondName == nil ? nil : param.firstName diff --git a/Plugins/BridgeJS/Sources/BridgeJSTool/BridgeJSTool.swift b/Plugins/BridgeJS/Sources/BridgeJSTool/BridgeJSTool.swift index 005af04a8..fa8a0a273 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSTool/BridgeJSTool.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSTool/BridgeJSTool.swift @@ -201,6 +201,9 @@ import BridgeJSUtilities let skeleton = try withSpan("SwiftToSkeleton.finalize") { return try swiftToSkeleton.finalize() } + for (file, diagnostic) in swiftToSkeleton.warnings { + printStderr(diagnostic.formattedDescription(fileName: file)) + } var exporter: ExportSwift? if let skeleton = skeleton.exported { diff --git a/Plugins/BridgeJS/Sources/BridgeJSToolInternal/BridgeJSToolInternal.swift b/Plugins/BridgeJS/Sources/BridgeJSToolInternal/BridgeJSToolInternal.swift index f4de24093..4a58f1972 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSToolInternal/BridgeJSToolInternal.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSToolInternal/BridgeJSToolInternal.swift @@ -60,6 +60,11 @@ import ArgumentParser swiftToSkeleton.addSourceFile(sourceFile, inputFilePath: inputFile) } let skeleton = try swiftToSkeleton.finalize() + for (file, diagnostic) in swiftToSkeleton.warnings { + FileHandle.standardError.write( + Data((diagnostic.formattedDescription(fileName: file, colorize: false) + "\n").utf8) + ) + } let encoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted, .sortedKeys] let skeletonData = try encoder.encode(skeleton) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/ClosureAsyncThrowsWarningTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/ClosureAsyncThrowsWarningTests.swift new file mode 100644 index 000000000..4ee9bc5cc --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/ClosureAsyncThrowsWarningTests.swift @@ -0,0 +1,122 @@ +import Foundation +import SwiftParser +import SwiftSyntax +import Testing + +@testable import BridgeJSCore +@testable import BridgeJSSkeleton + +@Suite struct ClosureAsyncThrowsWarningTests { + @Test + func warnsOnTypedAsyncThrowsClosureReturn() throws { + let result = try resolveApp( + source: """ + @JS public func makeParser() -> JSTypedClosure<(String) async throws(JSException) -> String> { + fatalError() + } + """ + ) + #expect(result.warnings.count == 1) + let warning = try #require(result.warnings.first) + #expect(warning.diagnostic.severity == .warning) + #expect(warning.diagnostic.message.contains("swiftlang/swift#89320")) + } + + @Test + func warnsOnPlainAsyncThrowsClosureReturn() throws { + let result = try resolveApp( + source: """ + @JS public func makeParser() -> (String) async throws(JSException) -> String { + fatalError() + } + """ + ) + #expect(result.warnings.count == 1) + #expect(result.warnings.first?.diagnostic.severity == .warning) + } + + @Test + func doesNotWarnOnAsyncThrowsClosureParameter() throws { + let result = try resolveApp( + source: """ + @JS public func process(_ cb: (String) async throws(JSException) -> String) {} + """ + ) + #expect(result.warnings.isEmpty) + } + + @Test + func doesNotWarnOnNonThrowingAsyncClosureReturn() throws { + let result = try resolveApp( + source: """ + @JS public func makeParser() -> JSTypedClosure<(String) async -> String> { + fatalError() + } + """ + ) + #expect(result.warnings.isEmpty) + } + + @Test + func doesNotWarnOnSyncThrowsClosureReturn() throws { + let result = try resolveApp( + source: """ + @JS public func makeParser() -> JSTypedClosure<(String) throws(JSException) -> String> { + fatalError() + } + """ + ) + #expect(result.warnings.isEmpty) + } + + @Test + func warnsOnTypedAsyncThrowsClosureImportParameter() throws { + let result = try resolveApp( + source: """ + @JSFunction func register( + _ cb: JSTypedClosure<(String) async throws(JSException) -> String> + ) throws(JSException) + """ + ) + #expect(result.warnings.count == 1) + #expect(result.warnings.first?.diagnostic.severity == .warning) + } + + @Test + func warningDoesNotFailSkeletonResolution() throws { + let result = try resolveApp( + source: """ + @JS public func makeParser() -> JSTypedClosure<(String) async throws(JSException) -> String> { + fatalError() + } + """ + ) + let function = try #require(result.skeleton.exported?.functions.first(where: { $0.name == "makeParser" })) + guard case .closure(let signature, true) = function.returnType else { + Issue.record("Expected typed closure return type, got \(function.returnType)") + return + } + #expect(signature.isAsync) + #expect(signature.isThrows) + } + + // MARK: - Utilities + + private struct Resolution { + let skeleton: BridgeJSSkeleton + let warnings: [(file: String, diagnostic: DiagnosticError)] + } + + private func resolveApp(source appSource: String) throws -> Resolution { + let swiftAPI = SwiftToSkeleton( + progress: .silent, + moduleName: "App", + exposeToGlobal: false, + externalModuleIndex: ExternalModuleIndex(dependencies: []) + ) + let sourceFile = Parser.parse(source: appSource) + swiftAPI.addSourceFile(sourceFile, inputFilePath: "App.swift") + let skeleton = try swiftAPI.finalize() + return Resolution(skeleton: skeleton, warnings: swiftAPI.warnings) + } +} diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Bringing-Swift-Closures-to-JavaScript.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Bringing-Swift-Closures-to-JavaScript.md index 2d0c94152..81383cb83 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Bringing-Swift-Closures-to-JavaScript.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Bringing-Swift-Closures-to-JavaScript.md @@ -78,7 +78,7 @@ const count = await fetchCount("/items"); // Promise **Cancellation is a non-goal.** There is no propagation between a Swift `Task` and a JavaScript `Promise` in either direction. -> Note: The reject path of async throwing typed closures is affected by a Swift compiler bug ([swiftlang/swift#89320](https://github.com/swiftlang/swift/issues/89320)). See for details. +> Note: The reject path of async throwing typed closures is affected by a Swift compiler bug ([swiftlang/swift#89320](https://github.com/swiftlang/swift/issues/89320)); BridgeJS emits a build-time warning for this signature. See for details. ## Lifetime and release() diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Closure.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Closure.md index 4dd08faa8..8e3e70176 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Closure.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Closure.md @@ -239,7 +239,7 @@ Notes: - The same `JavaScriptEventLoop.installGlobalExecutor()` requirement applies as for async functions; there is no special handling for closures. - **Cancellation is a non-goal.** There is no propagation between a Swift `Task` and a JavaScript `Promise` in either direction; cancelling one side does not cancel the other. -> Warning: When an async throwing closure handed to JavaScript throws, the error is currently lost instead of rejecting the `Promise` with it, due to a Swift compiler bug on `wasm32` ([swiftlang/swift#89320](https://github.com/swiftlang/swift/issues/89320), fix in progress in [swiftlang/swift#89715](https://github.com/swiftlang/swift/pull/89715)). Closures that capture state are unaffected, as are throwing JavaScript callbacks passed into Swift. +> Warning: When an async throwing closure handed to JavaScript throws, the error is currently lost instead of rejecting the `Promise` with it, due to a Swift compiler bug on `wasm32` ([swiftlang/swift#89320](https://github.com/swiftlang/swift/issues/89320), fix in progress in [swiftlang/swift#89715](https://github.com/swiftlang/swift/pull/89715)). Closures that capture state are unaffected, as are throwing JavaScript callbacks passed into Swift. BridgeJS emits a build-time warning for this signature. ## Supported Features From d26143ea6797d94f37ff76bc2f242b81c1cc28ad Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Thu, 11 Jun 2026 09:24:29 +0200 Subject: [PATCH 15/50] Box JSException storage in a class to fit the direct typed-error convention --- .../BridgeJSCore/SwiftToSkeleton.swift | 39 ------ .../ClosureAsyncThrowsWarningTests.swift | 122 ------------------ .../Bringing-Swift-Closures-to-JavaScript.md | 1 - .../Exporting-Swift-Closure.md | 4 +- Sources/JavaScriptKit/JSException.swift | 64 ++++++--- .../JavaScript/ClosureAsyncTests.mjs | 6 - .../JSClosure+AsyncTests.swift | 12 ++ 7 files changed, 63 insertions(+), 185 deletions(-) delete mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/ClosureAsyncThrowsWarningTests.swift diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index ab9175e16..a6afe2779 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -610,37 +610,6 @@ private enum ExportSwiftConstants { static let supportedRawTypes = SwiftEnumRawType.supportedTypeNames } -/// Warns about Swift closures handed to JavaScript with an `async throws(JSException)` signature. -/// Captureless closure values lose their thrown error at runtime due to a Swift compiler bug. -private func asyncThrowsClosureWarning(node: some SyntaxProtocol) -> DiagnosticError { - DiagnosticError( - node: node, - message: - "async throwing closures passed to JavaScript may lose thrown errors due to a Swift compiler bug " - + "(swiftlang/swift#89320) unless the closure value captures state", - hint: - "Pass a closure that captures state, or see the BridgeJS closure documentation for details", - severity: .warning - ) -} - -extension BridgeType { - fileprivate var containsAsyncThrowsClosure: Bool { - switch self { - case .closure(let signature, _): - return signature.isAsync && signature.isThrows - case .nullable(let wrapped, _): - return wrapped.containsAsyncThrowsClosure - case .array(let element): - return element.containsAsyncThrowsClosure - case .dictionary(let value): - return value.containsAsyncThrowsClosure - default: - return false - } - } -} - extension AttributeSyntax { /// The attribute name as text when it is a simple identifier (e.g. "JS", "JSFunction"). /// Prefer this over `attributeName.trimmedDescription` for name checks to avoid unnecessary string work. @@ -1233,9 +1202,6 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { guard let type = resolvedType else { return nil } returnType = type - if returnType.containsAsyncThrowsClosure { - errors.append(asyncThrowsClosureWarning(node: returnClause.type)) - } } else { returnType = .void } @@ -2895,11 +2861,6 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { guard let bridgeType = withLookupErrors({ parent.lookupType(for: type, errors: &$0) }) else { return nil } - if case .closure(let signature, useJSTypedClosure: true) = bridgeType, - signature.isAsync, signature.isThrows - { - errors.append(asyncThrowsClosureWarning(node: type)) - } let nameToken = param.secondName ?? param.firstName let name = SwiftToSkeleton.normalizeIdentifier(nameToken.text) let labelToken = param.secondName == nil ? nil : param.firstName diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/ClosureAsyncThrowsWarningTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/ClosureAsyncThrowsWarningTests.swift deleted file mode 100644 index 4ee9bc5cc..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/ClosureAsyncThrowsWarningTests.swift +++ /dev/null @@ -1,122 +0,0 @@ -import Foundation -import SwiftParser -import SwiftSyntax -import Testing - -@testable import BridgeJSCore -@testable import BridgeJSSkeleton - -@Suite struct ClosureAsyncThrowsWarningTests { - @Test - func warnsOnTypedAsyncThrowsClosureReturn() throws { - let result = try resolveApp( - source: """ - @JS public func makeParser() -> JSTypedClosure<(String) async throws(JSException) -> String> { - fatalError() - } - """ - ) - #expect(result.warnings.count == 1) - let warning = try #require(result.warnings.first) - #expect(warning.diagnostic.severity == .warning) - #expect(warning.diagnostic.message.contains("swiftlang/swift#89320")) - } - - @Test - func warnsOnPlainAsyncThrowsClosureReturn() throws { - let result = try resolveApp( - source: """ - @JS public func makeParser() -> (String) async throws(JSException) -> String { - fatalError() - } - """ - ) - #expect(result.warnings.count == 1) - #expect(result.warnings.first?.diagnostic.severity == .warning) - } - - @Test - func doesNotWarnOnAsyncThrowsClosureParameter() throws { - let result = try resolveApp( - source: """ - @JS public func process(_ cb: (String) async throws(JSException) -> String) {} - """ - ) - #expect(result.warnings.isEmpty) - } - - @Test - func doesNotWarnOnNonThrowingAsyncClosureReturn() throws { - let result = try resolveApp( - source: """ - @JS public func makeParser() -> JSTypedClosure<(String) async -> String> { - fatalError() - } - """ - ) - #expect(result.warnings.isEmpty) - } - - @Test - func doesNotWarnOnSyncThrowsClosureReturn() throws { - let result = try resolveApp( - source: """ - @JS public func makeParser() -> JSTypedClosure<(String) throws(JSException) -> String> { - fatalError() - } - """ - ) - #expect(result.warnings.isEmpty) - } - - @Test - func warnsOnTypedAsyncThrowsClosureImportParameter() throws { - let result = try resolveApp( - source: """ - @JSFunction func register( - _ cb: JSTypedClosure<(String) async throws(JSException) -> String> - ) throws(JSException) - """ - ) - #expect(result.warnings.count == 1) - #expect(result.warnings.first?.diagnostic.severity == .warning) - } - - @Test - func warningDoesNotFailSkeletonResolution() throws { - let result = try resolveApp( - source: """ - @JS public func makeParser() -> JSTypedClosure<(String) async throws(JSException) -> String> { - fatalError() - } - """ - ) - let function = try #require(result.skeleton.exported?.functions.first(where: { $0.name == "makeParser" })) - guard case .closure(let signature, true) = function.returnType else { - Issue.record("Expected typed closure return type, got \(function.returnType)") - return - } - #expect(signature.isAsync) - #expect(signature.isThrows) - } - - // MARK: - Utilities - - private struct Resolution { - let skeleton: BridgeJSSkeleton - let warnings: [(file: String, diagnostic: DiagnosticError)] - } - - private func resolveApp(source appSource: String) throws -> Resolution { - let swiftAPI = SwiftToSkeleton( - progress: .silent, - moduleName: "App", - exposeToGlobal: false, - externalModuleIndex: ExternalModuleIndex(dependencies: []) - ) - let sourceFile = Parser.parse(source: appSource) - swiftAPI.addSourceFile(sourceFile, inputFilePath: "App.swift") - let skeleton = try swiftAPI.finalize() - return Resolution(skeleton: skeleton, warnings: swiftAPI.warnings) - } -} diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Bringing-Swift-Closures-to-JavaScript.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Bringing-Swift-Closures-to-JavaScript.md index 81383cb83..7b95feb50 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Bringing-Swift-Closures-to-JavaScript.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Bringing-Swift-Closures-to-JavaScript.md @@ -78,7 +78,6 @@ const count = await fetchCount("/items"); // Promise **Cancellation is a non-goal.** There is no propagation between a Swift `Task` and a JavaScript `Promise` in either direction. -> Note: The reject path of async throwing typed closures is affected by a Swift compiler bug ([swiftlang/swift#89320](https://github.com/swiftlang/swift/issues/89320)); BridgeJS emits a build-time warning for this signature. See for details. ## Lifetime and release() diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Closure.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Closure.md index 8e3e70176..9b9f4ab97 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Closure.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Closure.md @@ -239,7 +239,7 @@ Notes: - The same `JavaScriptEventLoop.installGlobalExecutor()` requirement applies as for async functions; there is no special handling for closures. - **Cancellation is a non-goal.** There is no propagation between a Swift `Task` and a JavaScript `Promise` in either direction; cancelling one side does not cancel the other. -> Warning: When an async throwing closure handed to JavaScript throws, the error is currently lost instead of rejecting the `Promise` with it, due to a Swift compiler bug on `wasm32` ([swiftlang/swift#89320](https://github.com/swiftlang/swift/issues/89320), fix in progress in [swiftlang/swift#89715](https://github.com/swiftlang/swift/pull/89715)). Closures that capture state are unaffected, as are throwing JavaScript callbacks passed into Swift. BridgeJS emits a build-time warning for this signature. + ## Supported Features @@ -251,7 +251,7 @@ Notes: | Optional types in closures | ✅ | | Closure-typed `@JS` properties | ❌ | | Async closures `(A) async -> B` | ✅ | -| Async throwing closures `(A) async throws(JSException) -> B` | ✅ (reject path of closures handed to JS pending [swiftlang/swift#89320](https://github.com/swiftlang/swift/issues/89320)) | +| Async throwing closures `(A) async throws(JSException) -> B` | ✅ | | Throwing closures `(A) throws(JSException) -> B` | ✅ | ## See Also diff --git a/Sources/JavaScriptKit/JSException.swift b/Sources/JavaScriptKit/JSException.swift index 4d95e207d..84232163c 100644 --- a/Sources/JavaScriptKit/JSException.swift +++ b/Sources/JavaScriptKit/JSException.swift @@ -13,38 +13,66 @@ /// } /// ``` public struct JSException: Error, Equatable, CustomStringConvertible { - /// The value thrown from JavaScript. - /// This can be any JavaScript value (error object, string, number, etc.). - public var thrownValue: JSValue { - return _thrownValue + /// Boxes the exception payload in a class so `JSException` stays within the direct + /// typed-error convention on wasm32. + private final class Storage { + /// The actual JavaScript value that was thrown. + let thrownValue: JSValue + + /// A description of the exception. + let description: String + + /// The stack trace of the exception. + let stack: String? + + init(thrownValue: JSValue, description: String, stack: String?) { + self.thrownValue = thrownValue + self.description = description + self.stack = stack + } } - /// The actual JavaScript value that was thrown. + /// The boxed payload of the exception. /// /// Marked as `nonisolated(unsafe)` to satisfy `Sendable` requirement /// from `Error` protocol. - private nonisolated(unsafe) let _thrownValue: JSValue + private nonisolated(unsafe) let storage: Storage + + /// The value thrown from JavaScript. + /// This can be any JavaScript value (error object, string, number, etc.). + public var thrownValue: JSValue { + return storage.thrownValue + } /// A description of the exception. - public let description: String + public var description: String { + return storage.description + } /// The stack trace of the exception. - public let stack: String? + public var stack: String? { + return storage.stack + } /// Initializes a new JSException instance with a value thrown from JavaScript. /// /// Only available within the package. This must be called on the thread where the exception object created. + /// The stringified representation is captured on the object owner thread to bring useful info + /// to the catching thread even if they are different threads. @usableFromInline package init(_ thrownValue: JSValue) { - self._thrownValue = thrownValue - // Capture the stringified representation on the object owner thread - // to bring useful info to the catching thread even if they are different threads. if let errorObject = thrownValue.object, let stack = errorObject.stack.string { - self.description = "JSException(\(stack))" - self.stack = stack + self.storage = Storage( + thrownValue: thrownValue, + description: "JSException(\(stack))", + stack: stack + ) } else { - self.description = "JSException(\(thrownValue))" - self.stack = nil + self.storage = Storage( + thrownValue: thrownValue, + description: "JSException(\(thrownValue))", + stack: nil + ) } } @@ -55,4 +83,10 @@ public struct JSException: Error, Equatable, CustomStringConvertible { public init(message: String) { self.init(JSError(message: message).jsValue) } + + public static func == (lhs: JSException, rhs: JSException) -> Bool { + return lhs.storage.thrownValue == rhs.storage.thrownValue + && lhs.storage.description == rhs.storage.description + && lhs.storage.stack == rhs.storage.stack + } } diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/ClosureAsyncTests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/ClosureAsyncTests.mjs index d7f249ec4..57a824aa4 100644 --- a/Tests/BridgeJSRuntimeTests/JavaScript/ClosureAsyncTests.mjs +++ b/Tests/BridgeJSRuntimeTests/JavaScript/ClosureAsyncTests.mjs @@ -45,9 +45,6 @@ export async function runJsClosureAsyncTests(exports) { assert.equal(await parsed, "parsed:42"); assert.equal(await parser("-7"), "parsed:-7"); - // Blocked by swiftlang/swift#89320 (wasm32 typed-throws async miscompile for captureless closures); re-enable once swiftlang/swift#89715 lands. - const ASYNC_THROWS_CLOSURE_REJECT_BLOCKED = true; - if (!ASYNC_THROWS_CLOSURE_REJECT_BLOCKED) { let directionBReject = null; try { await parser("not-a-number"); @@ -57,7 +54,6 @@ export async function runJsClosureAsyncTests(exports) { } assert.notEqual(directionBReject, null); assert.equal(directionBReject.message, "AsyncParseError: not-a-number"); - } assert.equal(await parser("100"), "parsed:100"); @@ -72,7 +68,6 @@ export async function runJsClosureAsyncTests(exports) { assert.equal(await recorded, undefined); assert.equal(exports.lastRecordedValue(), "logged-value"); - if (!ASYNC_THROWS_CLOSURE_REJECT_BLOCKED) { let voidReject = null; try { await recorder("boom"); @@ -82,7 +77,6 @@ export async function runJsClosureAsyncTests(exports) { } assert.notEqual(voidReject, null); assert.equal(voidReject.message, "AsyncRecorderError"); - } const payloadLoader = exports.makeAsyncPayloadLoader(); const payloadPromise = payloadLoader(true); diff --git a/Tests/JavaScriptEventLoopTests/JSClosure+AsyncTests.swift b/Tests/JavaScriptEventLoopTests/JSClosure+AsyncTests.swift index e3c19a8e4..f53c7eeb7 100644 --- a/Tests/JavaScriptEventLoopTests/JSClosure+AsyncTests.swift +++ b/Tests/JavaScriptEventLoopTests/JSClosure+AsyncTests.swift @@ -24,6 +24,18 @@ class JSClosureAsyncTests: XCTestCase { XCTAssertEqual(result, 42.0) } + func testAsyncClosureReject() async throws { + let closure = JSClosure.async { (_) async throws(JSException) -> JSValue in + throw JSException(message: "AsyncClosureRejected") + }.jsValue + let result = await JSPromise(from: closure.function!())!.result + guard case .failure(let rejectedValue) = result else { + XCTFail("Expected the async closure promise to reject, got \(result)") + return + } + XCTAssertEqual(rejectedValue.object?.message.string, "AsyncClosureRejected") + } + func testAsyncClosureWithPriority() async throws { let priority = UnsafeSendableBox(nil) let closure = JSClosure.async(priority: .high) { _ in From e3315ec6b1031a1b6d82fd03e48414fdc002f1d8 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Fri, 12 Jun 2026 12:47:00 +0100 Subject: [PATCH 16/50] BridgeJS: Normalize wasm pointer offsets in JS --- .github/workflows/test.yml | 1 + .../Sources/BridgeJSLink/BridgeJSLink.swift | 7 +- .../BridgeJSLinkTests/ArrayTypes.js | 5 +- .../__Snapshots__/BridgeJSLinkTests/Async.js | 4 +- .../AsyncAssociatedValueEnum.js | 4 +- .../BridgeJSLinkTests/AsyncImport.js | 6 +- .../BridgeJSLinkTests/AsyncStaticImport.js | 6 +- .../BridgeJSLinkTests/DefaultParameters.js | 5 +- .../BridgeJSLinkTests/DictionaryTypes.js | 5 +- .../BridgeJSLinkTests/EnumAssociatedValue.js | 5 +- .../EnumAssociatedValueImport.js | 4 +- .../BridgeJSLinkTests/EnumCase.js | 4 +- .../BridgeJSLinkTests/EnumCaseImport.js | 4 +- .../BridgeJSLinkTests/EnumNamespace.Global.js | 5 +- .../BridgeJSLinkTests/EnumNamespace.js | 5 +- .../BridgeJSLinkTests/EnumRawType.js | 4 +- .../BridgeJSLinkTests/FixedWidthIntegers.js | 4 +- .../BridgeJSLinkTests/GlobalGetter.js | 4 +- .../BridgeJSLinkTests/GlobalThisImports.js | 4 +- .../IdentityModeClass.ConfigPointer.js | 5 +- .../IdentityModeClass.PerClass.js | 5 +- .../BridgeJSLinkTests/IdentityModeClass.js | 5 +- .../BridgeJSLinkTests/ImportArray.js | 4 +- .../ImportedTypeInExportedInterface.js | 4 +- .../BridgeJSLinkTests/InvalidPropertyNames.js | 4 +- .../BridgeJSLinkTests/JSClass.js | 4 +- .../JSClassStaticFunctions.js | 4 +- .../BridgeJSLinkTests/JSTypedArrayTypes.js | 4 +- .../BridgeJSLinkTests/JSValue.js | 5 +- .../BridgeJSLinkTests/MixedGlobal.js | 5 +- .../BridgeJSLinkTests/MixedModules.js | 5 +- .../BridgeJSLinkTests/MixedPrivate.js | 5 +- .../BridgeJSLinkTests/Namespaces.Global.js | 5 +- .../BridgeJSLinkTests/Namespaces.js | 5 +- .../BridgeJSLinkTests/NestedType.js | 5 +- .../BridgeJSLinkTests/Optionals.js | 5 +- .../BridgeJSLinkTests/PrimitiveParameters.js | 4 +- .../BridgeJSLinkTests/PrimitiveReturn.js | 4 +- .../BridgeJSLinkTests/PropertyTypes.js | 5 +- .../BridgeJSLinkTests/Protocol.js | 5 +- .../BridgeJSLinkTests/ProtocolInClosure.js | 7 +- .../StaticFunctions.Global.js | 5 +- .../BridgeJSLinkTests/StaticFunctions.js | 5 +- .../StaticProperties.Global.js | 5 +- .../BridgeJSLinkTests/StaticProperties.js | 5 +- .../BridgeJSLinkTests/StringParameter.js | 4 +- .../BridgeJSLinkTests/StringReturn.js | 4 +- .../BridgeJSLinkTests/SwiftClass.js | 5 +- .../BridgeJSLinkTests/SwiftClosure.js | 7 +- .../BridgeJSLinkTests/SwiftClosureImports.js | 6 +- .../BridgeJSLinkTests/SwiftStruct.js | 5 +- .../BridgeJSLinkTests/SwiftStructImports.js | 4 +- .../SwiftTypedClosureAccess.js | 6 +- .../__Snapshots__/BridgeJSLinkTests/Throws.js | 4 +- .../BridgeJSLinkTests/UnsafePointer.js | 4 +- .../VoidParameterVoidReturn.js | 4 +- Runtime/src/index.ts | 26 ++-- Runtime/src/js-value.ts | 26 ++-- Runtime/test/pointer-normalization.test.ts | 114 ++++++++++++++++++ package.json | 1 + 60 files changed, 294 insertions(+), 136 deletions(-) create mode 100644 Runtime/test/pointer-normalization.test.ts diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index ef72ca352..37e5bce78 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -54,6 +54,7 @@ jobs: echo "SWIFT_SDK_ID=${{ steps.setup-swiftwasm.outputs.swift-sdk-id }}" >> $GITHUB_ENV echo "SWIFT_BIN_PATH=$(dirname $(which swiftc))" >> $GITHUB_ENV - run: make bootstrap + - run: npm run test:runtime - run: make unittest # Skip unit tests with uwasi because its proc_exit throws # unhandled promise rejection. diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index a9acf048e..8c9c20a14 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -107,6 +107,7 @@ public struct BridgeJSLink { /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; const makeFresh = (identityMap) => { const obj = Object.create(prototype); const state = { pointer, deinit, hasReleased: false, identityMap }; @@ -428,7 +429,7 @@ public struct BridgeJSLink { "\(JSGlueVariableScope.reservedSwift).\(JSGlueVariableScope.reservedMemory).release(sourceId);" ) printer.write( - "const bytes = new Uint8Array(\(JSGlueVariableScope.reservedMemory).buffer, bytesPtr);" + "const bytes = new Uint8Array(\(JSGlueVariableScope.reservedMemory).buffer, bytesPtr >>> 0);" ) printer.write("bytes.set(source);") } @@ -443,7 +444,7 @@ public struct BridgeJSLink { printer.write("bjs[\"swift_js_init_memory_with_result\"] = function(ptr, len) {") printer.indent { printer.write( - "const target = new Uint8Array(\(JSGlueVariableScope.reservedMemory).buffer, ptr, len);" + "const target = new Uint8Array(\(JSGlueVariableScope.reservedMemory).buffer, ptr >>> 0, len >>> 0);" ) printer.write("target.set(\(JSGlueVariableScope.reservedStorageToReturnBytes));") printer.write("\(JSGlueVariableScope.reservedStorageToReturnBytes) = undefined;") @@ -789,7 +790,7 @@ public struct BridgeJSLink { helperPrinter.write("if (state.unregistered) {") helperPrinter.indent { helperPrinter.write( - "const bytes = new Uint8Array(\(JSGlueVariableScope.reservedMemory).buffer, state.file);" + "const bytes = new Uint8Array(\(JSGlueVariableScope.reservedMemory).buffer, state.file >>> 0);" ) helperPrinter.write("let length = 0;") helperPrinter.write("while (bytes[length] !== 0) { length += 1; }") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js index 75d961e98..7978d1522 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js @@ -70,14 +70,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } @@ -390,6 +390,7 @@ export async function createInstantiator(options, swift) { /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; const makeFresh = (identityMap) => { const obj = Object.create(prototype); const state = { pointer, deinit, hasReleased: false, identityMap }; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js index 9319cdd7e..680da9c5e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js @@ -155,14 +155,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js index 69e4a4928..98c0aff46 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js @@ -178,14 +178,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js index 27e53b8d7..fa50b23f2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js @@ -128,7 +128,7 @@ export async function createInstantiator(options, swift) { const state = { pointer, file, line, unregistered: false }; const real = (...args) => { if (state.unregistered) { - const bytes = new Uint8Array(memory.buffer, state.file); + const bytes = new Uint8Array(memory.buffer, state.file >>> 0); let length = 0; while (bytes[length] !== 0) { length += 1; } const fileID = decodeString(state.file, length); @@ -160,14 +160,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js index 789379a32..c359886b3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js @@ -128,7 +128,7 @@ export async function createInstantiator(options, swift) { const state = { pointer, file, line, unregistered: false }; const real = (...args) => { if (state.unregistered) { - const bytes = new Uint8Array(memory.buffer, state.file); + const bytes = new Uint8Array(memory.buffer, state.file >>> 0); let length = 0; while (bytes[length] !== 0) { length += 1; } const fileID = decodeString(state.file, length); @@ -159,14 +159,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js index 4b13bb633..0c6bfbec8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js @@ -87,14 +87,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } @@ -301,6 +301,7 @@ export async function createInstantiator(options, swift) { /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; const makeFresh = (identityMap) => { const obj = Object.create(prototype); const state = { pointer, deinit, hasReleased: false, identityMap }; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js index 2021f1c96..104472a02 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js @@ -86,14 +86,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } @@ -310,6 +310,7 @@ export async function createInstantiator(options, swift) { /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; const makeFresh = (identityMap) => { const obj = Object.create(prototype); const state = { pointer, deinit, hasReleased: false, identityMap }; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js index d97e4ef11..35b05fe61 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js @@ -788,14 +788,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } @@ -987,6 +987,7 @@ export async function createInstantiator(options, swift) { /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; const makeFresh = (identityMap) => { const obj = Object.create(prototype); const state = { pointer, deinit, hasReleased: false, identityMap }; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js index 1688dc94d..de374bd70 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js @@ -89,14 +89,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js index b4c5870b6..c2ae031bb 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js @@ -69,14 +69,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js index dc1b3c6b3..f2d6b8750 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js @@ -50,14 +50,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js index 050c16b18..1a8f5662f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js @@ -89,14 +89,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } @@ -293,6 +293,7 @@ export async function createInstantiator(options, swift) { /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; const makeFresh = (identityMap) => { const obj = Object.create(prototype); const state = { pointer, deinit, hasReleased: false, identityMap }; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js index 9f2f4122c..9196e99b3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js @@ -70,14 +70,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } @@ -274,6 +274,7 @@ export async function createInstantiator(options, swift) { /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; const makeFresh = (identityMap) => { const obj = Object.create(prototype); const state = { pointer, deinit, hasReleased: false, identityMap }; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js index 2ab98b31b..9e18a8d80 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js @@ -121,14 +121,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js index 94bfe89cd..a009f8d71 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js @@ -46,14 +46,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js index 174c9b430..b1d830768 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js @@ -46,14 +46,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js index e8a89c6e4..6f43c2d9c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js @@ -45,14 +45,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js index 99c0bb4ea..36728f890 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js @@ -45,14 +45,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } @@ -245,6 +245,7 @@ export async function createInstantiator(options, swift) { /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; const makeFresh = (identityMap) => { const obj = Object.create(prototype); const state = { pointer, deinit, hasReleased: false, identityMap }; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js index 82458b81a..ed180c1c8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js @@ -45,14 +45,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } @@ -245,6 +245,7 @@ export async function createInstantiator(options, swift) { /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; const makeFresh = (identityMap) => { const obj = Object.create(prototype); const state = { pointer, deinit, hasReleased: false, identityMap }; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js index 82458b81a..ed180c1c8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js @@ -45,14 +45,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } @@ -245,6 +245,7 @@ export async function createInstantiator(options, swift) { /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; const makeFresh = (identityMap) => { const obj = Object.create(prototype); const state = { pointer, deinit, hasReleased: false, identityMap }; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js index 8ebcbda28..2ad7251f8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js @@ -46,14 +46,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js index 710eebe36..4328e4d4e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js @@ -84,14 +84,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js index 605359fb8..8d1ac2698 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js @@ -46,14 +46,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js index e24b5dac5..08215f159 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js @@ -46,14 +46,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js index b936636a9..a38b0a391 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js @@ -46,14 +46,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.js index c5c37a512..5c713cc78 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.js @@ -45,14 +45,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js index e8f617e5b..d47fd3e85 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js @@ -135,14 +135,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } @@ -369,6 +369,7 @@ export async function createInstantiator(options, swift) { /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; const makeFresh = (identityMap) => { const obj = Object.create(prototype); const state = { pointer, deinit, hasReleased: false, identityMap }; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js index 3abacf371..577fa0ca7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js @@ -45,14 +45,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } @@ -237,6 +237,7 @@ export async function createInstantiator(options, swift) { /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; const makeFresh = (identityMap) => { const obj = Object.create(prototype); const state = { pointer, deinit, hasReleased: false, identityMap }; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js index a2dc23d68..e15c7bcfb 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js @@ -45,14 +45,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } @@ -245,6 +245,7 @@ export async function createInstantiator(options, swift) { /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; const makeFresh = (identityMap) => { const obj = Object.create(prototype); const state = { pointer, deinit, hasReleased: false, identityMap }; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js index 7fdf9b4c8..e1605fb10 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js @@ -45,14 +45,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } @@ -237,6 +237,7 @@ export async function createInstantiator(options, swift) { /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; const makeFresh = (identityMap) => { const obj = Object.create(prototype); const state = { pointer, deinit, hasReleased: false, identityMap }; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js index 09a6ace60..aa5e3dbb4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js @@ -45,14 +45,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } @@ -249,6 +249,7 @@ export async function createInstantiator(options, swift) { /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; const makeFresh = (identityMap) => { const obj = Object.create(prototype); const state = { pointer, deinit, hasReleased: false, identityMap }; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js index 1c9287a08..9a5c6473e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js @@ -45,14 +45,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } @@ -249,6 +249,7 @@ export async function createInstantiator(options, swift) { /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; const makeFresh = (identityMap) => { const obj = Object.create(prototype); const state = { pointer, deinit, hasReleased: false, identityMap }; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js index 7c2751964..1fb339f32 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js @@ -70,14 +70,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } @@ -280,6 +280,7 @@ export async function createInstantiator(options, swift) { /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; const makeFresh = (identityMap) => { const obj = Object.create(prototype); const state = { pointer, deinit, hasReleased: false, identityMap }; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js index c3c41f332..956582377 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js @@ -46,14 +46,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } @@ -526,6 +526,7 @@ export async function createInstantiator(options, swift) { /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; const makeFresh = (identityMap) => { const obj = Object.create(prototype); const state = { pointer, deinit, hasReleased: false, identityMap }; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js index 3957b5482..46d57d793 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js @@ -46,14 +46,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js index e624ceb1a..bb4e8552d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js @@ -46,14 +46,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js index 6e66102e2..0070d0dbe 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js @@ -45,14 +45,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } @@ -237,6 +237,7 @@ export async function createInstantiator(options, swift) { /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; const makeFresh = (identityMap) => { const obj = Object.create(prototype); const state = { pointer, deinit, hasReleased: false, identityMap }; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js index ac533b6d4..999210eb5 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js @@ -102,14 +102,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } @@ -597,6 +597,7 @@ export async function createInstantiator(options, swift) { /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; const makeFresh = (identityMap) => { const obj = Object.create(prototype); const state = { pointer, deinit, hasReleased: false, identityMap }; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js index 102ac6020..d9c31ed1d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js @@ -39,7 +39,7 @@ export async function createInstantiator(options, swift) { const state = { pointer, file, line, unregistered: false }; const real = (...args) => { if (state.unregistered) { - const bytes = new Uint8Array(memory.buffer, state.file); + const bytes = new Uint8Array(memory.buffer, state.file >>> 0); let length = 0; while (bytes[length] !== 0) { length += 1; } const fileID = decodeString(state.file, length); @@ -70,14 +70,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } @@ -383,6 +383,7 @@ export async function createInstantiator(options, swift) { /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; const makeFresh = (identityMap) => { const obj = Object.create(prototype); const state = { pointer, deinit, hasReleased: false, identityMap }; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js index 5257c9856..d626e9adf 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js @@ -89,14 +89,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } @@ -281,6 +281,7 @@ export async function createInstantiator(options, swift) { /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; const makeFresh = (identityMap) => { const obj = Object.create(prototype); const state = { pointer, deinit, hasReleased: false, identityMap }; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js index 91316a8c4..93f1e7ec7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js @@ -89,14 +89,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } @@ -281,6 +281,7 @@ export async function createInstantiator(options, swift) { /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; const makeFresh = (identityMap) => { const obj = Object.create(prototype); const state = { pointer, deinit, hasReleased: false, identityMap }; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js index f238551a9..edf069178 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js @@ -50,14 +50,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } @@ -242,6 +242,7 @@ export async function createInstantiator(options, swift) { /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; const makeFresh = (identityMap) => { const obj = Object.create(prototype); const state = { pointer, deinit, hasReleased: false, identityMap }; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js index c7f9b4955..64132a3c2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js @@ -50,14 +50,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } @@ -242,6 +242,7 @@ export async function createInstantiator(options, swift) { /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; const makeFresh = (identityMap) => { const obj = Object.create(prototype); const state = { pointer, deinit, hasReleased: false, identityMap }; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js index 994e1710a..2c3da5f26 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js @@ -46,14 +46,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js index 839e194cf..057bf9658 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js @@ -46,14 +46,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js index 5ee56f5bc..7f9fb8a20 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js @@ -46,14 +46,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } @@ -265,6 +265,7 @@ export async function createInstantiator(options, swift) { /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; const makeFresh = (identityMap) => { const obj = Object.create(prototype); const state = { pointer, deinit, hasReleased: false, identityMap }; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js index 4f0770092..f5912b3f5 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js @@ -158,7 +158,7 @@ export async function createInstantiator(options, swift) { const state = { pointer, file, line, unregistered: false }; const real = (...args) => { if (state.unregistered) { - const bytes = new Uint8Array(memory.buffer, state.file); + const bytes = new Uint8Array(memory.buffer, state.file >>> 0); let length = 0; while (bytes[length] !== 0) { length += 1; } const fileID = decodeString(state.file, length); @@ -262,14 +262,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } @@ -1352,6 +1352,7 @@ export async function createInstantiator(options, swift) { /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; const makeFresh = (identityMap) => { const obj = Object.create(prototype); const state = { pointer, deinit, hasReleased: false, identityMap }; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js index 0cc8fd287..d03915f87 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js @@ -128,7 +128,7 @@ export async function createInstantiator(options, swift) { const state = { pointer, file, line, unregistered: false }; const real = (...args) => { if (state.unregistered) { - const bytes = new Uint8Array(memory.buffer, state.file); + const bytes = new Uint8Array(memory.buffer, state.file >>> 0); let length = 0; while (bytes[length] !== 0) { length += 1; } const fileID = decodeString(state.file, length); @@ -160,14 +160,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js index aa523be20..b25010a23 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js @@ -258,14 +258,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } @@ -506,6 +506,7 @@ export async function createInstantiator(options, swift) { /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; const makeFresh = (identityMap) => { const obj = Object.create(prototype); const state = { pointer, deinit, hasReleased: false, identityMap }; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js index 44b7c5527..523861b9a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js @@ -57,14 +57,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.js index f07b00968..66d6494fd 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.js @@ -39,7 +39,7 @@ export async function createInstantiator(options, swift) { const state = { pointer, file, line, unregistered: false }; const real = (...args) => { if (state.unregistered) { - const bytes = new Uint8Array(memory.buffer, state.file); + const bytes = new Uint8Array(memory.buffer, state.file >>> 0); let length = 0; while (bytes[length] !== 0) { length += 1; } const fileID = decodeString(state.file, length); @@ -70,14 +70,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js index d1036cba4..6ff126525 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js @@ -45,14 +45,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js index 54276025b..457bfa973 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js @@ -62,14 +62,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js index 755165ee1..3c75771c5 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js @@ -46,14 +46,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } diff --git a/Runtime/src/index.ts b/Runtime/src/index.ts index 7d75a6801..879774a7d 100644 --- a/Runtime/src/index.ts +++ b/Runtime/src/index.ts @@ -450,31 +450,39 @@ export class SwiftRuntime { const memory = this.memory; const bytes = this.textEncoder.encode(memory.getObject(ref)); const bytes_ptr = memory.retain(bytes); - this.getDataView().setUint32(bytes_ptr_result, bytes_ptr, true); + this.getDataView().setUint32( + bytes_ptr_result >>> 0, + bytes_ptr, + true, + ); return bytes.length; }, swjs_decode_string: // NOTE: TextDecoder can't decode typed arrays backed by SharedArrayBuffer this.options.sharedMemory == true ? (bytes_ptr: pointer, length: number) => { + const bytesOffset = bytes_ptr >>> 0; + const byteLength = length >>> 0; const bytes = this.getUint8Array().slice( - bytes_ptr, - bytes_ptr + length, + bytesOffset, + bytesOffset + byteLength, ); const string = this.textDecoder.decode(bytes); return this.memory.retain(string); } : (bytes_ptr: pointer, length: number) => { + const bytesOffset = bytes_ptr >>> 0; + const byteLength = length >>> 0; const bytes = this.getUint8Array().subarray( - bytes_ptr, - bytes_ptr + length, + bytesOffset, + bytesOffset + byteLength, ); const string = this.textDecoder.decode(bytes); return this.memory.retain(string); }, swjs_load_string: (ref: ref, buffer: pointer) => { const bytes = this.memory.getObject(ref); - this.getUint8Array().set(bytes, buffer); + this.getUint8Array().set(bytes, buffer >>> 0); }, swjs_call_function: ( @@ -741,8 +749,8 @@ export class SwiftRuntime { } const array = new ArrayType( this.wasmMemory!.buffer, - elementsPtr, - length, + elementsPtr >>> 0, + length >>> 0, ); // Call `.slice()` to copy the memory return this.memory.retain(array.slice()); @@ -756,7 +764,7 @@ export class SwiftRuntime { const memory = this.memory; const typedArray = memory.getObject(ref); const bytes = new Uint8Array(typedArray.buffer); - this.getUint8Array().set(bytes, buffer); + this.getUint8Array().set(bytes, buffer >>> 0); }, swjs_release: (ref: ref) => { diff --git a/Runtime/src/js-value.ts b/Runtime/src/js-value.ts index b044e5cbe..407625bb4 100644 --- a/Runtime/src/js-value.ts +++ b/Runtime/src/js-value.ts @@ -60,14 +60,16 @@ export const decodeArray = ( memory: DataView, objectSpace: JSObjectSpace, ) => { + const basePtr = ptr >>> 0; + const count = length >>> 0; // fast path for empty array - if (length === 0) { + if (count === 0) { return []; } let result = []; - for (let index = 0; index < length; index++) { - const base = ptr + 16 * index; + for (let index = 0; index < count; index++) { + const base = basePtr + 16 * index; const kind = memory.getUint32(base, true); const payload1 = memory.getUint32(base + 4, true); const payload2 = memory.getFloat64(base + 8, true); @@ -97,7 +99,7 @@ export const write = ( memory, objectSpace, ); - memory.setUint32(kind_ptr, kind, true); + memory.setUint32(kind_ptr >>> 0, kind, true); }; export const writeAndReturnKindBits = ( @@ -109,23 +111,25 @@ export const writeAndReturnKindBits = ( objectSpace: JSObjectSpace, ): JavaScriptValueKindAndFlags => { const exceptionBit = (is_exception ? 1 : 0) << 31; + const payload1Offset = payload1_ptr >>> 0; + const payload2Offset = payload2_ptr >>> 0; if (value === null) { return exceptionBit | Kind.Null; } const writeRef = (kind: Kind) => { - memory.setUint32(payload1_ptr, objectSpace.retain(value), true); + memory.setUint32(payload1Offset, objectSpace.retain(value), true); return exceptionBit | kind; }; const type = typeof value; switch (type) { case "boolean": { - memory.setUint32(payload1_ptr, value ? 1 : 0, true); + memory.setUint32(payload1Offset, value ? 1 : 0, true); return exceptionBit | Kind.Boolean; } case "number": { - memory.setFloat64(payload2_ptr, value, true); + memory.setFloat64(payload2Offset, value, true); return exceptionBit | Kind.Number; } case "string": { @@ -157,9 +161,11 @@ export function decodeObjectRefs( length: number, memory: DataView, ): ref[] { - const result: ref[] = new Array(length); - for (let i = 0; i < length; i++) { - result[i] = memory.getUint32(ptr + 4 * i, true); + const basePtr = ptr >>> 0; + const count = length >>> 0; + const result: ref[] = new Array(count); + for (let i = 0; i < count; i++) { + result[i] = memory.getUint32(basePtr + 4 * i, true); } return result; } diff --git a/Runtime/test/pointer-normalization.test.ts b/Runtime/test/pointer-normalization.test.ts new file mode 100644 index 000000000..003bbdeb4 --- /dev/null +++ b/Runtime/test/pointer-normalization.test.ts @@ -0,0 +1,114 @@ +import { describe, expect, test } from "vitest"; +import { SwiftRuntime } from "../src/index.js"; +import { decodeArray, decodeObjectRefs, Kind, write } from "../src/js-value.js"; + +// A Wasm pointer is an `i32`. Once the linear memory grows past 2 GiB, valid +// addresses set the high bit and the guest passes them to JavaScript as *negative* +// numbers, which must be normalized with `>>> 0` before being used as memory +// offsets. These tests use a real >2 GiB `WebAssembly.Memory` and a real +// `SwiftRuntime`, exercising the actual code paths at such an address; without the +// normalization each one throws a `RangeError` on the negative offset. +const PAGE_SIZE = 64 * 1024; +const HIGH_OFFSET = 0x8000_0000; // 2 GiB, the first address with the high bit set +const SIGNED_POINTER = HIGH_OFFSET | 0; // how the guest passes that pointer: -2_147_483_648 +const MEMORY_PAGES = HIGH_OFFSET / PAGE_SIZE + 4; // a few pages past the offset + +function makeRuntime(): { runtime: SwiftRuntime; memory: WebAssembly.Memory } { + const memory = new WebAssembly.Memory({ initial: MEMORY_PAGES }); + const runtime = new SwiftRuntime(); + runtime.setInstance({ + exports: { + memory, + swjs_library_version: () => 708, + }, + } as unknown as WebAssembly.Instance); + return { runtime, memory }; +} + +describe("pointer normalization at >2 GiB addresses", () => { + test("swjs_decode_string reads from a high-bit pointer", () => { + const { runtime, memory } = makeRuntime(); + const bytes = new TextEncoder().encode("hello, 🌍"); + new Uint8Array(memory.buffer).set(bytes, HIGH_OFFSET); + + const imports = runtime.wasmImports as any; + const ref = imports.swjs_decode_string(SIGNED_POINTER, bytes.length); + + expect((runtime as any).memory.getObject(ref)).toBe("hello, 🌍"); + }); + + test("swjs_load_string writes to a high-bit pointer", () => { + const { runtime, memory } = makeRuntime(); + const bytes = new TextEncoder().encode("world"); + const ref = (runtime as any).memory.retain(bytes); + + const imports = runtime.wasmImports as any; + imports.swjs_load_string(ref, SIGNED_POINTER); + + const written = new Uint8Array(memory.buffer).slice( + HIGH_OFFSET, + HIGH_OFFSET + bytes.length, + ); + expect(new TextDecoder().decode(written)).toBe("world"); + }); + + test("swjs_create_typed_array copies from a high-bit pointer", () => { + const { runtime, memory } = makeRuntime(); + new Uint8Array(memory.buffer).set([1, 2, 3, 4], HIGH_OFFSET); + + const space = (runtime as any).memory; + const constructorRef = space.retain(Uint8Array); + const imports = runtime.wasmImports as any; + const ref = imports.swjs_create_typed_array( + constructorRef, + SIGNED_POINTER, + 4, + ); + + expect(Array.from(space.getObject(ref))).toEqual([1, 2, 3, 4]); + }); + + test("decodeArray reads JSValue elements from a high-bit pointer", () => { + const { runtime, memory } = makeRuntime(); + const dataView = new DataView(memory.buffer); + dataView.setUint32(HIGH_OFFSET, Kind.Number, true); + dataView.setUint32(HIGH_OFFSET + 4, 0, true); + dataView.setFloat64(HIGH_OFFSET + 8, 42.5, true); + + const values = decodeArray( + SIGNED_POINTER, + 1, + dataView, + (runtime as any).memory, + ); + + expect(values).toEqual([42.5]); + }); + + test("decodeObjectRefs reads refs from a high-bit pointer", () => { + const { memory } = makeRuntime(); + const dataView = new DataView(memory.buffer); + dataView.setUint32(HIGH_OFFSET, 11, true); + dataView.setUint32(HIGH_OFFSET + 4, 22, true); + + expect(decodeObjectRefs(SIGNED_POINTER, 2, dataView)).toEqual([11, 22]); + }); + + test("write stores a JSValue at high-bit pointers", () => { + const { runtime, memory } = makeRuntime(); + const dataView = new DataView(memory.buffer); + + write( + 42.5, + SIGNED_POINTER, + SIGNED_POINTER + 4, + SIGNED_POINTER + 8, + false, + dataView, + (runtime as any).memory, + ); + + expect(dataView.getUint32(HIGH_OFFSET, true)).toBe(Kind.Number); + expect(dataView.getFloat64(HIGH_OFFSET + 8, true)).toBe(42.5); + }); +}); diff --git a/package.json b/package.json index 509cddde2..866b2bb6f 100644 --- a/package.json +++ b/package.json @@ -14,6 +14,7 @@ "build:ts": "cd Runtime; rollup -c", "prepublishOnly": "npm run build", "format": "prettier --write Runtime/src", + "test:runtime": "vitest run Runtime/test", "check:bridgejs-dts": "tsc --project Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/tsconfig.json" }, "keywords": [ From 2fc75d460a7bf74ed259301dd54e34a363a6a392 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 22 Jun 2026 17:47:53 +0100 Subject: [PATCH 17/50] Bump actions/checkout from 6 to 7 (#770) Bumps [actions/checkout](https://github.com/actions/checkout) from 6 to 7. - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/v6...v7) --- updated-dependencies: - dependency-name: actions/checkout dependency-version: '7' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/test.yml | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 37e5bce78..1ce6ebe60 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -35,7 +35,7 @@ jobs: JAVASCRIPTKIT_WASI_BACKEND: ${{ matrix.entry.wasi-backend }} steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@v7 - name: Export matrix env if: ${{ matrix.entry.env != '' && matrix.entry.env != null }} run: | @@ -79,7 +79,7 @@ jobs: container: image: ${{ matrix.entry.image }} steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 - name: Setup Node.js uses: actions/setup-node@v6 with: @@ -105,7 +105,7 @@ jobs: xcode: Xcode_26.0.1 runs-on: ${{ matrix.os }} steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 - run: swift build --product BridgeJSTool env: DEVELOPER_DIR: /Applications/${{ matrix.xcode }}.app/Contents/Developer/ @@ -116,7 +116,7 @@ jobs: prettier: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 - uses: actions/setup-node@v6 with: node-version: '20' @@ -128,7 +128,7 @@ jobs: container: image: swift:6.3 steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 - run: ./Utilities/format.swift - name: Check for formatting changes run: | @@ -141,7 +141,7 @@ jobs: check-bridgejs-generated: runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 - uses: ./.github/actions/install-swift with: download-url: https://download.swift.org/development/ubuntu2204/swift-DEVELOPMENT-SNAPSHOT-2026-05-27-a/swift-DEVELOPMENT-SNAPSHOT-2026-05-27-a-ubuntu22.04.tar.gz @@ -158,7 +158,7 @@ jobs: build-examples: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 - uses: ./.github/actions/install-swift with: download-url: https://download.swift.org/development/ubuntu2204/swift-DEVELOPMENT-SNAPSHOT-2026-05-27-a/swift-DEVELOPMENT-SNAPSHOT-2026-05-27-a-ubuntu22.04.tar.gz From 3c520b0c5ee690f2d441ea78aa3f3758d6f818f3 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Tue, 23 Jun 2026 12:52:28 +0200 Subject: [PATCH 18/50] BridgeJS: Emit static members in declare global class declarations The `declare global { namespace ... }` class stub rendered every method without `static` and filtered properties to instance-only, so a `@JS static func` on a namespaced class was typed as an instance method and a `@JS static var` was omitted from the generated `.d.ts`. This was a type-only defect: the emitted JavaScript already exposes these members statically (and the class's namespace export entry types them correctly), so only TypeScript consumers were affected. Split static and instance members in this path: emit static methods with `static` and include static properties. This has been incorrect since the global namespace class stub was introduced, not a regression. The `Namespaces.Global` snapshot already exercises a namespaced class with `static func`/`static var` but had recorded the wrong output, so it is updated to the corrected declarations. --- .../BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift | 12 +++++++----- .../BridgeJSLinkTests/Namespaces.Global.d.ts | 3 ++- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index 8c9c20a14..01c390f26 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -3143,17 +3143,19 @@ extension BridgeJSLink { let sortedMethods = klass.methods.sorted { $0.name < $1.name } for method in sortedMethods { + let staticKeyword = method.effects.isStatic ? "static " : "" let methodSignature = - "\(method.name)\(renderTSSignatureCallback(method.parameters, method.returnType, method.effects));" + "\(staticKeyword)\(method.name)\(renderTSSignatureCallback(method.parameters, method.returnType, method.effects));" printer.write(methodSignature) } - let sortedProperties = klass.properties.filter { !$0.isStatic }.sorted { - $0.name < $1.name - } + let sortedProperties = klass.properties.sorted { $0.name < $1.name } for property in sortedProperties { + let staticKeyword = property.isStatic ? "static " : "" let readonly = property.isReadonly ? "readonly " : "" - printer.write("\(readonly)\(property.name): \(property.type.tsType);") + printer.write( + "\(staticKeyword)\(readonly)\(property.name): \(property.type.tsType);" + ) } printer.write("release(): void;") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.d.ts index 1353220bc..d9af0c8eb 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.d.ts @@ -34,7 +34,8 @@ declare global { class Greeter { constructor(name: string); greet(): string; - makeDefault(): Greeter; + static makeDefault(): Greeter; + static readonly defaultGreeting: string; release(): void; } class UUID { From 45088be53a11a96871a261e31bb753fe39bcddac Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Mon, 22 Jun 2026 17:24:51 +0200 Subject: [PATCH 19/50] BridgeJS: Include Swift doc comments in generated d.ts Propagate Swift `///` and `/** */` documentation on exported declarations into the generated TypeScript declarations as JSDoc, so editors surface hover docs for the bridged API. The exporter now captures the leading doc comment for functions, classes, methods, properties, constructors, structs, and enums into the skeleton, and the linker renders it as a single JSDoc block. The Swift DocC field list is mapped as the inverse of the TS2Swift importer: the leading description becomes the JSDoc body, `- Parameters:`/`- Parameter x:` become `@param`, `- Returns:` becomes `@returns`, and `- Throws:` becomes `@throws`. Existing default-value annotations are merged into the same block so a parameter never emits two comment blocks; declarations without doc comments produce byte-identical output to before. --- .../Generated/JavaScript/BridgeJS.json | 1 + .../BridgeJSCore/SwiftToSkeleton.swift | 84 +++- .../Sources/BridgeJSLink/BridgeJSLink.swift | 297 ++++++++++-- .../BridgeJSSkeleton/BridgeJSSkeleton.swift | 45 +- .../Inputs/MacroSwift/DocComments.swift | 91 ++++ .../Inputs/MacroSwift/Namespaces.swift | 5 + .../BridgeJSCodegenTests/DocComments.json | 436 ++++++++++++++++++ .../BridgeJSCodegenTests/DocComments.swift | 317 +++++++++++++ .../Namespaces.Global.json | 3 + .../BridgeJSCodegenTests/Namespaces.json | 3 + .../BridgeJSLinkTests/DocComments.d.ts | 140 ++++++ .../BridgeJSLinkTests/DocComments.js | 421 +++++++++++++++++ .../BridgeJSLinkTests/Namespaces.Global.d.ts | 22 + .../BridgeJSLinkTests/Namespaces.d.ts | 11 + 14 files changed, 1808 insertions(+), 68 deletions(-) create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/DocComments.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DocComments.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DocComments.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.d.ts create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.js diff --git a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/JavaScript/BridgeJS.json b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/JavaScript/BridgeJS.json index 6f1fc940c..c4a3a8c9d 100644 --- a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/JavaScript/BridgeJS.json +++ b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/JavaScript/BridgeJS.json @@ -16,6 +16,7 @@ "methods" : [ { "abiName" : "bjs_PlayBridgeJS_updateDetailed", + "documentation" : "Structured entry point used by the playground so JS doesn't need to parse diagnostics.", "effects" : { "isAsync" : false, "isStatic" : false, diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index a6afe2779..ed7ebcd1b 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -1266,10 +1266,56 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { returnType: returnType, effects: effects, namespace: finalNamespace, - staticContext: staticContext + staticContext: staticContext, + documentation: extractDocumentation(from: node) ) } + /// Returns the doc comment (`///` or `/** */`) attached to a declaration, with + /// markers stripped and DocC field lists (`- Parameters:`, `- Returns:`) preserved. + private func extractDocumentation(from node: some SyntaxProtocol) -> String? { + var run: [String] = [] + for piece in node.leadingTrivia { + switch piece { + case .docLineComment(let text): + var line = Substring(text) + if line.hasPrefix("///") { line = line.dropFirst(3) } + if line.first == " " { line = line.dropFirst() } + if line.last == "\r" { line = line.dropLast() } + run.append(String(line)) + case .docBlockComment(let text): + run.append(contentsOf: stripBlockComment(text)) + case .newlines(let count), .carriageReturns(let count), .carriageReturnLineFeeds(let count): + if count >= 2 { run.removeAll() } + case .lineComment, .blockComment: + run.removeAll() + default: + continue + } + } + // Trim boundary blank lines so line (`///`) and block (`/** */`) comments + // produce a consistent skeleton value. + while run.first?.trimmingCharacters(in: .whitespaces).isEmpty == true { run.removeFirst() } + while run.last?.trimmingCharacters(in: .whitespaces).isEmpty == true { run.removeLast() } + return run.isEmpty ? nil : run.joined(separator: "\n") + } + + private func stripBlockComment(_ text: String) -> [String] { + var body = Substring(text) + if body.hasPrefix("/**") { body = body.dropFirst(3) } + if body.hasSuffix("*/") { body = body.dropLast(2) } + return body.split(separator: "\n", omittingEmptySubsequences: false).map { raw -> String in + var line = raw[...] + if line.last == "\r" { line = line.dropLast() } + while let first = line.first, first == " " || first == "\t" { line = line.dropFirst() } + if line.first == "*" { + line = line.dropFirst() + if line.first == " " { line = line.dropFirst() } + } + return String(line) + } + } + private func collectEffects(signature: FunctionSignatureSyntax, isStatic: Bool = false) -> Effects? { let isAsync = signature.effectSpecifiers?.asyncSpecifier != nil var isThrows = false @@ -1360,7 +1406,8 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { let constructor = ExportedConstructor( abiName: "bjs_\(classAbiName)_init", parameters: parameters, - effects: effects + effects: effects, + documentation: extractDocumentation(from: node) ) exportedClassByName[classKey]?.constructor = constructor @@ -1383,7 +1430,8 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { let constructor = ExportedConstructor( abiName: "bjs_\(structAbiName)_init", parameters: parameters, - effects: effects + effects: effects, + documentation: extractDocumentation(from: node) ) exportedStructByName[structKey]?.constructor = constructor @@ -1490,7 +1538,8 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { isReadonly: isReadonly, isStatic: isStatic, namespace: finalNamespace, - staticContext: staticContext + staticContext: staticContext, + documentation: extractDocumentation(from: node) ) if case .enumBody(_, let key) = state { @@ -1537,7 +1586,8 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { methods: [], properties: [], namespace: effectiveNamespace, - identityMode: classIdentityMode + identityMode: classIdentityMode, + documentation: extractDocumentation(from: node) ) let uniqueKey = makeKey(name: name, namespace: effectiveNamespace) @@ -1657,7 +1707,8 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { namespace: effectiveNamespace, emitStyle: emitStyle, staticMethods: [], - staticProperties: [] + staticProperties: [], + documentation: extractDocumentation(from: node) ) let enumUniqueKey = makeKey(name: name, namespace: effectiveNamespace) @@ -1774,7 +1825,8 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { name: name, methods: [], properties: [], - namespace: effectiveNamespace + namespace: effectiveNamespace, + documentation: extractDocumentation(from: node) ) stateStack.push(state: .protocolBody(name: name, key: protocolUniqueKey)) @@ -1798,7 +1850,8 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { name: name, methods: methods, properties: exportedProtocolByName[protocolUniqueKey]?.properties ?? [], - namespace: effectiveNamespace + namespace: effectiveNamespace, + documentation: extractDocumentation(from: node) ) exportedProtocolByName[protocolUniqueKey] = exportedProtocol @@ -1874,7 +1927,8 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { isReadonly: true, isStatic: false, namespace: effectiveNamespace, - staticContext: nil + staticContext: nil, + documentation: extractDocumentation(from: varDecl) ) properties.append(property) } @@ -1888,7 +1942,8 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { explicitAccessControl: explicitAccessControl, properties: properties, methods: [], - namespace: effectiveNamespace + namespace: effectiveNamespace, + documentation: extractDocumentation(from: node) ) exportedStructByName[structUniqueKey] = exportedStruct @@ -1981,7 +2036,8 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { returnType: returnType, effects: effects, namespace: namespace, - staticContext: nil + staticContext: nil, + documentation: extractDocumentation(from: node) ) } @@ -2022,7 +2078,8 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { let exportedProperty = ExportedProtocolProperty( name: propertyName, type: propertyType, - isReadonly: isReadonly + isReadonly: isReadonly, + documentation: extractDocumentation(from: node) ) if var currentProtocol = exportedProtocolByName[protocolKey] { @@ -2033,7 +2090,8 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { name: currentProtocol.name, methods: currentProtocol.methods, properties: properties, - namespace: currentProtocol.namespace + namespace: currentProtocol.namespace, + documentation: currentProtocol.documentation ) exportedProtocolByName[protocolKey] = currentProtocol } diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index 01c390f26..a24fde09b 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -936,14 +936,19 @@ public struct BridgeJSLink { for skeleton in exportedSkeletons { for proto in skeleton.protocols { + printer.write(lines: renderJSDoc(documentation: proto.documentation, parameters: [])) printer.write("export interface \(proto.name) {") printer.indent { for method in proto.methods { + printer.write( + lines: renderJSDoc(documentation: method.documentation, parameters: method.parameters) + ) printer.write( "\(method.name)\(renderTSSignature(parameters: method.parameters, returnType: method.returnType, effects: method.effects));" ) } for property in proto.properties { + printer.write(lines: renderJSDoc(documentation: property.documentation, parameters: [])) let propertySignature = property.isReadonly ? "readonly \(property.name): \(resolveTypeScriptType(property.type));" @@ -977,12 +982,19 @@ public struct BridgeJSLink { printer.write("export type \(enumObjectName) = typeof \(fullEnumValuesPath) & {") printer.indent { for function in enumDefinition.staticMethods { + printer.write( + lines: renderJSDoc( + documentation: function.documentation, + parameters: function.parameters + ) + ) printer.write( "\(function.name)\(renderTSSignature(parameters: function.parameters, returnType: function.returnType, effects: function.effects));" ) } for property in enumDefinition.staticProperties { let readonly = property.isReadonly ? "readonly " : "" + printer.write(lines: renderJSDoc(documentation: property.documentation, parameters: [])) printer.write("\(readonly)\(property.name): \(resolveTypeScriptType(property.type));") } } @@ -999,6 +1011,9 @@ public struct BridgeJSLink { exportedSkeletons: exportedSkeletons, renderTSSignatureCallback: { parameters, returnType, effects in self.renderTSSignature(parameters: parameters, returnType: returnType, effects: effects) + }, + renderDocCallback: { documentation, parameters in + self.renderJSDoc(documentation: documentation, parameters: parameters) } ) printer.write(lines: namespaceDeclarationsLines) @@ -1014,8 +1029,16 @@ public struct BridgeJSLink { renderClassEntry: { klass in data.namespacedClassDtsExportEntries[klass.name] ?? [] }, - renderFunctionSignature: { function in - "\(function.name)\(self.renderTSSignature(parameters: function.parameters, returnType: function.returnType, effects: function.effects));" + renderFunctionEntry: { function in + self.renderJSDoc(documentation: function.documentation, parameters: function.parameters) + + [ + "\(function.name)\(self.renderTSSignature(parameters: function.parameters, returnType: function.returnType, effects: function.effects));" + ] + }, + renderPropertyEntry: { property in + let readonly = property.isReadonly ? "readonly " : "" + return self.renderJSDoc(documentation: property.documentation, parameters: []) + + ["\(readonly)\(property.name): \(property.type.tsType);"] } ) printer.write("export type Exports = {") @@ -1574,12 +1597,6 @@ public struct BridgeJSLink { .replacingOccurrences(of: "\"", with: "\\\"") } - /// Helper method to append JSDoc comments for parameters with default values - private func appendJSDocIfNeeded(for parameters: [Parameter], to lines: inout [String]) { - let jsDocLines = DefaultValueUtils.formatJSDoc(for: parameters) - lines.append(contentsOf: jsDocLines) - } - func renderExportedStruct( _ structDefinition: ExportedStruct ) throws -> (js: [String], dtsType: [String], dtsExportEntry: [String]) { @@ -1589,15 +1606,24 @@ public struct BridgeJSLink { let staticProperties = structDefinition.properties.filter { $0.isStatic } let dtsTypePrinter = CodeFragmentPrinter() + for line in renderJSDoc(documentation: structDefinition.documentation, parameters: []) { + dtsTypePrinter.write(line) + } dtsTypePrinter.write("export interface \(structName) {") let instanceProps = structDefinition.properties.filter { !$0.isStatic } dtsTypePrinter.indent { for property in instanceProps { let tsType = resolveTypeScriptType(property.type) + for line in renderJSDoc(documentation: property.documentation, parameters: []) { + dtsTypePrinter.write(line) + } dtsTypePrinter.write("\(property.name): \(tsType);") } for method in structDefinition.methods where !method.effects.isStatic { - let jsDocLines = DefaultValueUtils.formatJSDoc(for: method.parameters) + let jsDocLines = renderJSDoc( + documentation: method.documentation, + parameters: method.parameters + ) dtsTypePrinter.write(lines: jsDocLines) let signature = renderTSSignature( parameters: method.parameters, @@ -1659,7 +1685,10 @@ public struct BridgeJSLink { dtsExportEntryPrinter.write("\(structName): {") dtsExportEntryPrinter.indent { if let constructor = structDefinition.constructor { - let jsDocLines = DefaultValueUtils.formatJSDoc(for: constructor.parameters) + let jsDocLines = renderJSDoc( + documentation: constructor.documentation, + parameters: constructor.parameters + ) dtsExportEntryPrinter.write(lines: jsDocLines) dtsExportEntryPrinter.write( "init\(renderTSSignature(parameters: constructor.parameters, returnType: .swiftStruct(structDefinition.swiftCallName), effects: constructor.effects));" @@ -1667,10 +1696,16 @@ public struct BridgeJSLink { } for property in staticProperties { let readonly = property.isReadonly ? "readonly " : "" + for line in renderJSDoc(documentation: property.documentation, parameters: []) { + dtsExportEntryPrinter.write(line) + } dtsExportEntryPrinter.write("\(readonly)\(property.name): \(resolveTypeScriptType(property.type));") } for method in staticMethods { - let jsDocLines = DefaultValueUtils.formatJSDoc(for: method.parameters) + let jsDocLines = renderJSDoc( + documentation: method.documentation, + parameters: method.parameters + ) dtsExportEntryPrinter.write(lines: jsDocLines) dtsExportEntryPrinter.write( "\(method.name)\(renderTSSignature(parameters: method.parameters, returnType: method.returnType, effects: method.effects));" @@ -1770,6 +1805,10 @@ public struct BridgeJSLink { let printer = CodeFragmentPrinter() let enumValuesName = enumDefinition.valuesName + for line in renderJSDoc(documentation: enumDefinition.documentation, parameters: []) { + printer.write(line) + } + switch enumDefinition.emitStyle { case .tsEnum: switch enumDefinition.enumType { @@ -1883,7 +1922,7 @@ extension BridgeJSLink { ) var dtsLines: [String] = [] - appendJSDocIfNeeded(for: function.parameters, to: &dtsLines) + dtsLines.append(contentsOf: renderJSDoc(documentation: function.documentation, parameters: function.parameters)) dtsLines.append( "\(function.name)\(renderTSSignature(parameters: function.parameters, returnType: function.returnType, effects: function.effects));" @@ -1935,7 +1974,7 @@ extension BridgeJSLink { var dtsLines: [String] = [] - appendJSDocIfNeeded(for: function.parameters, to: &dtsLines) + dtsLines.append(contentsOf: renderJSDoc(documentation: function.documentation, parameters: function.parameters)) dtsLines.append( "static \(function.name)\(renderTSSignature(parameters: function.parameters, returnType: function.returnType, effects: function.effects));" @@ -1966,7 +2005,7 @@ extension BridgeJSLink { var dtsLines: [String] = [] - appendJSDocIfNeeded(for: function.parameters, to: &dtsLines) + dtsLines.append(contentsOf: renderJSDoc(documentation: function.documentation, parameters: function.parameters)) dtsLines.append( "\(function.name)\(renderTSSignature(parameters: function.parameters, returnType: function.returnType, effects: function.effects));" @@ -2082,6 +2121,9 @@ extension BridgeJSLink { let dtsTypePrinter = CodeFragmentPrinter() let dtsExportEntryPrinter = CodeFragmentPrinter() + for line in renderJSDoc(documentation: klass.documentation, parameters: []) { + dtsTypePrinter.write(line) + } dtsTypePrinter.write("export interface \(klass.name) extends SwiftHeapObject {") dtsExportEntryPrinter.write("\(klass.name): {") jsPrinter.write("class \(klass.name) extends SwiftHeapObject {") @@ -2134,7 +2176,10 @@ extension BridgeJSLink { } dtsExportEntryPrinter.indent { - let jsDocLines = DefaultValueUtils.formatJSDoc(for: constructor.parameters) + let jsDocLines = renderJSDoc( + documentation: constructor.documentation, + parameters: constructor.parameters + ) for line in jsDocLines { dtsExportEntryPrinter.write(line) } @@ -2167,6 +2212,12 @@ extension BridgeJSLink { } dtsExportEntryPrinter.indent { + for line in renderJSDoc( + documentation: method.documentation, + parameters: method.parameters + ) { + dtsExportEntryPrinter.write(line) + } dtsExportEntryPrinter.write( "\(method.name)\(renderTSSignature(parameters: method.parameters, returnType: method.returnType, effects: method.effects));" ) @@ -2194,6 +2245,12 @@ extension BridgeJSLink { } dtsTypePrinter.indent { + for line in renderJSDoc( + documentation: method.documentation, + parameters: method.parameters + ) { + dtsTypePrinter.write(line) + } dtsTypePrinter.write( "\(method.name)\(renderTSSignature(parameters: method.parameters, returnType: method.returnType, effects: method.effects));" ) @@ -2281,6 +2338,9 @@ extension BridgeJSLink { // Add instance property to TypeScript interface definition let readonly = property.isReadonly ? "readonly " : "" dtsPrinter.indent { + for line in renderJSDoc(documentation: property.documentation, parameters: []) { + dtsPrinter.write(line) + } dtsPrinter.write("\(readonly)\(property.name): \(property.type.tsType);") } } @@ -2708,6 +2768,7 @@ extension BridgeJSLink { var functionDtsLines: [(name: String, lines: [String])] = [] var classDtsLines: [(name: String, lines: [String])] = [] var enumDtsLines: [(name: String, line: String)] = [] + var staticPropertyDtsLines: [(name: String, lines: [String])] = [] var propertyJsLines: [String] = [] } @@ -2791,7 +2852,8 @@ extension BridgeJSLink { fileprivate func buildHierarchicalExportsType( exportedSkeletons: [ExportedSkeleton], renderClassEntry: (ExportedClass) -> [String], - renderFunctionSignature: (ExportedFunction) -> String + renderFunctionEntry: (ExportedFunction) -> [String], + renderPropertyEntry: (ExportedProperty) -> [String] ) -> [String] { let printer = CodeFragmentPrinter() let rootNode = NamespaceNode(name: "") @@ -2802,7 +2864,8 @@ extension BridgeJSLink { populateTypeScriptExportLines( node: node, renderClassEntry: renderClassEntry, - renderFunctionSignature: renderFunctionSignature + renderFunctionEntry: renderFunctionEntry, + renderPropertyEntry: renderPropertyEntry ) } @@ -2814,11 +2877,11 @@ extension BridgeJSLink { private func populateTypeScriptExportLines( node: NamespaceNode, renderClassEntry: (ExportedClass) -> [String], - renderFunctionSignature: (ExportedFunction) -> String + renderFunctionEntry: (ExportedFunction) -> [String], + renderPropertyEntry: (ExportedProperty) -> [String] ) { for function in node.content.functions { - let signature = renderFunctionSignature(function) - node.content.functionDtsLines.append((function.name, [signature])) + node.content.functionDtsLines.append((function.name, renderFunctionEntry(function))) } for klass in node.content.classes { @@ -2826,6 +2889,10 @@ extension BridgeJSLink { node.content.classDtsLines.append((klass.name, entry)) } + for property in node.content.staticProperties { + node.content.staticPropertyDtsLines.append((property.name, renderPropertyEntry(property))) + } + for enumDef in node.content.enums { node.content.enumDtsLines.append((enumDef.name, "\(enumDef.name): \(enumDef.objectTypeName)")) } @@ -2834,7 +2901,8 @@ extension BridgeJSLink { populateTypeScriptExportLines( node: childNode, renderClassEntry: renderClassEntry, - renderFunctionSignature: renderFunctionSignature + renderFunctionEntry: renderFunctionEntry, + renderPropertyEntry: renderPropertyEntry ) } } @@ -2962,9 +3030,8 @@ extension BridgeJSLink { printer.write(line) } - for property in childNode.content.staticProperties.sorted(by: { $0.name < $1.name }) { - let readonly = property.isReadonly ? "readonly " : "" - printer.write("\(readonly)\(property.name): \(property.type.tsType);") + for (_, lines) in childNode.content.staticPropertyDtsLines.sorted(by: { $0.name < $1.name }) { + printer.write(lines: lines) } for (_, lines) in childNode.content.functionDtsLines.sorted(by: { $0.name < $1.name }) { @@ -3030,7 +3097,8 @@ extension BridgeJSLink { /// - Returns: Array of TypeScript declaration lines defining the global namespace structure func namespaceDeclarations( exportedSkeletons: [ExportedSkeleton], - renderTSSignatureCallback: @escaping ([Parameter], BridgeType, Effects) -> String + renderTSSignatureCallback: @escaping ([Parameter], BridgeType, Effects) -> String, + renderDocCallback: @escaping (String?, [Parameter]) -> [String] ) -> [String] { let printer = CodeFragmentPrinter() @@ -3052,7 +3120,8 @@ extension BridgeJSLink { printer: printer, exposeToGlobal: true, exportedSkeletons: exportedSkeletons, - renderTSSignatureCallback: renderTSSignatureCallback + renderTSSignatureCallback: renderTSSignatureCallback, + renderDocCallback: renderDocCallback ) printer.unindent() printer.write("}") @@ -3071,7 +3140,8 @@ extension BridgeJSLink { printer: printer, exposeToGlobal: false, exportedSkeletons: exportedSkeletons, - renderTSSignatureCallback: renderTSSignatureCallback + renderTSSignatureCallback: renderTSSignatureCallback, + renderDocCallback: renderDocCallback ) } } @@ -3085,7 +3155,8 @@ extension BridgeJSLink { printer: CodeFragmentPrinter, exposeToGlobal: Bool, exportedSkeletons: [ExportedSkeleton], - renderTSSignatureCallback: @escaping ([Parameter], BridgeType, Effects) -> String + renderTSSignatureCallback: @escaping ([Parameter], BridgeType, Effects) -> String, + renderDocCallback: @escaping (String?, [Parameter]) -> [String] ) { func hasContent(node: NamespaceNode) -> Bool { // Enums and structs are always included @@ -3129,6 +3200,7 @@ extension BridgeJSLink { if exposeToGlobal { let sortedClasses = childNode.content.classes.sorted { $0.name < $1.name } for klass in sortedClasses { + printer.write(lines: renderDocCallback(klass.documentation, [])) printer.write("class \(klass.name) {") printer.indent { if let constructor = klass.constructor { @@ -3138,6 +3210,9 @@ extension BridgeJSLink { } let constructorSignature = "constructor(\(paramSignatures.joined(separator: ", ")));" + printer.write( + lines: renderDocCallback(constructor.documentation, constructor.parameters) + ) printer.write(constructorSignature) } @@ -3146,6 +3221,7 @@ extension BridgeJSLink { let staticKeyword = method.effects.isStatic ? "static " : "" let methodSignature = "\(staticKeyword)\(method.name)\(renderTSSignatureCallback(method.parameters, method.returnType, method.effects));" + printer.write(lines: renderDocCallback(method.documentation, method.parameters)) printer.write(methodSignature) } @@ -3153,6 +3229,7 @@ extension BridgeJSLink { for property in sortedProperties { let staticKeyword = property.isStatic ? "static " : "" let readonly = property.isReadonly ? "readonly " : "" + printer.write(lines: renderDocCallback(property.documentation, [])) printer.write( "\(staticKeyword)\(readonly)\(property.name): \(property.type.tsType);" ) @@ -3167,6 +3244,7 @@ extension BridgeJSLink { // Generate enum definitions within declare global namespace let sortedEnums = childNode.content.enums.sorted { $0.name < $1.name } for enumDefinition in sortedEnums { + printer.write(lines: renderDocCallback(enumDefinition.documentation, [])) let style: EnumEmitStyle = enumDefinition.emitStyle let enumValuesName = enumDefinition.valuesName switch enumDefinition.enumType { @@ -3275,6 +3353,7 @@ extension BridgeJSLink { let sortedStructs = childNode.content.structs.sorted { $0.name < $1.name } for structDef in sortedStructs { let instanceProps = structDef.properties.filter { !$0.isStatic } + printer.write(lines: renderDocCallback(structDef.documentation, [])) printer.write("export interface \(structDef.name) {") printer.indent { for property in instanceProps { @@ -3282,6 +3361,7 @@ extension BridgeJSLink { property.type, exportedSkeletons: exportedSkeletons ) + printer.write(lines: renderDocCallback(property.documentation, [])) printer.write("\(property.name): \(tsType);") } } @@ -3294,11 +3374,13 @@ extension BridgeJSLink { for function in sortedFunctions { let signature = "function \(function.name)\(renderTSSignatureCallback(function.parameters, function.returnType, function.effects));" + printer.write(lines: renderDocCallback(function.documentation, function.parameters)) printer.write(signature) } let sortedProperties = childNode.content.staticProperties.sorted { $0.name < $1.name } for property in sortedProperties { let readonly = property.isReadonly ? "var " : "let " + printer.write(lines: renderDocCallback(property.documentation, [])) printer.write("\(readonly)\(property.name): \(property.type.tsType);") } } @@ -3309,7 +3391,8 @@ extension BridgeJSLink { printer: printer, exposeToGlobal: exposeToGlobal, exportedSkeletons: exportedSkeletons, - renderTSSignatureCallback: renderTSSignatureCallback + renderTSSignatureCallback: renderTSSignatureCallback, + renderDocCallback: renderDocCallback ) printer.unindent() @@ -3668,24 +3751,6 @@ enum DefaultValueUtils { .replacingOccurrences(of: "\"", with: "\\\"") } - /// Generates JSDoc comment lines for parameters with default values - static func formatJSDoc(for parameters: [Parameter]) -> [String] { - let paramsWithDefaults = parameters.filter { $0.hasDefault } - guard !paramsWithDefaults.isEmpty else { - return [] - } - - var jsDocLines: [String] = ["/**"] - for param in paramsWithDefaults { - if let defaultValue = param.defaultValue { - let defaultDoc = format(defaultValue, as: .typescript) - jsDocLines.append(" * @param \(param.name) - Optional parameter (default: \(defaultDoc))") - } - } - jsDocLines.append(" */") - return jsDocLines - } - /// Generates a JavaScript parameter list with default values static func formatParameterList(_ parameters: [Parameter]) -> String { return parameters.map { param in @@ -3698,6 +3763,144 @@ enum DefaultValueUtils { } } +extension BridgeJSLink { + /// Renders the JSDoc block for an exported declaration, mapping the Swift DocC + /// comment to `@param`/`@returns`/`@throws` and merging any default-value notes. + /// Returns an empty array when there is nothing to document. + fileprivate func renderJSDoc(documentation: String?, parameters: [Parameter]) -> [String] { + let parsed = documentation.map(DocCComment.init(parsing:)) ?? DocCComment() + + var tagLines: [String] = [] + for parameter in parameters { + let docText = parsed.parameter(named: parameter.name) + let defaultValue = parameter.defaultValue.map { DefaultValueUtils.format($0, as: .typescript) } + switch (docText, defaultValue) { + case let (.some(text), .some(value)): + tagLines.append("@param \(parameter.name) \(text) (default: \(value))") + case let (.some(text), .none): + tagLines.append("@param \(parameter.name) \(text)") + case let (.none, .some(value)): + tagLines.append("@param \(parameter.name) - Optional parameter (default: \(value))") + case (.none, .none): + continue + } + } + if let returns = parsed.returns { + tagLines.append(returns.isEmpty ? "@returns" : "@returns \(returns)") + } + if let thrown = parsed.throws { + tagLines.append(thrown.isEmpty ? "@throws" : "@throws \(thrown)") + } + + guard !parsed.description.isEmpty || !tagLines.isEmpty else { return [] } + + // `*/` in the doc text would prematurely close the JSDoc block comment. + func escape(_ text: String) -> String { text.replacingOccurrences(of: "*/", with: "*\\/") } + + var lines: [String] = ["/**"] + lines.append(contentsOf: parsed.description.map { $0.isEmpty ? " *" : " * \(escape($0))" }) + lines.append(contentsOf: tagLines.map { " * \(escape($0))" }) + lines.append(" */") + return lines + } +} + +/// A parsed Swift DocC comment: a description block plus its `- Parameters:`, +/// `- Returns:`, and `- Throws:` field items. +private struct DocCComment { + var description: [String] = [] + var parameters: [(name: String, text: String)] = [] + var returns: String? + var `throws`: String? + + init() {} + + init(parsing text: String) { + enum Target { case description, parameter(Int), returns, `throws`, none } + var target: Target = .description + + func append(continuation line: String) { + let trimmed = line.trimmingCharacters(in: .whitespaces) + switch target { + case .description: description.append(line) + case .parameter(let index) where !trimmed.isEmpty: parameters[index].text += " \(trimmed)" + case .returns where !trimmed.isEmpty: returns = [returns, trimmed].compactMap { $0 }.joined(separator: " ") + case .throws where !trimmed.isEmpty: + `throws` = [`throws`, trimmed].compactMap { $0 }.joined(separator: " ") + default: return + } + } + + func addParameter(_ name: String, _ desc: String) { + parameters.append((name: name, text: desc)) + target = .parameter(parameters.count - 1) + } + + func isInParameterList(_ target: Target) -> Bool { + switch target { + case .none, .parameter: return true + default: return false + } + } + + for rawLine in text.split(separator: "\n", omittingEmptySubsequences: false).map(String.init) { + let trimmed = rawLine.trimmingCharacters(in: .whitespaces) + if trimmed == "- Parameters:" { + target = .none + } else if let (name, desc) = Self.listItem(trimmed, keyword: "Parameter") { + addParameter(name, desc) + } else if let desc = Self.field(trimmed, keyword: "Returns") { + returns = desc + target = .returns + } else if let desc = Self.field(trimmed, keyword: "Throws") { + `throws` = desc + target = .throws + } else if isInParameterList(target), let (name, desc) = Self.bareItem(trimmed) { + addParameter(name, desc) + } else { + append(continuation: rawLine) + } + } + + while description.first?.trimmingCharacters(in: .whitespaces).isEmpty == true { description.removeFirst() } + while description.last?.trimmingCharacters(in: .whitespaces).isEmpty == true { description.removeLast() } + } + + func parameter(named name: String) -> String? { + parameters.first { $0.name == name }?.text + } + + /// Matches `- Keyword name: description`. + private static func listItem(_ line: String, keyword: String) -> (String, String)? { + guard line.hasPrefix("- \(keyword) ") else { return nil } + return splitNameAndDescription(String(line.dropFirst("- \(keyword) ".count))) + } + + /// Matches `- name: description` (a sub-item of a `- Parameters:` block). + private static func bareItem(_ line: String) -> (String, String)? { + guard line.hasPrefix("- ") else { return nil } + guard let (name, desc) = splitNameAndDescription(String(line.dropFirst(2))), !name.contains(" ") else { + return nil + } + return (name, desc) + } + + /// Matches `- Keyword: description`, returning the (possibly empty) description. + private static func field(_ line: String, keyword: String) -> String? { + if line.hasPrefix("- \(keyword): ") { + return String(line.dropFirst("- \(keyword): ".count)).trimmingCharacters(in: .whitespaces) + } + return line == "- \(keyword):" ? "" : nil + } + + private static func splitNameAndDescription(_ rest: String) -> (String, String)? { + guard let colon = rest.firstIndex(of: ":") else { return nil } + let name = String(rest[.. String { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/DocComments.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/DocComments.swift new file mode 100644 index 000000000..8cdc72d4d --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/DocComments.swift @@ -0,0 +1,91 @@ +/// Returns a greeting for a user. +/// - Parameters: +/// - name: The user's name. +/// - greeting: The greeting word to use. +/// - Returns: The composed greeting message. +@JS func greet(name: String, greeting: String = "Hello") -> String { + return "\(greeting), \(name)!" +} + +/// Adds two numbers together. +/// - Parameter a: The first addend. +/// - Parameter b: The second addend. +/// - Returns: The sum of the inputs. +@JS func add(a: Int, b: Int) -> Int { a + b } + +/// +/// Has blank doc lines around the summary; boundaries should be trimmed. +/// +@JS func trimmed() {} + +/** + * Says hello to the world. + * + * Demonstrates that block doc comments are supported too. + */ +@JS func hello() {} + +/// Parses an integer from text. +/// - Parameter text: The text to parse. +/// - Returns: The parsed integer. +/// - Throws: A `JSException` when the text is not a valid integer. +@JS func parseInt(text: String) throws(JSException) -> Int { 0 } + +/// A greeter that keeps the target name. +@JS class Greeter { + /// The configured name. + @JS var name: String + + /// Create a greeter. + /// - Parameter name: The name to greet. + @JS init(name: String) { + self.name = name + } + + /// Returns a greeting for the configured name. + /// - Returns: The greeting message. + @JS func greet() -> String { + return "Hello, " + self.name + "!" + } +} + +/// A 2D point in space. +@JS struct Point { + /// The horizontal position. + let x: Double + /// The vertical position. + let y: Double +} + +/// A primary color channel. +@JS enum Color { + case red + case green + case blue + + /// The default channel. + @JS static var fallback: String { "red" } + + /// Returns the canonical name for a channel label. + /// - Parameter label: The raw label. + /// - Returns: The canonical channel name. + @JS static func canonical(label: String) -> String { label } +} + +/// Receives lifecycle callbacks. +@JS protocol Listener { + /// The listener's display name. + var name: String { get } + + /// Called when an event fires. + /// - Parameter id: The event identifier. + func onEvent(id: Int) +} + +/// Doubles a value, in a namespace. +/// - Parameter value: The value to double. +/// - Returns: Twice the input. +@JS(namespace: "MathUtils") func double(value: Int) -> Int { value * 2 } + +/// Returns the JSDoc terminator */ embedded mid-sentence. +@JS func terminator() -> String { "*/" } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Namespaces.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Namespaces.swift index 7cd63c698..7ad3037b9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Namespaces.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Namespaces.swift @@ -1,7 +1,10 @@ @JS func plainFunction() -> String { "plain" } +/// A namespaced free function. +/// - Returns: A fixed namespaced string. @JS(namespace: "MyModule.Utils") func namespacedFunction() -> String { "namespaced" } +/// A greeter living in a namespace. @JS(namespace: "__Swift.Foundation") class Greeter { var name: String @@ -9,6 +12,8 @@ self.name = name } + /// Produces a greeting for the configured name. + /// - Returns: The greeting message. @JS func greet() -> String { return "Hello, " + self.name + "!" } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DocComments.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DocComments.json new file mode 100644 index 000000000..c69fca509 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DocComments.json @@ -0,0 +1,436 @@ +{ + "exported" : { + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_Greeter_init", + "documentation" : "Create a greeter.\n- Parameter name: The name to greet.", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "name", + "name" : "name", + "type" : { + "string" : { + + } + } + } + ] + }, + "documentation" : "A greeter that keeps the target name.", + "methods" : [ + { + "abiName" : "bjs_Greeter_greet", + "documentation" : "Returns a greeting for the configured name.\n- Returns: The greeting message.", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "greet", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "name" : "Greeter", + "properties" : [ + { + "documentation" : "The configured name.", + "isReadonly" : false, + "isStatic" : false, + "name" : "name", + "type" : { + "string" : { + + } + } + } + ], + "swiftCallName" : "Greeter" + } + ], + "enums" : [ + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "red" + }, + { + "associatedValues" : [ + + ], + "name" : "green" + }, + { + "associatedValues" : [ + + ], + "name" : "blue" + } + ], + "documentation" : "A primary color channel.", + "emitStyle" : "const", + "name" : "Color", + "staticMethods" : [ + { + "abiName" : "bjs_Color_static_canonical", + "documentation" : "Returns the canonical name for a channel label.\n- Parameter label: The raw label.\n- Returns: The canonical channel name.", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "canonical", + "parameters" : [ + { + "label" : "label", + "name" : "label", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + }, + "staticContext" : { + "enumName" : { + "_0" : "Color" + } + } + } + ], + "staticProperties" : [ + { + "documentation" : "The default channel.", + "isReadonly" : true, + "isStatic" : true, + "name" : "fallback", + "staticContext" : { + "enumName" : { + "_0" : "Color" + } + }, + "type" : { + "string" : { + + } + } + } + ], + "swiftCallName" : "Color", + "tsFullPath" : "Color" + } + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_greet", + "documentation" : "Returns a greeting for a user.\n- Parameters:\n - name: The user's name.\n - greeting: The greeting word to use.\n- Returns: The composed greeting message.", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "greet", + "parameters" : [ + { + "label" : "name", + "name" : "name", + "type" : { + "string" : { + + } + } + }, + { + "defaultValue" : { + "string" : { + "_0" : "Hello" + } + }, + "label" : "greeting", + "name" : "greeting", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_add", + "documentation" : "Adds two numbers together.\n- Parameter a: The first addend.\n- Parameter b: The second addend.\n- Returns: The sum of the inputs.", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "add", + "parameters" : [ + { + "label" : "a", + "name" : "a", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "label" : "b", + "name" : "b", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "abiName" : "bjs_trimmed", + "documentation" : "Has blank doc lines around the summary; boundaries should be trimmed.", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "trimmed", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_hello", + "documentation" : "Says hello to the world.\n\nDemonstrates that block doc comments are supported too.", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "hello", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_parseInt", + "documentation" : "Parses an integer from text.\n- Parameter text: The text to parse.\n- Returns: The parsed integer.\n- Throws: A `JSException` when the text is not a valid integer.", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "parseInt", + "parameters" : [ + { + "label" : "text", + "name" : "text", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "abiName" : "bjs_MathUtils_double", + "documentation" : "Doubles a value, in a namespace.\n- Parameter value: The value to double.\n- Returns: Twice the input.", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "double", + "namespace" : [ + "MathUtils" + ], + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "abiName" : "bjs_terminator", + "documentation" : "Returns the JSDoc terminator *\/ embedded mid-sentence.", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "terminator", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "protocols" : [ + { + "documentation" : "Receives lifecycle callbacks.", + "methods" : [ + { + "abiName" : "bjs_Listener_onEvent", + "documentation" : "Called when an event fires.\n- Parameter id: The event identifier.", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "onEvent", + "parameters" : [ + { + "label" : "id", + "name" : "id", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "void" : { + + } + } + } + ], + "name" : "Listener", + "properties" : [ + { + "documentation" : "The listener's display name.", + "isReadonly" : true, + "name" : "name", + "type" : { + "string" : { + + } + } + } + ] + } + ], + "structs" : [ + { + "documentation" : "A 2D point in space.", + "methods" : [ + + ], + "name" : "Point", + "properties" : [ + { + "documentation" : "The horizontal position.", + "isReadonly" : true, + "isStatic" : false, + "name" : "x", + "type" : { + "double" : { + + } + } + }, + { + "documentation" : "The vertical position.", + "isReadonly" : true, + "isStatic" : false, + "name" : "y", + "type" : { + "double" : { + + } + } + } + ], + "swiftCallName" : "Point" + } + ] + }, + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DocComments.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DocComments.swift new file mode 100644 index 000000000..eaed9e413 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DocComments.swift @@ -0,0 +1,317 @@ +struct AnyListener: Listener, _BridgedSwiftProtocolWrapper { + let jsObject: JSObject + + func onEvent(id: Int) -> Void { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let idValue = id.bridgeJSLowerParameter() + _extern_onEvent(jsObjectValue, idValue) + } + + var name: String { + get { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let ret = bjs_Listener_name_get(jsObjectValue) + return String.bridgeJSLiftReturn(ret) + } + } + + static func bridgeJSLiftParameter(_ value: Int32) -> Self { + return AnyListener(jsObject: JSObject(id: UInt32(bitPattern: value))) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_Listener_onEvent") +fileprivate func _extern_onEvent_extern(_ jsObject: Int32, _ id: Int32) -> Void +#else +fileprivate func _extern_onEvent_extern(_ jsObject: Int32, _ id: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_onEvent(_ jsObject: Int32, _ id: Int32) -> Void { + return _extern_onEvent_extern(jsObject, id) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_Listener_name_get") +fileprivate func bjs_Listener_name_get_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func bjs_Listener_name_get_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_Listener_name_get(_ jsObject: Int32) -> Int32 { + return bjs_Listener_name_get_extern(jsObject) +} + +extension Color: _BridgedSwiftCaseEnum { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + return bridgeJSRawValue + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> Color { + return bridgeJSLiftParameter(value) + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> Color { + return Color(bridgeJSRawValue: value)! + } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { + return bridgeJSLowerParameter() + } + + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { + switch bridgeJSRawValue { + case 0: + self = .red + case 1: + self = .green + case 2: + self = .blue + default: + return nil + } + } + + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { + switch self { + case .red: + return 0 + case .green: + return 1 + case .blue: + return 2 + } + } +} + +@_expose(wasm, "bjs_Color_static_canonical") +@_cdecl("bjs_Color_static_canonical") +public func _bjs_Color_static_canonical(_ labelBytes: Int32, _ labelLength: Int32) -> Void { + #if arch(wasm32) + let ret = Color.canonical(label: String.bridgeJSLiftParameter(labelBytes, labelLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Color_static_fallback_get") +@_cdecl("bjs_Color_static_fallback_get") +public func _bjs_Color_static_fallback_get() -> Void { + #if arch(wasm32) + let ret = Color.fallback + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension Point: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Point { + let y = Double.bridgeJSStackPop() + let x = Double.bridgeJSStackPop() + return Point(x: x, y: y) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.x.bridgeJSStackPush() + self.y.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_Point(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Point())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Point") +fileprivate func _bjs_struct_lower_Point_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_Point_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_Point(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Point_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Point") +fileprivate func _bjs_struct_lift_Point_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_Point_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_Point() -> Int32 { + return _bjs_struct_lift_Point_extern() +} + +@_expose(wasm, "bjs_greet") +@_cdecl("bjs_greet") +public func _bjs_greet(_ nameBytes: Int32, _ nameLength: Int32, _ greetingBytes: Int32, _ greetingLength: Int32) -> Void { + #if arch(wasm32) + let ret = greet(name: String.bridgeJSLiftParameter(nameBytes, nameLength), greeting: String.bridgeJSLiftParameter(greetingBytes, greetingLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_add") +@_cdecl("bjs_add") +public func _bjs_add(_ a: Int32, _ b: Int32) -> Int32 { + #if arch(wasm32) + let ret = add(a: Int.bridgeJSLiftParameter(a), b: Int.bridgeJSLiftParameter(b)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_trimmed") +@_cdecl("bjs_trimmed") +public func _bjs_trimmed() -> Void { + #if arch(wasm32) + trimmed() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_hello") +@_cdecl("bjs_hello") +public func _bjs_hello() -> Void { + #if arch(wasm32) + hello() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_parseInt") +@_cdecl("bjs_parseInt") +public func _bjs_parseInt(_ textBytes: Int32, _ textLength: Int32) -> Int32 { + #if arch(wasm32) + do { + let ret = try parseInt(text: String.bridgeJSLiftParameter(textBytes, textLength)) + return ret.bridgeJSLowerReturn() + } catch let error { + if let error = error.thrownValue.object { + withExtendedLifetime(error) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } else { + let jsError = JSError(message: error.description) + withExtendedLifetime(jsError.jsObject) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } + return 0 + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_MathUtils_double") +@_cdecl("bjs_MathUtils_double") +public func _bjs_MathUtils_double(_ value: Int32) -> Int32 { + #if arch(wasm32) + let ret = double(value: Int.bridgeJSLiftParameter(value)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_terminator") +@_cdecl("bjs_terminator") +public func _bjs_terminator() -> Void { + #if arch(wasm32) + let ret = terminator() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Greeter_init") +@_cdecl("bjs_Greeter_init") +public func _bjs_Greeter_init(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = Greeter(name: String.bridgeJSLiftParameter(nameBytes, nameLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Greeter_greet") +@_cdecl("bjs_Greeter_greet") +public func _bjs_Greeter_greet(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = Greeter.bridgeJSLiftParameter(_self).greet() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Greeter_name_get") +@_cdecl("bjs_Greeter_name_get") +public func _bjs_Greeter_name_get(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = Greeter.bridgeJSLiftParameter(_self).name + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Greeter_name_set") +@_cdecl("bjs_Greeter_name_set") +public func _bjs_Greeter_name_set(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + #if arch(wasm32) + Greeter.bridgeJSLiftParameter(_self).name = String.bridgeJSLiftParameter(valueBytes, valueLength) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Greeter_deinit") +@_cdecl("bjs_Greeter_deinit") +public func _bjs_Greeter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension Greeter: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_Greeter_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_Greeter_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_Greeter_wrap") +fileprivate func _bjs_Greeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_Greeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_Greeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Greeter_wrap_extern(pointer) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.json index 4b6b720f1..ef9e0b758 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.json @@ -21,9 +21,11 @@ } ] }, + "documentation" : "A greeter living in a namespace.", "methods" : [ { "abiName" : "bjs___Swift_Foundation_Greeter_greet", + "documentation" : "Produces a greeting for the configured name.\n- Returns: The greeting message.", "effects" : { "isAsync" : false, "isStatic" : false, @@ -262,6 +264,7 @@ }, { "abiName" : "bjs_MyModule_Utils_namespacedFunction", + "documentation" : "A namespaced free function.\n- Returns: A fixed namespaced string.", "effects" : { "isAsync" : false, "isStatic" : false, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.json index 3c07b7dcf..397d1123c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.json @@ -21,9 +21,11 @@ } ] }, + "documentation" : "A greeter living in a namespace.", "methods" : [ { "abiName" : "bjs___Swift_Foundation_Greeter_greet", + "documentation" : "Produces a greeting for the configured name.\n- Returns: The greeting message.", "effects" : { "isAsync" : false, "isStatic" : false, @@ -262,6 +264,7 @@ }, { "abiName" : "bjs_MyModule_Utils_namespacedFunction", + "documentation" : "A namespaced free function.\n- Returns: A fixed namespaced string.", "effects" : { "isAsync" : false, "isStatic" : false, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.d.ts new file mode 100644 index 000000000..359d719d1 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.d.ts @@ -0,0 +1,140 @@ +// 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`. + +/** + * Receives lifecycle callbacks. + */ +export interface Listener { + /** + * Called when an event fires. + * @param id The event identifier. + */ + onEvent(id: number): void; + /** + * The listener's display name. + */ + readonly name: string; +} + +/** + * A primary color channel. + */ +export const ColorValues: { + readonly Red: 0; + readonly Green: 1; + readonly Blue: 2; +}; +export type ColorTag = typeof ColorValues[keyof typeof ColorValues]; + +/** + * A 2D point in space. + */ +export interface Point { + /** + * The horizontal position. + */ + x: number; + /** + * The vertical position. + */ + y: number; +} +export type ColorObject = typeof ColorValues & { + /** + * Returns the canonical name for a channel label. + * @param label The raw label. + * @returns The canonical channel name. + */ + canonical(label: string): string; + /** + * The default channel. + */ + readonly fallback: string; +}; + +/// Represents a Swift heap object like a class instance or an actor instance. +export interface SwiftHeapObject { + /// Release the heap object. + /// + /// Note: Calling this method will release the heap object and it will no longer be accessible. + release(): void; +} +/** + * A greeter that keeps the target name. + */ +export interface Greeter extends SwiftHeapObject { + /** + * Returns a greeting for the configured name. + * @returns The greeting message. + */ + greet(): string; + /** + * The configured name. + */ + name: string; +} +export type Exports = { + Greeter: { + /** + * Create a greeter. + * @param name The name to greet. + */ + new(name: string): Greeter; + } + /** + * Returns a greeting for a user. + * @param name The user's name. + * @param greeting The greeting word to use. (default: "Hello") + * @returns The composed greeting message. + */ + greet(name: string, greeting?: string): string; + /** + * Adds two numbers together. + * @param a The first addend. + * @param b The second addend. + * @returns The sum of the inputs. + */ + add(a: number, b: number): number; + /** + * Has blank doc lines around the summary; boundaries should be trimmed. + */ + trimmed(): void; + /** + * Says hello to the world. + * + * Demonstrates that block doc comments are supported too. + */ + hello(): void; + /** + * Parses an integer from text. + * @param text The text to parse. + * @returns The parsed integer. + * @throws A `JSException` when the text is not a valid integer. + */ + parseInt(text: string): number; + /** + * Returns the JSDoc terminator *\/ embedded mid-sentence. + */ + terminator(): string; + Color: ColorObject + MathUtils: { + /** + * Doubles a value, in a namespace. + * @param value The value to double. + * @returns Twice the input. + */ + double(value: number): number; + }, +} +export type Imports = { +} +export function createInstantiator(options: { + imports: Imports; +}, swift: any): Promise<{ + addImports: (importObject: WebAssembly.Imports) => void; + setInstance: (instance: WebAssembly.Instance) => void; + createExports: (instance: WebAssembly.Instance) => Exports; +}>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.js new file mode 100644 index 000000000..07e8673bf --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.js @@ -0,0 +1,421 @@ +// 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`. + +export const ColorValues = { + Red: 0, + Green: 1, + Blue: 2, +}; + +export async function createInstantiator(options, swift) { + let instance; + let memory; + let setException; + let decodeString; + const textDecoder = new TextDecoder("utf-8"); + const textEncoder = new TextEncoder("utf-8"); + let tmpRetString; + let tmpRetBytes; + let tmpRetException; + let tmpRetOptionalBool; + let tmpRetOptionalInt; + let tmpRetOptionalFloat; + let tmpRetOptionalDouble; + let tmpRetOptionalHeapObject; + let strStack = []; + let i32Stack = []; + let i64Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; + let taStack = []; + const enumHelpers = {}; + const structHelpers = {}; + + let _exports = null; + let bjs = null; + const __bjs_createPointHelpers = () => ({ + lower: (value) => { + f64Stack.push(value.x); + f64Stack.push(value.y); + }, + lift: () => { + const f64 = f64Stack.pop(); + const f641 = f64Stack.pop(); + return { x: f641, y: f64 }; + } + }); + + return { + /** + * @param {WebAssembly.Imports} importObject + */ + addImports: (importObject, importsContext) => { + bjs = {}; + importObject["bjs"] = bjs; + bjs["swift_js_return_string"] = function(ptr, len) { + tmpRetString = decodeString(ptr, len); + } + bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { + const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); + bytes.set(source); + } + bjs["swift_js_make_js_string"] = function(ptr, len) { + return swift.memory.retain(decodeString(ptr, len)); + } + bjs["swift_js_init_memory_with_result"] = function(ptr, len) { + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); + target.set(tmpRetBytes); + tmpRetBytes = undefined; + } + bjs["swift_js_throw"] = function(id) { + tmpRetException = swift.memory.retainByRef(id); + } + bjs["swift_js_retain"] = function(id) { + return swift.memory.retainByRef(id); + } + bjs["swift_js_release"] = function(id) { + swift.memory.release(id); + } + bjs["swift_js_push_i32"] = function(v) { + i32Stack.push(v | 0); + } + bjs["swift_js_push_f32"] = function(v) { + f32Stack.push(Math.fround(v)); + } + bjs["swift_js_push_f64"] = function(v) { + f64Stack.push(v); + } + bjs["swift_js_push_string"] = function(ptr, len) { + const value = decodeString(ptr, len); + strStack.push(value); + } + bjs["swift_js_pop_i32"] = function() { + return i32Stack.pop(); + } + bjs["swift_js_pop_f32"] = function() { + return f32Stack.pop(); + } + bjs["swift_js_pop_f64"] = function() { + return f64Stack.pop(); + } + bjs["swift_js_push_pointer"] = function(pointer) { + ptrStack.push(pointer); + } + bjs["swift_js_pop_pointer"] = function() { + return ptrStack.pop(); + } + bjs["swift_js_push_i64"] = function(v) { + i64Stack.push(v); + } + bjs["swift_js_pop_i64"] = function() { + return i64Stack.pop(); + } + const taCtors = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array]; + bjs["swift_js_push_typed_array"] = function(kind, ptr, count) { + const Ctor = taCtors[kind]; + const byteLen = count * Ctor.BYTES_PER_ELEMENT; + const copy = memory.buffer.slice(ptr, ptr + byteLen); + taStack.push(Array.from(new Ctor(copy))); + } + bjs["swift_js_struct_lower_Point"] = function(objectId) { + structHelpers.Point.lower(swift.memory.getObject(objectId)); + } + bjs["swift_js_struct_lift_Point"] = function() { + const value = structHelpers.Point.lift(); + return swift.memory.retain(value); + } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } + bjs["swift_js_return_optional_bool"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalBool = null; + } else { + tmpRetOptionalBool = value !== 0; + } + } + bjs["swift_js_return_optional_int"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalInt = null; + } else { + tmpRetOptionalInt = value | 0; + } + } + bjs["swift_js_return_optional_float"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalFloat = null; + } else { + tmpRetOptionalFloat = Math.fround(value); + } + } + bjs["swift_js_return_optional_double"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalDouble = null; + } else { + tmpRetOptionalDouble = value; + } + } + bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = decodeString(ptr, len); + } + } + bjs["swift_js_return_optional_object"] = function(isSome, objectId) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = swift.memory.getObject(objectId); + } + } + bjs["swift_js_return_optional_heap_object"] = function(isSome, pointer) { + if (isSome === 0) { + tmpRetOptionalHeapObject = null; + } else { + tmpRetOptionalHeapObject = pointer; + } + } + bjs["swift_js_get_optional_int_presence"] = function() { + return tmpRetOptionalInt != null ? 1 : 0; + } + bjs["swift_js_get_optional_int_value"] = function() { + const value = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; + return value; + } + bjs["swift_js_get_optional_string"] = function() { + const str = tmpRetString; + tmpRetString = undefined; + if (str == null) { + return -1; + } else { + const bytes = textEncoder.encode(str); + tmpRetBytes = bytes; + return bytes.length; + } + } + bjs["swift_js_get_optional_float_presence"] = function() { + return tmpRetOptionalFloat != null ? 1 : 0; + } + bjs["swift_js_get_optional_float_value"] = function() { + const value = tmpRetOptionalFloat; + tmpRetOptionalFloat = undefined; + return value; + } + bjs["swift_js_get_optional_double_presence"] = function() { + return tmpRetOptionalDouble != null ? 1 : 0; + } + bjs["swift_js_get_optional_double_value"] = function() { + const value = tmpRetOptionalDouble; + tmpRetOptionalDouble = undefined; + return value; + } + bjs["swift_js_get_optional_heap_object_pointer"] = function() { + const pointer = tmpRetOptionalHeapObject; + tmpRetOptionalHeapObject = undefined; + return pointer || 0; + } + bjs["swift_js_closure_unregister"] = function(funcRef) {} + // Wrapper functions for module: TestModule + if (!importObject["TestModule"]) { + importObject["TestModule"] = {}; + } + importObject["TestModule"]["bjs_Greeter_wrap"] = function(pointer) { + const obj = _exports['Greeter'].__construct(pointer); + return swift.memory.retain(obj); + }; + const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; + TestModule["bjs_Listener_name_get"] = function bjs_Listener_name_get(self) { + try { + let ret = swift.memory.getObject(self).name; + tmpRetBytes = textEncoder.encode(ret); + return tmpRetBytes.length; + } catch (error) { + setException(error); + } + } + TestModule["bjs_Listener_onEvent"] = function bjs_Listener_onEvent(self, id) { + try { + swift.memory.getObject(self).onEvent(id); + } catch (error) { + setException(error); + } + } + }, + setInstance: (i) => { + instance = i; + memory = instance.exports.memory; + + decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + + setException = (error) => { + instance.exports._swift_js_exception.value = swift.memory.retain(error) + } + }, + /** @param {WebAssembly.Instance} instance */ + createExports: (instance) => { + const js = swift.memory.heap; + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.identityMap?.delete(state.pointer); + state.deinit(state.pointer); + }); + + /// Represents a Swift heap object like a class instance or an actor instance. + class SwiftHeapObject { + static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; + const makeFresh = (identityMap) => { + const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false, identityMap }; + obj.pointer = pointer; + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); + if (identityMap) { + identityMap.set(pointer, new WeakRef(obj)); + } + return obj; + }; + + if (!identityCache) { + return makeFresh(null); + } + + const cached = identityCache.get(pointer)?.deref(); + if (cached && !cached.__swiftHeapObjectState.hasReleased) { + deinit(pointer); + return cached; + } + if (identityCache.has(pointer)) { + identityCache.delete(pointer); + } + + return makeFresh(identityCache); + } + + release() { + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.identityMap?.delete(state.pointer); + state.deinit(state.pointer); + } + } + class Greeter extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Greeter_deinit, Greeter.prototype, null); + } + + constructor(name) { + const nameBytes = textEncoder.encode(name); + const nameId = swift.memory.retain(nameBytes); + const ret = instance.exports.bjs_Greeter_init(nameId, nameBytes.length); + return Greeter.__construct(ret); + } + greet() { + instance.exports.bjs_Greeter_greet(this.pointer); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + } + get name() { + instance.exports.bjs_Greeter_name_get(this.pointer); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + } + set name(value) { + const valueBytes = textEncoder.encode(value); + const valueId = swift.memory.retain(valueBytes); + instance.exports.bjs_Greeter_name_set(this.pointer, valueId, valueBytes.length); + } + } + const PointHelpers = __bjs_createPointHelpers(); + structHelpers.Point = PointHelpers; + + const exports = { + Greeter, + greet: function bjs_greet(name, greeting = "Hello") { + const nameBytes = textEncoder.encode(name); + const nameId = swift.memory.retain(nameBytes); + const greetingBytes = textEncoder.encode(greeting); + const greetingId = swift.memory.retain(greetingBytes); + instance.exports.bjs_greet(nameId, nameBytes.length, greetingId, greetingBytes.length); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + }, + add: function bjs_add(a, b) { + const ret = instance.exports.bjs_add(a, b); + return ret; + }, + trimmed: function bjs_trimmed() { + instance.exports.bjs_trimmed(); + }, + hello: function bjs_hello() { + instance.exports.bjs_hello(); + }, + parseInt: function bjs_parseInt(text) { + const textBytes = textEncoder.encode(text); + const textId = swift.memory.retain(textBytes); + const ret = instance.exports.bjs_parseInt(textId, textBytes.length); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + return ret; + }, + terminator: function bjs_terminator() { + instance.exports.bjs_terminator(); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + }, + Color: { + ...ColorValues, + canonical: function(label) { + const labelBytes = textEncoder.encode(label); + const labelId = swift.memory.retain(labelBytes); + instance.exports.bjs_Color_static_canonical(labelId, labelBytes.length); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + }, + get fallback() { + instance.exports.bjs_Color_static_fallback_get(); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + } + }, + MathUtils: { + double: function bjs_MathUtils_double(value) { + const ret = instance.exports.bjs_MathUtils_double(value); + return ret; + }, + }, + }; + _exports = exports; + return exports; + }, + } +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.d.ts index d9af0c8eb..ae792be4c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.d.ts @@ -17,6 +17,10 @@ declare global { } namespace MyModule { namespace Utils { + /** + * A namespaced free function. + * @returns A fixed namespaced string. + */ function namespacedFunction(): string; } } @@ -31,8 +35,15 @@ declare global { } namespace __Swift { namespace Foundation { + /** + * A greeter living in a namespace. + */ class Greeter { constructor(name: string); + /** + * Produces a greeting for the configured name. + * @returns The greeting message. + */ greet(): string; static makeDefault(): Greeter; static readonly defaultGreeting: string; @@ -53,7 +64,14 @@ export interface SwiftHeapObject { /// Note: Calling this method will release the heap object and it will no longer be accessible. release(): void; } +/** + * A greeter living in a namespace. + */ export interface Greeter extends SwiftHeapObject { + /** + * Produces a greeting for the configured name. + * @returns The greeting message. + */ greet(): string; } export interface Converter extends SwiftHeapObject { @@ -75,6 +93,10 @@ export type Exports = { }, MyModule: { Utils: { + /** + * A namespaced free function. + * @returns A fixed namespaced string. + */ namespacedFunction(): string; }, }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.d.ts index 6b2d65cd8..4c02c18b3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.d.ts @@ -11,7 +11,14 @@ export interface SwiftHeapObject { /// Note: Calling this method will release the heap object and it will no longer be accessible. release(): void; } +/** + * A greeter living in a namespace. + */ export interface Greeter extends SwiftHeapObject { + /** + * Produces a greeting for the configured name. + * @returns The greeting message. + */ greet(): string; } export interface Converter extends SwiftHeapObject { @@ -33,6 +40,10 @@ export type Exports = { }, MyModule: { Utils: { + /** + * A namespaced free function. + * @returns A fixed namespaced string. + */ namespacedFunction(): string; }, }, From 358b38a50f368f42b3aec84db8fa222e14a509d9 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Tue, 23 Jun 2026 19:50:34 +0200 Subject: [PATCH 20/50] CI: Build examples in parallel on pull requests (#782) The `build-examples` job built all examples sequentially in a single job, taking ~57 minutes - each example is its own SwiftPM package that recompiles JavaScriptKit and swift-syntax from scratch, with no sharing between them. Split the job by event: - Pull requests fan out a matrix `build-examples` with one job per example, built in parallel. Wall-clock drops to that of the slowest single example (~10 min). Each example now reports as a separate `build-examples ()` check, so the required status checks need updating (see PR description). - `main` keeps the full release build of all examples plus the GitHub Pages deploy (`build-examples-deploy`), so published artifacts are unchanged. Examples are built in release to match the deploy path, keeping the only behavioral change the parallelism. Each matrix step runs `build.sh` from the example directory (via `working-directory`), mirroring Utilities/build-examples.sh. --- .github/workflows/test.yml | 39 +++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 1ce6ebe60..e19fed6f2 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -155,7 +155,44 @@ jobs: exit 1 } + # Pull requests: compile every example in parallel just to catch breakage. + # One job per example avoids rebuilding JavaScriptKit + swift-syntax 6x in series, + # which collapses the wall-clock time from ~1h to that of the slowest single example. build-examples: + if: github.event_name == 'pull_request' + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + example: + - ActorOnWebWorker + - Basic + - Embedded + - Multithreading + - OffscrenCanvas + - PlayBridgeJS + steps: + - uses: actions/checkout@v7 + - uses: ./.github/actions/install-swift + with: + download-url: https://download.swift.org/development/ubuntu2204/swift-DEVELOPMENT-SNAPSHOT-2026-05-27-a/swift-DEVELOPMENT-SNAPSHOT-2026-05-27-a-ubuntu22.04.tar.gz + - uses: swiftwasm/setup-swiftwasm@v2 + id: setup-wasm32-unknown-wasip1 + with: { target: wasm32-unknown-wasip1 } + - uses: swiftwasm/setup-swiftwasm@v2 + id: setup-wasm32-unknown-wasip1-threads + with: { target: wasm32-unknown-wasip1-threads } + # build.sh resolves the package relative to the working directory, so run it + # from the example directory (mirroring Utilities/build-examples.sh's `cd`). + - run: ./build.sh release + working-directory: Examples/${{ matrix.example }} + env: + SWIFT_SDK_ID_wasm32_unknown_wasip1_threads: ${{ steps.setup-wasm32-unknown-wasip1-threads.outputs.swift-sdk-id }} + SWIFT_SDK_ID_wasm32_unknown_wasip1: ${{ steps.setup-wasm32-unknown-wasip1.outputs.swift-sdk-id }} + + # main: build all examples in release and publish them to GitHub Pages. + build-examples-deploy: + if: github.event_name == 'push' && github.ref == 'refs/heads/main' runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 @@ -184,7 +221,7 @@ jobs: environment: name: github-pages url: ${{ steps.deployment.outputs.page_url }} - needs: build-examples + needs: build-examples-deploy permissions: pages: write id-token: write From d748e5b1025d36ccb515908bac52b0c34e100086 Mon Sep 17 00:00:00 2001 From: William Taylor Date: Tue, 26 May 2026 10:38:46 +1000 Subject: [PATCH 21/50] BridgeJS: Export types using a separate JS representation --- .../Generated/JavaScript/BridgeJS.json | 3 + .../Generated/JavaScript/BridgeJS.json | 3 + .../Sources/BridgeJSCore/ClosureCodegen.swift | 6 +- .../Sources/BridgeJSCore/ExportSwift.swift | 108 +- .../BridgeJSCore/ExternalModuleIndex.swift | 6 + .../Sources/BridgeJSCore/ImportTS.swift | 21 +- .../BridgeJSCore/SwiftToSkeleton.swift | 135 +- .../Sources/BridgeJSLink/BridgeJSLink.swift | 4 + .../Sources/BridgeJSLink/JSGlueGen.swift | 41 + .../BridgeJSSkeleton/BridgeJSSkeleton.swift | 28 +- .../BridgeJSToolTests/DiagnosticsTests.swift | 72 + .../Inputs/MacroSwift/Alias.swift | 121 + .../Inputs/MacroSwift/AliasInClosure.swift | 22 + .../Inputs/MacroSwift/EnumAlias.swift | 29 + .../BridgeJSCodegenTests/Alias.json | 719 +++ .../BridgeJSCodegenTests/Alias.swift | 389 ++ .../BridgeJSCodegenTests/AliasInClosure.json | 145 + .../BridgeJSCodegenTests/AliasInClosure.swift | 188 + .../BridgeJSCodegenTests/ArrayTypes.json | 3 + .../BridgeJSCodegenTests/Async.json | 3 + .../CrossFileExtension.json | 3 + .../CrossFileFunctionTypes.ReverseOrder.json | 3 + .../CrossFileFunctionTypes.json | 3 + .../CrossFileTypeResolution.ReverseOrder.json | 3 + .../CrossFileTypeResolution.json | 3 + .../DefaultParameters.json | 3 + .../BridgeJSCodegenTests/DictionaryTypes.json | 3 + .../BridgeJSCodegenTests/EnumAlias.json | 96 + .../BridgeJSCodegenTests/EnumAlias.swift | 52 + .../EnumAssociatedValue.json | 3 + .../BridgeJSCodegenTests/EnumCase.json | 3 + .../EnumNamespace.Global.json | 3 + .../BridgeJSCodegenTests/EnumNamespace.json | 3 + .../BridgeJSCodegenTests/EnumRawType.json | 3 + .../FixedWidthIntegers.json | 3 + .../IdentityModeClass.json | 3 + .../ImportedTypeInExportedInterface.json | 3 + .../JSTypedArrayTypes.json | 3 + .../BridgeJSCodegenTests/JSValue.json | 3 + .../BridgeJSCodegenTests/MixedGlobal.json | 3 + .../BridgeJSCodegenTests/MixedPrivate.json | 3 + .../Namespaces.Global.json | 3 + .../BridgeJSCodegenTests/Namespaces.json | 3 + .../BridgeJSCodegenTests/NestedType.json | 3 + .../BridgeJSCodegenTests/Optionals.json | 3 + .../PrimitiveParameters.json | 3 + .../BridgeJSCodegenTests/PrimitiveReturn.json | 3 + .../BridgeJSCodegenTests/PropertyTypes.json | 3 + .../BridgeJSCodegenTests/Protocol.json | 3 + .../ProtocolInClosure.json | 3 + .../StaticFunctions.Global.json | 3 + .../BridgeJSCodegenTests/StaticFunctions.json | 3 + .../StaticProperties.Global.json | 3 + .../StaticProperties.json | 3 + .../BridgeJSCodegenTests/StringParameter.json | 3 + .../BridgeJSCodegenTests/StringReturn.json | 3 + .../BridgeJSCodegenTests/SwiftClass.json | 3 + .../BridgeJSCodegenTests/SwiftClosure.json | 3 + .../BridgeJSCodegenTests/SwiftStruct.json | 3 + .../SwiftStructImports.json | 3 + .../BridgeJSCodegenTests/Throws.json | 3 + .../BridgeJSCodegenTests/UnsafePointer.json | 3 + .../VoidParameterVoidReturn.json | 3 + .../BridgeJSLinkTests/Alias.d.ts | 71 + .../__Snapshots__/BridgeJSLinkTests/Alias.js | 517 ++ .../BridgeJSLinkTests/AliasInClosure.d.ts | 31 + .../BridgeJSLinkTests/AliasInClosure.js | 372 ++ .../BridgeJSLinkTests/EnumAlias.d.ts | 30 + .../BridgeJSLinkTests/EnumAlias.js | 295 ++ Sources/JavaScriptKit/Macros.swift | 8 +- .../Generated/JavaScript/BridgeJS.json | 3 + .../Generated/JavaScript/BridgeJS.json | 3 + Tests/BridgeJSRuntimeTests/AliasAPIs.swift | 401 ++ Tests/BridgeJSRuntimeTests/AliasTests.swift | 72 + .../Generated/BridgeJS.Macros.swift | 2 + .../Generated/BridgeJS.swift | 4024 ++++++---------- .../Generated/JavaScript/BridgeJS.json | 4180 +++++++++-------- .../JavaScript/AliasTests.mjs | 357 ++ Tests/BridgeJSRuntimeTests/bridge-js.d.ts | 2 + Tests/prelude.mjs | 18 + 80 files changed, 8274 insertions(+), 4429 deletions(-) create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Alias.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/AliasInClosure.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/EnumAlias.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAlias.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAlias.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.d.ts create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.d.ts create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.d.ts create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js create mode 100644 Tests/BridgeJSRuntimeTests/AliasAPIs.swift create mode 100644 Tests/BridgeJSRuntimeTests/AliasTests.swift create mode 100644 Tests/BridgeJSRuntimeTests/JavaScript/AliasTests.mjs diff --git a/Benchmarks/Sources/Generated/JavaScript/BridgeJS.json b/Benchmarks/Sources/Generated/JavaScript/BridgeJS.json index 7209c62f7..124e817ba 100644 --- a/Benchmarks/Sources/Generated/JavaScript/BridgeJS.json +++ b/Benchmarks/Sources/Generated/JavaScript/BridgeJS.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ { "constructor" : { diff --git a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/JavaScript/BridgeJS.json b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/JavaScript/BridgeJS.json index c4a3a8c9d..9beee9031 100644 --- a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/JavaScript/BridgeJS.json +++ b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/JavaScript/BridgeJS.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ { "constructor" : { diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift index d4e65c631..317bd0b4f 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift @@ -153,7 +153,8 @@ public struct ClosureCodegen { let argNames = liftInfo.parameters.map { (argName, _) in liftInfo.parameters.count > 1 ? "\(paramName)\(argName.capitalizedFirstLetter)" : paramName } - liftedParams.append("\(paramType.swiftType).bridgeJSLiftParameter(\(argNames.joined(separator: ", ")))") + let liftCall = "\(paramType.unaliased.swiftType).bridgeJSLiftParameter(\(argNames.joined(separator: ", ")))" + liftedParams.append(paramType.liftAliases(expression: liftCall)) } let tryPrefix = signature.isThrows ? "try " : "" @@ -197,7 +198,8 @@ public struct ClosureCodegen { } printer.write("}") default: - printer.write("return result.bridgeJSLowerReturn()") + let lowered = signature.returnType.lowerAliases(expression: "result") + printer.write("return \(lowered).bridgeJSLowerReturn()") } } } diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift index 90c572b9d..cdbd3970f 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift @@ -227,15 +227,15 @@ public class ExportSwift { } else { optionalSwiftType = "JSUndefinedOr" } - typeNameForIntrinsic = "\(optionalSwiftType)<\(wrappedType.swiftType)>" - liftingExpr = ExprSyntax( - "\(raw: typeNameForIntrinsic).bridgeJSLiftParameter(\(raw: argumentsToLift.joined(separator: ", ")))" - ) + typeNameForIntrinsic = "\(optionalSwiftType)<\(wrappedType.unaliased.swiftType)>" + let liftCall = + "\(typeNameForIntrinsic).bridgeJSLiftParameter(\(argumentsToLift.joined(separator: ", ")))" + liftingExpr = "\(raw: param.type.liftAliases(expression: liftCall))" default: - typeNameForIntrinsic = param.type.swiftType - liftingExpr = ExprSyntax( - "\(raw: typeNameForIntrinsic).bridgeJSLiftParameter(\(raw: argumentsToLift.joined(separator: ", ")))" - ) + typeNameForIntrinsic = param.type.unaliased.swiftType + let liftCall = + "\(typeNameForIntrinsic).bridgeJSLiftParameter(\(argumentsToLift.joined(separator: ", ")))" + liftingExpr = "\(raw: param.type.liftAliases(expression: liftCall))" } liftedParameterExprs.append(liftingExpr) @@ -280,7 +280,8 @@ public class ExportSwift { } if effects.isAsync, returnType != .void { - return CodeBlockItemSyntax(item: .init(StmtSyntax("return \(raw: callExpr)"))) + let lowered = returnType.lowerAliases(expression: callExpr.description) + return CodeBlockItemSyntax(item: .init(StmtSyntax("return \(raw: lowered)"))) } if returnType == .void { @@ -393,17 +394,18 @@ public class ExportSwift { return } + let returnAccessor = returnType.lowerAliases(expression: "ret") switch returnType { case .closure(_, useJSTypedClosure: false): append("return JSTypedClosure(ret).bridgeJSLowerReturn()") case .array, .nullable(.array, _): let stackCodegen = StackCodegen() - for stmt in stackCodegen.lowerStatements(for: returnType, accessor: "ret", varPrefix: "ret") { + for stmt in stackCodegen.lowerStatements(for: returnType, accessor: returnAccessor, varPrefix: "ret") { append(stmt) } case .dictionary(.swiftProtocol): let stackCodegen = StackCodegen() - for stmt in stackCodegen.lowerStatements(for: returnType, accessor: "ret", varPrefix: "ret") { + for stmt in stackCodegen.lowerStatements(for: returnType, accessor: returnAccessor, varPrefix: "ret") { append(stmt) } case .swiftProtocol: @@ -419,7 +421,7 @@ public class ExportSwift { """ ) default: - append("return ret.bridgeJSLowerReturn()") + append("return \(raw: returnAccessor).bridgeJSLowerReturn()") } } @@ -877,8 +879,8 @@ struct StackCodegen { switch type { case .string, .integer, .bool, .float, .double, .jsObject(nil), .jsValue, .swiftStruct, .swiftHeapObject, .unsafePointer, - .swiftProtocol, .caseEnum, .associatedValueEnum, .rawValueEnum, .array, .dictionary: - return "\(raw: type.swiftType).bridgeJSStackPop()" + .swiftProtocol, .caseEnum, .associatedValueEnum, .rawValueEnum, .array, .dictionary, .alias: + return "\(raw: type.liftAliases(expression: "\(type.unaliased.swiftType).bridgeJSStackPop()"))" case .jsObject(let className?): return "\(raw: className)(unsafelyWrapping: JSObject.bridgeJSStackPop())" case .nullable(let wrappedType, let kind): @@ -895,8 +897,10 @@ struct StackCodegen { switch wrappedType { case .string, .integer, .bool, .float, .double, .jsObject(nil), .jsValue, .swiftStruct, .swiftHeapObject, .caseEnum, .associatedValueEnum, .rawValueEnum, - .array, .dictionary: - return "\(raw: typeName)<\(raw: wrappedType.swiftType)>.bridgeJSStackPop()" + .array, .dictionary, .alias: + let popCall = "\(typeName)<\(wrappedType.unaliased.swiftType)>.bridgeJSStackPop()" + let nullableType = BridgeType.nullable(wrappedType, kind) + return "\(raw: nullableType.liftAliases(expression: popCall))" case .jsObject(let className?): return "\(raw: typeName).bridgeJSStackPop().map { \(raw: className)(unsafelyWrapping: $0) }" case .nullable, .void, .namespaceEnum, .closure, .unsafePointer, .swiftProtocol: @@ -918,7 +922,7 @@ struct StackCodegen { switch type { case .string, .integer, .bool, .float, .double, .jsValue, .jsObject(nil), .swiftHeapObject, .unsafePointer, .closure, - .caseEnum, .rawValueEnum, .associatedValueEnum, .swiftStruct, .nullable: + .caseEnum, .rawValueEnum, .associatedValueEnum, .swiftStruct, .nullable, .alias: return ["\(raw: accessor).bridgeJSStackPush()"] case .jsObject(_?): return ["\(raw: accessor).jsObject.bridgeJSStackPush()"] @@ -1204,9 +1208,10 @@ struct EnumCodegen { ) { for (index, associatedValue) in associatedValues.enumerated() { let paramName = associatedValue.label ?? "param\(index)" + let accessor = associatedValue.type.lowerAliases(expression: paramName) let statements = stackCodegen.lowerStatements( for: associatedValue.type, - accessor: paramName, + accessor: accessor, varPrefix: paramName ) for statement in statements { @@ -1339,7 +1344,7 @@ struct StructCodegen { let instanceProps = structDef.properties.filter { !$0.isStatic } for property in instanceProps { - let accessor = "self.\(property.name)" + let accessor = property.type.lowerAliases(expression: "self.\(property.name)") let statements = stackCodegen.lowerStatements( for: property.type, accessor: accessor, @@ -1565,6 +1570,64 @@ extension UnsafePointerType { } extension BridgeType { + var unaliased: BridgeType { + switch self { + case .alias(_, let underlying): return underlying.unaliased + case .nullable(let wrapped, let kind): return .nullable(wrapped.unaliased, kind) + case .array(let element): return .array(element.unaliased) + case .dictionary(let value): return .dictionary(value.unaliased) + case .bool, .integer, .float, .double, .string, .jsValue, .jsObject, + .swiftHeapObject, .unsafePointer, .swiftProtocol, .void, + .caseEnum, .rawValueEnum, .associatedValueEnum, .swiftStruct, + .namespaceEnum, .closure: + return self + } + } + + /// If this type contains an alias, convert the expression with a type of the alias to the underlying type. + func liftAliases(expression: String) -> String { + switch self { + case .alias(let name, _): + return "\(name).bridgeFromJS(\(expression))" + case .nullable(let wrapped, _): + let lifted = wrapped.liftAliases(expression: "$0") + return lifted == "$0" ? expression : "\(expression).map { \(lifted) }" + case .array(let element): + let lifted = element.liftAliases(expression: "$0") + return lifted == "$0" ? expression : "\(expression).map { \(lifted) }" + case .dictionary(let value): + let lifted = value.liftAliases(expression: "$0") + return lifted == "$0" ? expression : "\(expression).mapValues { \(lifted) }" + case .bool, .integer, .float, .double, .string, .jsValue, .jsObject, + .swiftHeapObject, .unsafePointer, .swiftProtocol, .void, + .caseEnum, .rawValueEnum, .associatedValueEnum, .swiftStruct, + .namespaceEnum, .closure: + return expression + } + } + + /// Opposite of `liftAliases`: if this type contains an alias, convert the expression with a type of the underlying to the alias type. + func lowerAliases(expression: String) -> String { + switch self { + case .alias: + return "\(expression).bridgeToJS()" + case .nullable(let wrapped, _): + let lowered = wrapped.lowerAliases(expression: "$0") + return lowered == "$0" ? expression : "\(expression).map { \(lowered) }" + case .array(let element): + let lowered = element.lowerAliases(expression: "$0") + return lowered == "$0" ? expression : "\(expression).map { \(lowered) }" + case .dictionary(let value): + let lowered = value.lowerAliases(expression: "$0") + return lowered == "$0" ? expression : "\(expression).mapValues { \(lowered) }" + case .bool, .integer, .float, .double, .string, .jsValue, .jsObject, + .swiftHeapObject, .unsafePointer, .swiftProtocol, .void, + .caseEnum, .rawValueEnum, .associatedValueEnum, .swiftStruct, + .namespaceEnum, .closure: + return expression + } + } + var swiftType: String { switch self { case .bool: return "Bool" @@ -1593,6 +1656,7 @@ extension BridgeType { let effectsStr = (signature.isAsync ? " async" : "") + (signature.isThrows ? " throws" : "") let closureType = "(\(paramTypes))\(effectsStr) -> \(signature.returnType.swiftType)" return useJSTypedClosure ? "JSTypedClosure<\(closureType)>" : closureType + case .alias(let name, _): return name } } @@ -1617,6 +1681,8 @@ extension BridgeType { return true case .nullable(let wrapped, _): return wrapped.isStackUsingParameter + case .alias(_, let underlying): + return underlying.isStackUsingParameter default: return false } @@ -1675,6 +1741,8 @@ extension BridgeType { return LiftingIntrinsicInfo(parameters: [("callbackId", .i32)]) case .array, .dictionary: return LiftingIntrinsicInfo(parameters: []) + case .alias(_, let underlying): + return try underlying.liftParameterInfo() } } @@ -1726,6 +1794,8 @@ extension BridgeType { return .jsObject case .array, .dictionary: return .array + case .alias(_, let underlying): + return try underlying.loweringReturnInfo() } } } diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExternalModuleIndex.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExternalModuleIndex.swift index 91fd4388a..33a27d087 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ExternalModuleIndex.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExternalModuleIndex.swift @@ -63,6 +63,12 @@ public struct ExternalModuleIndex { for proto in exported.protocols { register(dotPath: proto.name, bridgeType: .swiftProtocol(proto.name)) } + for alias in exported.aliases { + register( + dotPath: alias.swiftCallName, + bridgeType: .alias(name: alias.swiftCallName, underlying: alias.underlying) + ) + } entriesByModule[moduleName] = moduleEntries } diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift index 2912ce698..9fd2af08e 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift @@ -172,7 +172,8 @@ public struct ImportTS { if loweringInfo.useBorrowing { let returnVariableName = "ret\(borrowedArguments.count)" let assign = needsReturnVariable ? "let \(returnVariableName) = " : "" - body.write("\(assign)\(param.name).bridgeJSWithLoweredParameter { \(pattern) in") + let loweredAlias = param.type.lowerAliases(expression: param.name) + body.write("\(assign)\(loweredAlias).bridgeJSWithLoweredParameter { \(pattern) in") body.indent() borrowedArguments.append( BorrowedArgument( @@ -203,7 +204,8 @@ public struct ImportTS { "(\(raw: param.name) as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()" ) } else { - initializerExpr = ExprSyntax("\(raw: param.name).bridgeJSLowerParameter()") + let loweredAlias = param.type.lowerAliases(expression: param.name) + initializerExpr = ExprSyntax("\(raw: loweredAlias).bridgeJSLowerParameter()") } if loweringInfo.loweredParameters.isEmpty { @@ -294,18 +296,21 @@ public struct ImportTS { if returnType.usesSideChannelForOptionalReturn() { // Side channel returns: extern function returns Void, value is retrieved via side channel - body.write("return \(returnType.swiftType).bridgeJSLiftReturnFromSideChannel()") + let liftCall = "\(returnType.unaliased.swiftType).bridgeJSLiftReturnFromSideChannel()" + body.write("return \(returnType.liftAliases(expression: liftCall))") } else { let liftExpr: String switch returnType { case .closure(let signature, _): liftExpr = "_BJS_Closure_\(signature.mangleName).bridgeJSLift(ret)" default: + let liftCall: String if liftingInfo.valueToLift != nil { - liftExpr = "\(returnType.swiftType).bridgeJSLiftReturn(ret)" + liftCall = "\(returnType.unaliased.swiftType).bridgeJSLiftReturn(ret)" } else { - liftExpr = "\(returnType.swiftType).bridgeJSLiftReturn()" + liftCall = "\(returnType.unaliased.swiftType).bridgeJSLiftReturn()" } + liftExpr = returnType.liftAliases(expression: liftCall) } body.write("return \(liftExpr)") } @@ -957,6 +962,8 @@ extension BridgeType { return LoweringParameterInfo(loweredParameters: params, useBorrowing: wrappedInfo.useBorrowing) case .array, .dictionary: return LoweringParameterInfo(loweredParameters: []) + case .alias(_, let underlying): + return try underlying.loweringParameterInfo(context: context) } } @@ -1019,7 +1026,7 @@ extension BridgeType { case .nullable(let wrappedType, _): // jsObject and `@JS struct` use the stack ABI for optionals — the thunk returns // void and the value (plus isSome discriminator) flows through the stacks. - if case .jsObject = wrappedType { + if case .jsObject = wrappedType.unaliased { return LiftingReturnInfo(valueToLift: nil) } if case .swiftStruct = wrappedType, context == .importTS { @@ -1029,6 +1036,8 @@ extension BridgeType { return LiftingReturnInfo(valueToLift: wrappedInfo.valueToLift) case .array, .dictionary: return LiftingReturnInfo(valueToLift: nil) + case .alias(_, let underlying): + return try underlying.liftingReturnInfo(context: context) } } } diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index ed7ebcd1b..8b4e79d64 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -399,6 +399,11 @@ public final class SwiftToSkeleton { if let enumDecl = typeDecl.as(EnumDeclSyntax.self) { let swiftCallName = SwiftToSkeleton.computeSwiftCallName(for: enumDecl, itemName: enumDecl.name.text) + if let jsAttribute = enumDecl.attributes.firstJSAttribute, + let aliasTarget = extractAliasTarget(from: jsAttribute) + { + return aliasType(target: aliasTarget, swiftCallName: swiftCallName, errors: &errors) + } let rawTypeString = enumDecl.inheritanceClause?.inheritedTypes.first { inheritedType in let typeName = inheritedType.type.trimmedDescription return ExportSwiftConstants.supportedRawTypes.contains(typeName) @@ -439,6 +444,11 @@ public final class SwiftToSkeleton { if structDecl.attributes.hasAttribute(name: "JSClass") { return .jsObject(swiftCallName) } + if let jsAttribute = structDecl.attributes.firstJSAttribute, + let aliasTarget = extractAliasTarget(from: jsAttribute) + { + return aliasType(target: aliasTarget, swiftCallName: swiftCallName, errors: &errors) + } return .swiftStruct(swiftCallName) } @@ -456,6 +466,13 @@ public final class SwiftToSkeleton { return .jsObject(swiftCallName) } + if let classDecl = typeDecl.as(ClassDeclSyntax.self), + let jsAttribute = classDecl.attributes.firstJSAttribute, + let aliasTarget = extractAliasTarget(from: jsAttribute) + { + return aliasType(target: aliasTarget, swiftCallName: swiftCallName, errors: &errors) + } + return .swiftHeapObject(swiftCallName) } @@ -517,6 +534,50 @@ public final class SwiftToSkeleton { } } + fileprivate func extractAliasTarget(from jsAttribute: AttributeSyntax) -> TypeSyntax? { + guard + let arguments = jsAttribute.arguments?.as(LabeledExprListSyntax.self), + let asArg = arguments.first(where: { $0.label?.text == "as" }), + let memberAccess = asArg.expression.as(MemberAccessExprSyntax.self), + memberAccess.declName.baseName.text == "self", + let base = memberAccess.base + else { + return nil + } + return TypeSyntax(stringLiteral: base.trimmedDescription) + } + + fileprivate func aliasType( + target aliasTarget: TypeSyntax, + swiftCallName: String, + errors: inout [DiagnosticError] + ) -> BridgeType? { + if let targetDecl = typeDeclResolver.resolve(aliasTarget), + let targetJSAttribute = targetDecl.attributes.firstJSAttribute, + extractAliasTarget(from: targetJSAttribute) != nil + { + errors.append( + DiagnosticError( + node: aliasTarget, + message: "`@JS(as:)` target must be a `@JS` type, not another `@JS(as:)` type", + hint: "Use the underlying `@JS` type directly" + ) + ) + return nil + } + guard let targetType = lookupType(for: aliasTarget, errors: &errors) else { return nil } + if case .swiftProtocol = targetType { + errors.append( + DiagnosticError( + node: aliasTarget, + message: "`@JS(as:)` cannot target a `@JS protocol`" + ) + ) + return nil + } + return .alias(name: swiftCallName, underlying: targetType) + } + fileprivate static func parseUnsafePointerType(_ type: TypeSyntax) -> UnsafePointerType? { func parse(baseName: String, genericArg: TypeSyntax?) -> UnsafePointerType? { let pointee = genericArg?.trimmedDescription @@ -650,6 +711,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { /// The names of the exported structs, in the order they were written in the source file var exportedStructNames: [String] = [] var exportedStructByName: [String: ExportedStruct] = [:] + var exportedAliases: [ExportedAlias] = [] var errors: [DiagnosticError] = [] /// Extensions collected during the walk, to be resolved after all files have been walked var deferredExtensions: [ExtensionDeclSyntax] = [] @@ -660,6 +722,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { result.enums.append(contentsOf: exportedEnumNames.map { exportedEnumByName[$0]! }) result.structs.append(contentsOf: exportedStructNames.map { exportedStructByName[$0]! }) result.protocols.append(contentsOf: exportedProtocolNames.map { exportedProtocolByName[$0]! }) + result.aliases.append(contentsOf: exportedAliases) } /// Creates a unique key by combining name and namespace @@ -1564,6 +1627,11 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { return .skipChildren } + if let aliasTarget = parent.extractAliasTarget(from: jsAttribute) { + recordAlias(node: node, aliasTarget: aliasTarget) + return .skipChildren + } + let namespaceResult = resolveNamespace(from: jsAttribute, for: node, declarationType: "class") guard namespaceResult.isValid else { return .skipChildren @@ -1662,11 +1730,38 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { return true } + private func recordAlias( + node: some SyntaxProtocol & NamedDeclSyntax, + aliasTarget: TypeSyntax + ) { + let swiftCallName = SwiftToSkeleton.computeSwiftCallName(for: node, itemName: node.name.text) + var lookupErrors: [DiagnosticError] = [] + guard + let aliasBridgeType = parent.aliasType( + target: aliasTarget, + swiftCallName: swiftCallName, + errors: &lookupErrors + ), + case .alias(_, let underlying) = aliasBridgeType + else { + errors.append(contentsOf: lookupErrors) + return + } + exportedAliases.append( + ExportedAlias(swiftCallName: swiftCallName, underlying: underlying) + ) + } + override func visit(_ node: EnumDeclSyntax) -> SyntaxVisitorContinueKind { guard let jsAttribute = node.attributes.firstJSAttribute else { return .skipChildren } + if let aliasTarget = parent.extractAliasTarget(from: jsAttribute) { + recordAlias(node: node, aliasTarget: aliasTarget) + return .skipChildren + } + let name = node.name.text let rawType: String? = node.inheritanceClause?.inheritedTypes.first { inheritedType in @@ -1767,24 +1862,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { } for enumCase in exportedEnum.cases { for associatedValue in enumCase.associatedValues { - switch associatedValue.type { - case .string, .integer, .float, .double, .bool, .caseEnum, .rawValueEnum, - .swiftStruct, .swiftHeapObject, .jsObject, .associatedValueEnum, .array: - break - case .nullable(let wrappedType, _): - switch wrappedType { - case .string, .integer, .float, .double, .bool, .caseEnum, .rawValueEnum, - .swiftStruct, .swiftHeapObject, .jsObject, .associatedValueEnum, .array: - break - default: - diagnose( - node: node, - message: "Unsupported associated value type: \(associatedValue.type.swiftType)", - hint: - "Only primitive types, enums, structs, classes, JSObject, arrays, and their optionals are supported in associated-value enums" - ) - } - default: + if !associatedValue.type.isSupportedAsAssociatedValue() { diagnose( node: node, message: "Unsupported associated value type: \(associatedValue.type.swiftType)", @@ -1867,6 +1945,11 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { return .skipChildren } + if let aliasTarget = parent.extractAliasTarget(from: jsAttribute) { + recordAlias(node: node, aliasTarget: aliasTarget) + return .skipChildren + } + let name = node.name.text let namespaceResult = resolveNamespace(from: jsAttribute, for: node, declarationType: "struct") @@ -2971,6 +3054,22 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { } } +extension BridgeType { + fileprivate func isSupportedAsAssociatedValue(allowNullable: Bool = true) -> Bool { + switch self { + case .string, .integer, .float, .double, .bool, .caseEnum, .rawValueEnum, + .swiftStruct, .swiftHeapObject, .jsObject, .associatedValueEnum, .array: + return true + case .alias(_, let underlying): + return underlying.isSupportedAsAssociatedValue(allowNullable: false) + case .nullable(let wrapped, _) where allowNullable: + return wrapped.isSupportedAsAssociatedValue(allowNullable: false) + default: + return false + } + } +} + extension GenericArgumentListSyntax { /// Compatibility helper for accessing the first argument as a TypeSyntax /// diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index a24fde09b..ed9eb950f 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -1550,6 +1550,8 @@ public struct BridgeJSLink { } } return type.tsType + case .alias(_, let underlying): + return resolveTypeScriptType(underlying, exportedSkeletons: exportedSkeletons) case .nullable(let wrapped, let kind): let base = resolveTypeScriptType(wrapped, exportedSkeletons: exportedSkeletons) return "\(base) | \(kind.absenceLiteral)" @@ -3960,6 +3962,8 @@ extension BridgeType { return "\(inner)[]" case .dictionary(let valueType): return "Record" + case .alias(_, let underlying): + return underlying.tsType } } diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift index ac2144bbc..c6ac936cd 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift @@ -651,6 +651,9 @@ struct IntrinsicJSFragment: Sendable { kind: JSOptionalKind, context bridgeContext: BridgeContext = .importTS ) throws -> IntrinsicJSFragment { + if case .alias(_, let underlying) = wrappedType { + return try optionalLiftParameter(wrappedType: underlying, kind: kind, context: bridgeContext) + } if wrappedType.isSingleParamScalar { let coerce = wrappedType.liftCoerce return IntrinsicJSFragment( @@ -739,6 +742,9 @@ struct IntrinsicJSFragment: Sendable { wrappedType: BridgeType, kind: JSOptionalKind ) throws -> IntrinsicJSFragment { + if case .alias(_, let underlying) = wrappedType { + return try optionalLowerParameter(wrappedType: underlying, kind: kind) + } if wrappedType.isSingleParamScalar { let wasmType = wrappedType.wasmParams[0].type let coerce = wrappedType.lowerCoerce @@ -967,6 +973,9 @@ struct IntrinsicJSFragment: Sendable { wrappedType: BridgeType, kind: JSOptionalKind ) -> IntrinsicJSFragment { + if case .alias(_, let underlying) = wrappedType { + return optionalLiftReturn(wrappedType: underlying, kind: kind) + } if let scalarKind = wrappedType.optionalScalarKind { return optionalLiftReturnFromStorage(storage: scalarKind.storageName) } @@ -1064,6 +1073,9 @@ struct IntrinsicJSFragment: Sendable { } static func optionalLowerReturn(wrappedType: BridgeType, kind: JSOptionalKind) throws -> IntrinsicJSFragment { + if case .alias(_, let underlying) = wrappedType { + return try optionalLowerReturn(wrappedType: underlying, kind: kind) + } switch wrappedType { case .void, .nullable, .namespaceEnum, .closure: throw BridgeJSLinkError(message: "Unsupported optional wrapped type for protocol export: \(wrappedType)") @@ -1188,6 +1200,9 @@ struct IntrinsicJSFragment: Sendable { // MARK: - Protocol Support static func protocolPropertyOptionalToSideChannel(wrappedType: BridgeType) throws -> IntrinsicJSFragment { + if case .alias(_, let underlying) = wrappedType { + return try protocolPropertyOptionalToSideChannel(wrappedType: underlying) + } if let scalarKind = wrappedType.optionalScalarKind { let storage = scalarKind.storageName return IntrinsicJSFragment( @@ -1323,6 +1338,8 @@ struct IntrinsicJSFragment: Sendable { return try arrayLower(elementType: elementType) case .dictionary(let valueType): return try dictionaryLower(valueType: valueType) + case .alias(_, let underlying): + return try lowerParameter(type: underlying) default: throw BridgeJSLinkError(message: "Unhandled type in lowerParameter: \(type)") } @@ -1380,6 +1397,8 @@ struct IntrinsicJSFragment: Sendable { return try arrayLift(elementType: elementType) case .dictionary(let valueType): return try dictionaryLift(valueType: valueType) + case .alias(_, let underlying): + return try liftReturn(type: underlying) default: throw BridgeJSLinkError(message: "Unhandled type in liftReturn: \(type)") } @@ -1470,6 +1489,8 @@ struct IntrinsicJSFragment: Sendable { return try arrayLift(elementType: elementType) case .dictionary(let valueType): return try dictionaryLift(valueType: valueType) + case .alias(_, let underlying): + return try liftParameter(type: underlying, context: context) default: throw BridgeJSLinkError(message: "Unhandled type in liftParameter: \(type)") } @@ -1524,6 +1545,8 @@ struct IntrinsicJSFragment: Sendable { return try arrayLower(elementType: elementType) case .dictionary(let valueType): return try dictionaryLower(valueType: valueType) + case .alias(_, let underlying): + return try lowerReturn(type: underlying, context: context) default: throw BridgeJSLinkError(message: "Unhandled type in lowerReturn: \(type)") } @@ -1941,6 +1964,9 @@ struct IntrinsicJSFragment: Sendable { } private static func stackLiftFragment(elementType: BridgeType) throws -> IntrinsicJSFragment { + if case .alias(_, let underlying) = elementType { + return try stackLiftFragment(elementType: underlying) + } if case .nullable(let wrappedType, let kind) = elementType { return try optionalElementRaiseFragment(wrappedType: wrappedType, kind: kind) } @@ -2068,6 +2094,9 @@ struct IntrinsicJSFragment: Sendable { } private static func stackLowerFragment(elementType: BridgeType) throws -> IntrinsicJSFragment { + if case .alias(_, let underlying) = elementType { + return try stackLowerFragment(elementType: underlying) + } if case .nullable(let wrappedType, let kind) = elementType { return try optionalElementLowerFragment(wrappedType: wrappedType, kind: kind) } @@ -2192,6 +2221,9 @@ struct IntrinsicJSFragment: Sendable { wrappedType: BridgeType, kind: JSOptionalKind ) throws -> IntrinsicJSFragment { + if case .alias(_, let underlying) = wrappedType { + return try optionalElementRaiseFragment(wrappedType: underlying, kind: kind) + } if case .associatedValueEnum(let fullName) = wrappedType { let base = fullName.components(separatedBy: ".").last ?? fullName let absenceLiteral = kind.absenceLiteral @@ -2258,6 +2290,9 @@ struct IntrinsicJSFragment: Sendable { wrappedType: BridgeType, kind: JSOptionalKind ) throws -> IntrinsicJSFragment { + if case .alias(_, let underlying) = wrappedType { + return try optionalElementLowerFragment(wrappedType: underlying, kind: kind) + } if case .associatedValueEnum(let fullName) = wrappedType { let base = fullName.components(separatedBy: ".").last ?? fullName return IntrinsicJSFragment( @@ -2680,6 +2715,8 @@ private extension BridgeType { return .stackABI case .nullable(let wrapped, _): return wrapped.optionalConvention + case .alias(_, let underlying): + return underlying.optionalConvention } } @@ -2711,6 +2748,8 @@ private extension BridgeType { return .i32(-1) case .nullable(let wrapped, _): return wrapped.nilSentinel + case .alias(_, let underlying): + return underlying.nilSentinel default: return .none } @@ -2776,6 +2815,8 @@ private extension BridgeType { return [] case .nullable(let wrapped, _): return wrapped.wasmParams + case .alias(_, let underlying): + return underlying.wasmParams } } diff --git a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift index 436c40ab7..4d1ebbbc1 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift @@ -274,6 +274,7 @@ public enum BridgeType: Codable, Equatable, Hashable, Sendable { case swiftProtocol(String) case swiftStruct(String) indirect case closure(ClosureSignature, useJSTypedClosure: Bool) + indirect case alias(name: String, underlying: BridgeType) } public enum WasmCoreType: String, Codable, Sendable { @@ -1007,12 +1008,23 @@ public struct ExportedProperty: Codable, Equatable, Sendable { } } +public struct ExportedAlias: Codable { + public let swiftCallName: String + public let underlying: BridgeType + + public init(swiftCallName: String, underlying: BridgeType) { + self.swiftCallName = swiftCallName + self.underlying = underlying + } +} + public struct ExportedSkeleton: Codable { public var functions: [ExportedFunction] public var classes: [ExportedClass] public var enums: [ExportedEnum] public var structs: [ExportedStruct] public var protocols: [ExportedProtocol] + public var aliases: [ExportedAlias] /// Whether to expose exported APIs to the global namespace. /// /// When `true`, exported functions, classes, and namespaces are available @@ -1032,6 +1044,7 @@ public struct ExportedSkeleton: Codable { enums: [ExportedEnum], structs: [ExportedStruct] = [], protocols: [ExportedProtocol] = [], + aliases: [ExportedAlias] = [], exposeToGlobal: Bool, identityMode: String? = nil ) { @@ -1040,6 +1053,7 @@ public struct ExportedSkeleton: Codable { self.enums = enums self.structs = structs self.protocols = protocols + self.aliases = aliases self.exposeToGlobal = exposeToGlobal self.identityMode = identityMode } @@ -1050,12 +1064,13 @@ public struct ExportedSkeleton: Codable { self.enums.append(contentsOf: other.enums) self.structs.append(contentsOf: other.structs) self.protocols.append(contentsOf: other.protocols) + self.aliases.append(contentsOf: other.aliases) assert(self.exposeToGlobal == other.exposeToGlobal) assert(self.identityMode == other.identityMode) } public var isEmpty: Bool { - functions.isEmpty && classes.isEmpty && enums.isEmpty && structs.isEmpty && protocols.isEmpty + functions.isEmpty && classes.isEmpty && enums.isEmpty && structs.isEmpty && protocols.isEmpty && aliases.isEmpty } /// Distinct `async` return types needing a `Promise_resolve_` helper, deduplicated @@ -1651,6 +1666,8 @@ extension BridgeType { case .dictionary: // Dictionaries use stack-based return with entry count (no direct WASM return type) return nil + case .alias(_, let underlying): + return underlying.abiReturnType } } @@ -1738,6 +1755,8 @@ extension BridgeType { case .dictionary(let valueType): // Dictionary mangling: "SD" prefix followed by value type (key is always String) return "SD\(valueType.mangleTypeName)" + case .alias(let name, _): + return "Al\(name.count)\(name)" } } @@ -1749,8 +1768,11 @@ extension BridgeType { guard case .nullable(let wrappedType, _) = self else { return false } + return wrappedType.requiresSideChannelForOptionalReturnIfWrapped + } - switch wrappedType { + private var requiresSideChannelForOptionalReturnIfWrapped: Bool { + switch self { case .string, .integer, .float, .double, .swiftProtocol: return true case .rawValueEnum(_, let rawType): @@ -1764,6 +1786,8 @@ extension BridgeType { } case .bool, .caseEnum, .swiftHeapObject, .associatedValueEnum, .jsObject: return false + case .alias(_, let underlying): + return underlying.requiresSideChannelForOptionalReturnIfWrapped default: return false } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift index ae12b6566..2db9ac2d7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift @@ -354,6 +354,78 @@ import Testing #expect(try exportSwift.finalize() != nil) } + @Test + func chainedJSAsDiagnostic() throws { + let source = """ + @JS(as: B.self) struct A { + consuming func bridgeToJS() -> B { fatalError() } + static func bridgeFromJS(_ value: consuming B) -> A { fatalError() } + } + @JS(as: C.self) struct B { + consuming func bridgeToJS() -> C { fatalError() } + static func bridgeFromJS(_ value: consuming C) -> B { fatalError() } + } + @JS class C { @JS init() {} } + """ + let swiftAPI = SwiftToSkeleton( + progress: .silent, + moduleName: "TestModule", + exposeToGlobal: false, + externalModuleIndex: .empty + ) + swiftAPI.addSourceFile(Parser.parse(source: source), inputFilePath: "test.swift") + #expect(throws: BridgeJSCoreDiagnosticError.self) { + _ = try swiftAPI.finalize() + } + } + + @Test + func cyclicJSAsDiagnostic() throws { + let source = """ + @JS(as: B.self) struct A { + consuming func bridgeToJS() -> B { fatalError() } + static func bridgeFromJS(_ value: consuming B) -> A { fatalError() } + } + @JS(as: A.self) struct B { + consuming func bridgeToJS() -> A { fatalError() } + static func bridgeFromJS(_ value: consuming A) -> B { fatalError() } + } + """ + let swiftAPI = SwiftToSkeleton( + progress: .silent, + moduleName: "TestModule", + exposeToGlobal: false, + externalModuleIndex: .empty + ) + swiftAPI.addSourceFile(Parser.parse(source: source), inputFilePath: "test.swift") + #expect(throws: BridgeJSCoreDiagnosticError.self) { + _ = try swiftAPI.finalize() + } + } + + @Test + func jsAsProtocolTargetDiagnostic() throws { + let source = """ + @JS protocol Audible { + func play() + } + @JS(as: Audible.self) struct AudibleTag { + consuming func bridgeToJS() -> any Audible { fatalError() } + static func bridgeFromJS(_ value: consuming any Audible) -> AudibleTag { fatalError() } + } + """ + let swiftAPI = SwiftToSkeleton( + progress: .silent, + moduleName: "TestModule", + exposeToGlobal: false, + externalModuleIndex: .empty + ) + swiftAPI.addSourceFile(Parser.parse(source: source), inputFilePath: "test.swift") + #expect(throws: BridgeJSCoreDiagnosticError.self) { + _ = try swiftAPI.finalize() + } + } + @Test func omitsNextLineWhenErrorIsOnLastLine() throws { let source = """ diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Alias.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Alias.swift new file mode 100644 index 000000000..f4d56653f --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Alias.swift @@ -0,0 +1,121 @@ +@JS(as: PolygonReference.self) struct Polygon { + var vertices: [Double] + + consuming func bridgeToJS() -> PolygonReference { + return PolygonReference(underlying: self) + } + + static func bridgeFromJS(_ value: consuming PolygonReference) -> Polygon { + return value.underlying + } +} + +@JS final class PolygonReference { + var underlying: Polygon + + @JS init(underlying: Polygon) { + self.underlying = underlying + } + + @JS func snapshot() -> Polygon + @JS func merge(_ other: Polygon) -> Polygon + @JS static func origin() -> Polygon +} + +@JS(as: TagReference.self) struct Tag { + var name: String + + consuming func bridgeToJS() -> TagReference { + return TagReference(underlying: self) + } + + static func bridgeFromJS(_ value: consuming TagReference) -> Tag { + return value.underlying + } +} + +@JS final class TagReference { + var underlying: Tag + + @JS init(underlying: Tag) { + self.underlying = underlying + } +} + +@JS func roundtripPolygon(_ polygon: Polygon) -> Polygon + +@JS func optionalPolygon(_ polygon: Polygon?) -> Polygon? + +@JS func polygonArray(_ polygons: [Polygon]) -> [Polygon] + +@JS func validatePolygon(_ polygon: Polygon) throws(JSException) -> Polygon + +@JS func makeTag(_ name: String) -> Tag + +@JS(as: String.self) struct Tagged { + var raw: String + + consuming func bridgeToJS() -> String { + return raw + } + + static func bridgeFromJS(_ value: consuming String) -> Tagged { + return Tagged(raw: value) + } +} + +@JSFunction func acceptTagged(_ tagged: Tagged) throws(JSException) -> Void +@JSFunction func acceptOptionalTagged(_ tagged: Tagged?) throws(JSException) -> Void +@JSFunction func roundtripTagged(_ tagged: Tagged) throws(JSException) -> Tagged + +@JSClass class Surface { + @JSFunction init() throws(JSException) + @JSGetter var label: String +} + +@JS(as: Surface.self) struct Canvas { + consuming func bridgeToJS() -> Surface { + fatalError("test stub") + } + + static func bridgeFromJS(_ value: consuming Surface) -> Canvas { + return Canvas() + } +} + +@JSFunction func produceOptionalCanvas() throws(JSException) -> Canvas? + +@JS enum InnerTag { + case payload(Int) + case empty +} + +@JS(as: InnerTag.self) struct AliasedTag { + consuming func bridgeToJS() -> InnerTag { + return .empty + } + + static func bridgeFromJS(_ value: consuming InnerTag) -> AliasedTag { + return AliasedTag() + } +} + +@JS func roundtripTags(_ xs: [AliasedTag?]) -> [AliasedTag?] + +@JS(as: Int.self) struct UserId { + var rawValue: Int + + consuming func bridgeToJS() -> Int { + return rawValue + } + + static func bridgeFromJS(_ value: consuming Int) -> UserId { + return UserId(rawValue: value) + } +} + +@JS protocol HasOptionalUserId { + var userId: UserId? { get } +} + +@JS func describeUser(_ owner: HasOptionalUserId) -> HasOptionalUserId diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/AliasInClosure.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/AliasInClosure.swift new file mode 100644 index 000000000..384481c5c --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/AliasInClosure.swift @@ -0,0 +1,22 @@ +@JS(as: PolygonReference.self) struct Polygon { + var sides: Int + + consuming func bridgeToJS() -> PolygonReference { + return PolygonReference(sides: sides) + } + + static func bridgeFromJS(_ value: consuming PolygonReference) -> Polygon { + return Polygon(sides: value.sides) + } +} + +@JS final class PolygonReference { + var sides: Int + + @JS init(sides: Int) { + self.sides = sides + } +} + +@JS func makePolygonFactory() -> () -> Polygon +@JS func makePolygonInspector() -> (Polygon) -> Int diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/EnumAlias.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/EnumAlias.swift new file mode 100644 index 000000000..7da395c2a --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/EnumAlias.swift @@ -0,0 +1,29 @@ +@JS(as: ColorBox.self) enum Color { + case red, green, blue + + consuming func bridgeToJS() -> ColorBox { + switch self { + case .red: return ColorBox(name: "red") + case .green: return ColorBox(name: "green") + case .blue: return ColorBox(name: "blue") + } + } + + static func bridgeFromJS(_ value: consuming ColorBox) -> Color { + switch value.name { + case "green": return .green + case "blue": return .blue + default: return .red + } + } +} + +@JS final class ColorBox { + var name: String + + @JS init(name: String) { + self.name = name + } +} + +@JS func roundtripColor(_ color: Color) -> Color diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.json new file mode 100644 index 000000000..bcdc43375 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.json @@ -0,0 +1,719 @@ +{ + "exported" : { + "aliases" : [ + { + "swiftCallName" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } + }, + { + "swiftCallName" : "Tag", + "underlying" : { + "swiftHeapObject" : { + "_0" : "TagReference" + } + } + }, + { + "swiftCallName" : "Tagged", + "underlying" : { + "string" : { + + } + } + }, + { + "swiftCallName" : "Canvas", + "underlying" : { + "jsObject" : { + "_0" : "Surface" + } + } + }, + { + "swiftCallName" : "AliasedTag", + "underlying" : { + "associatedValueEnum" : { + "_0" : "InnerTag" + } + } + }, + { + "swiftCallName" : "UserId", + "underlying" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_PolygonReference_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "underlying", + "name" : "underlying", + "type" : { + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_PolygonReference_snapshot", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "snapshot", + "parameters" : [ + + ], + "returnType" : { + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } + } + } + }, + { + "abiName" : "bjs_PolygonReference_merge", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "merge", + "parameters" : [ + { + "label" : "_", + "name" : "other", + "type" : { + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } + } + } + } + ], + "returnType" : { + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } + } + } + }, + { + "abiName" : "bjs_PolygonReference_static_origin", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "origin", + "parameters" : [ + + ], + "returnType" : { + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } + } + }, + "staticContext" : { + "className" : { + "_0" : "PolygonReference" + } + } + } + ], + "name" : "PolygonReference", + "properties" : [ + + ], + "swiftCallName" : "PolygonReference" + }, + { + "constructor" : { + "abiName" : "bjs_TagReference_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "underlying", + "name" : "underlying", + "type" : { + "alias" : { + "name" : "Tag", + "underlying" : { + "swiftHeapObject" : { + "_0" : "TagReference" + } + } + } + } + } + ] + }, + "methods" : [ + + ], + "name" : "TagReference", + "properties" : [ + + ], + "swiftCallName" : "TagReference" + } + ], + "enums" : [ + { + "cases" : [ + { + "associatedValues" : [ + { + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "name" : "payload" + }, + { + "associatedValues" : [ + + ], + "name" : "empty" + } + ], + "emitStyle" : "const", + "name" : "InnerTag", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "InnerTag", + "tsFullPath" : "InnerTag" + } + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_roundtripPolygon", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripPolygon", + "parameters" : [ + { + "label" : "_", + "name" : "polygon", + "type" : { + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } + } + } + } + ], + "returnType" : { + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } + } + } + }, + { + "abiName" : "bjs_optionalPolygon", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "optionalPolygon", + "parameters" : [ + { + "label" : "_", + "name" : "polygon", + "type" : { + "nullable" : { + "_0" : { + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_polygonArray", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "polygonArray", + "parameters" : [ + { + "label" : "_", + "name" : "polygons", + "type" : { + "array" : { + "_0" : { + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } + } + } + } + } + }, + { + "abiName" : "bjs_validatePolygon", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "validatePolygon", + "parameters" : [ + { + "label" : "_", + "name" : "polygon", + "type" : { + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } + } + } + } + ], + "returnType" : { + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } + } + } + }, + { + "abiName" : "bjs_makeTag", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "makeTag", + "parameters" : [ + { + "label" : "_", + "name" : "name", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "alias" : { + "name" : "Tag", + "underlying" : { + "swiftHeapObject" : { + "_0" : "TagReference" + } + } + } + } + }, + { + "abiName" : "bjs_roundtripTags", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripTags", + "parameters" : [ + { + "label" : "_", + "name" : "xs", + "type" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "alias" : { + "name" : "AliasedTag", + "underlying" : { + "associatedValueEnum" : { + "_0" : "InnerTag" + } + } + } + }, + "_1" : "null" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "alias" : { + "name" : "AliasedTag", + "underlying" : { + "associatedValueEnum" : { + "_0" : "InnerTag" + } + } + } + }, + "_1" : "null" + } + } + } + } + }, + { + "abiName" : "bjs_describeUser", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "describeUser", + "parameters" : [ + { + "label" : "_", + "name" : "owner", + "type" : { + "swiftProtocol" : { + "_0" : "HasOptionalUserId" + } + } + } + ], + "returnType" : { + "swiftProtocol" : { + "_0" : "HasOptionalUserId" + } + } + } + ], + "protocols" : [ + { + "methods" : [ + + ], + "name" : "HasOptionalUserId", + "properties" : [ + { + "isReadonly" : true, + "name" : "userId", + "type" : { + "nullable" : { + "_0" : { + "alias" : { + "name" : "UserId", + "underlying" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + }, + "_1" : "null" + } + } + } + ] + } + ], + "structs" : [ + + ] + }, + "imported" : { + "children" : [ + { + "functions" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "acceptTagged", + "parameters" : [ + { + "name" : "tagged", + "type" : { + "alias" : { + "name" : "Tagged", + "underlying" : { + "string" : { + + } + } + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "acceptOptionalTagged", + "parameters" : [ + { + "name" : "tagged", + "type" : { + "nullable" : { + "_0" : { + "alias" : { + "name" : "Tagged", + "underlying" : { + "string" : { + + } + } + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "roundtripTagged", + "parameters" : [ + { + "name" : "tagged", + "type" : { + "alias" : { + "name" : "Tagged", + "underlying" : { + "string" : { + + } + } + } + } + } + ], + "returnType" : { + "alias" : { + "name" : "Tagged", + "underlying" : { + "string" : { + + } + } + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "produceOptionalCanvas", + "parameters" : [ + + ], + "returnType" : { + "nullable" : { + "_0" : { + "alias" : { + "name" : "Canvas", + "underlying" : { + "jsObject" : { + "_0" : "Surface" + } + } + } + }, + "_1" : "null" + } + } + } + ], + "types" : [ + { + "accessLevel" : "internal", + "constructor" : { + "accessLevel" : "internal", + "parameters" : [ + + ] + }, + "getters" : [ + { + "accessLevel" : "internal", + "name" : "label", + "type" : { + "string" : { + + } + } + } + ], + "methods" : [ + + ], + "name" : "Surface", + "setters" : [ + + ], + "staticMethods" : [ + + ] + } + ] + } + ] + }, + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.swift new file mode 100644 index 000000000..1a31905f3 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.swift @@ -0,0 +1,389 @@ +struct AnyHasOptionalUserId: HasOptionalUserId, _BridgedSwiftProtocolWrapper { + let jsObject: JSObject + + var userId: Optional { + get { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + bjs_HasOptionalUserId_userId_get(jsObjectValue) + return Optional.bridgeJSLiftReturnFromSideChannel().map { UserId.bridgeFromJS($0) } + } + } + + static func bridgeJSLiftParameter(_ value: Int32) -> Self { + return AnyHasOptionalUserId(jsObject: JSObject(id: UInt32(bitPattern: value))) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_HasOptionalUserId_userId_get") +fileprivate func bjs_HasOptionalUserId_userId_get_extern(_ jsObject: Int32) -> Void +#else +fileprivate func bjs_HasOptionalUserId_userId_get_extern(_ jsObject: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_HasOptionalUserId_userId_get(_ jsObject: Int32) -> Void { + return bjs_HasOptionalUserId_userId_get_extern(jsObject) +} + +extension InnerTag: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> InnerTag { + switch caseId { + case 0: + return .payload(Int.bridgeJSStackPop()) + case 1: + return .empty + default: + fatalError("Unknown InnerTag case ID: \(caseId)") + } + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { + switch self { + case .payload(let param0): + param0.bridgeJSStackPush() + return Int32(0) + case .empty: + return Int32(1) + } + } +} + +@_expose(wasm, "bjs_roundtripPolygon") +@_cdecl("bjs_roundtripPolygon") +public func _bjs_roundtripPolygon(_ polygon: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = roundtripPolygon(_: Polygon.bridgeFromJS(PolygonReference.bridgeJSLiftParameter(polygon))) + return ret.bridgeToJS().bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_optionalPolygon") +@_cdecl("bjs_optionalPolygon") +public func _bjs_optionalPolygon(_ polygonIsSome: Int32, _ polygonValue: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = optionalPolygon(_: Optional.bridgeJSLiftParameter(polygonIsSome, polygonValue).map { Polygon.bridgeFromJS($0) }) + return ret.map { $0.bridgeToJS() }.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_polygonArray") +@_cdecl("bjs_polygonArray") +public func _bjs_polygonArray() -> Void { + #if arch(wasm32) + let ret = polygonArray(_: [PolygonReference].bridgeJSStackPop().map { Polygon.bridgeFromJS($0) }) + ret.map { $0.bridgeToJS() }.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_validatePolygon") +@_cdecl("bjs_validatePolygon") +public func _bjs_validatePolygon(_ polygon: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + #if arch(wasm32) + do { + let ret = try validatePolygon(_: Polygon.bridgeFromJS(PolygonReference.bridgeJSLiftParameter(polygon))) + return ret.bridgeToJS().bridgeJSLowerReturn() + } catch let error { + if let error = error.thrownValue.object { + withExtendedLifetime(error) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } else { + let jsError = JSError(message: String(describing: error)) + withExtendedLifetime(jsError.jsObject) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } + return UnsafeMutableRawPointer(bitPattern: -1).unsafelyUnwrapped + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_makeTag") +@_cdecl("bjs_makeTag") +public func _bjs_makeTag(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = makeTag(_: String.bridgeJSLiftParameter(nameBytes, nameLength)) + return ret.bridgeToJS().bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundtripTags") +@_cdecl("bjs_roundtripTags") +public func _bjs_roundtripTags() -> Void { + #if arch(wasm32) + let ret = roundtripTags(_: [Optional].bridgeJSStackPop().map { $0.map { AliasedTag.bridgeFromJS($0) } }) + ret.map { $0.map { $0.bridgeToJS() } }.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_describeUser") +@_cdecl("bjs_describeUser") +public func _bjs_describeUser(_ owner: Int32) -> Int32 { + #if arch(wasm32) + let ret = describeUser(_: AnyHasOptionalUserId.bridgeJSLiftParameter(owner)) as! _BridgedSwiftProtocolExportable + return ret.bridgeJSLowerAsProtocolReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_PolygonReference_init") +@_cdecl("bjs_PolygonReference_init") +public func _bjs_PolygonReference_init(_ underlying: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = PolygonReference(underlying: Polygon.bridgeFromJS(PolygonReference.bridgeJSLiftParameter(underlying))) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_PolygonReference_snapshot") +@_cdecl("bjs_PolygonReference_snapshot") +public func _bjs_PolygonReference_snapshot(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = PolygonReference.bridgeJSLiftParameter(_self).snapshot() + return ret.bridgeToJS().bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_PolygonReference_merge") +@_cdecl("bjs_PolygonReference_merge") +public func _bjs_PolygonReference_merge(_ _self: UnsafeMutableRawPointer, _ other: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = PolygonReference.bridgeJSLiftParameter(_self).merge(_: Polygon.bridgeFromJS(PolygonReference.bridgeJSLiftParameter(other))) + return ret.bridgeToJS().bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_PolygonReference_static_origin") +@_cdecl("bjs_PolygonReference_static_origin") +public func _bjs_PolygonReference_static_origin() -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = PolygonReference.origin() + return ret.bridgeToJS().bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_PolygonReference_deinit") +@_cdecl("bjs_PolygonReference_deinit") +public func _bjs_PolygonReference_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension PolygonReference: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_PolygonReference_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_PolygonReference_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_PolygonReference_wrap") +fileprivate func _bjs_PolygonReference_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_PolygonReference_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_PolygonReference_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_PolygonReference_wrap_extern(pointer) +} + +@_expose(wasm, "bjs_TagReference_init") +@_cdecl("bjs_TagReference_init") +public func _bjs_TagReference_init(_ underlying: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = TagReference(underlying: Tag.bridgeFromJS(TagReference.bridgeJSLiftParameter(underlying))) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_TagReference_deinit") +@_cdecl("bjs_TagReference_deinit") +public func _bjs_TagReference_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension TagReference: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_TagReference_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_TagReference_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_TagReference_wrap") +fileprivate func _bjs_TagReference_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_TagReference_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_TagReference_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_TagReference_wrap_extern(pointer) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_acceptTagged") +fileprivate func bjs_acceptTagged_extern(_ taggedBytes: Int32, _ taggedLength: Int32) -> Void +#else +fileprivate func bjs_acceptTagged_extern(_ taggedBytes: Int32, _ taggedLength: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_acceptTagged(_ taggedBytes: Int32, _ taggedLength: Int32) -> Void { + return bjs_acceptTagged_extern(taggedBytes, taggedLength) +} + +func _$acceptTagged(_ tagged: Tagged) throws(JSException) -> Void { + tagged.bridgeToJS().bridgeJSWithLoweredParameter { (taggedBytes, taggedLength) in + bjs_acceptTagged(taggedBytes, taggedLength) + } + if let error = _swift_js_take_exception() { + throw error + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_acceptOptionalTagged") +fileprivate func bjs_acceptOptionalTagged_extern(_ taggedIsSome: Int32, _ taggedBytes: Int32, _ taggedLength: Int32) -> Void +#else +fileprivate func bjs_acceptOptionalTagged_extern(_ taggedIsSome: Int32, _ taggedBytes: Int32, _ taggedLength: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_acceptOptionalTagged(_ taggedIsSome: Int32, _ taggedBytes: Int32, _ taggedLength: Int32) -> Void { + return bjs_acceptOptionalTagged_extern(taggedIsSome, taggedBytes, taggedLength) +} + +func _$acceptOptionalTagged(_ tagged: Optional) throws(JSException) -> Void { + tagged.map { + $0.bridgeToJS() + } .bridgeJSWithLoweredParameter { (taggedIsSome, taggedBytes, taggedLength) in + bjs_acceptOptionalTagged(taggedIsSome, taggedBytes, taggedLength) + } + if let error = _swift_js_take_exception() { + throw error + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_roundtripTagged") +fileprivate func bjs_roundtripTagged_extern(_ taggedBytes: Int32, _ taggedLength: Int32) -> Int32 +#else +fileprivate func bjs_roundtripTagged_extern(_ taggedBytes: Int32, _ taggedLength: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_roundtripTagged(_ taggedBytes: Int32, _ taggedLength: Int32) -> Int32 { + return bjs_roundtripTagged_extern(taggedBytes, taggedLength) +} + +func _$roundtripTagged(_ tagged: Tagged) throws(JSException) -> Tagged { + let ret0 = tagged.bridgeToJS().bridgeJSWithLoweredParameter { (taggedBytes, taggedLength) in + let ret = bjs_roundtripTagged(taggedBytes, taggedLength) + return ret + } + let ret = ret0 + if let error = _swift_js_take_exception() { + throw error + } + return Tagged.bridgeFromJS(String.bridgeJSLiftReturn(ret)) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_produceOptionalCanvas") +fileprivate func bjs_produceOptionalCanvas_extern() -> Void +#else +fileprivate func bjs_produceOptionalCanvas_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_produceOptionalCanvas() -> Void { + return bjs_produceOptionalCanvas_extern() +} + +func _$produceOptionalCanvas() throws(JSException) -> Optional { + bjs_produceOptionalCanvas() + if let error = _swift_js_take_exception() { + throw error + } + return Optional.bridgeJSLiftReturn().map { + Canvas.bridgeFromJS($0) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_Surface_init") +fileprivate func bjs_Surface_init_extern() -> Int32 +#else +fileprivate func bjs_Surface_init_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_Surface_init() -> Int32 { + return bjs_Surface_init_extern() +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_Surface_label_get") +fileprivate func bjs_Surface_label_get_extern(_ self: Int32) -> Int32 +#else +fileprivate func bjs_Surface_label_get_extern(_ self: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_Surface_label_get(_ self: Int32) -> Int32 { + return bjs_Surface_label_get_extern(self) +} + +func _$Surface_init() throws(JSException) -> JSObject { + let ret = bjs_Surface_init() + if let error = _swift_js_take_exception() { + throw error + } + return JSObject.bridgeJSLiftReturn(ret) +} + +func _$Surface_label_get(_ self: JSObject) throws(JSException) -> String { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_Surface_label_get(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.json new file mode 100644 index 000000000..d76761e0b --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.json @@ -0,0 +1,145 @@ +{ + "exported" : { + "aliases" : [ + { + "swiftCallName" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } + } + ], + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_PolygonReference_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "sides", + "name" : "sides", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ] + }, + "methods" : [ + + ], + "name" : "PolygonReference", + "properties" : [ + + ], + "swiftCallName" : "PolygonReference" + } + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_makePolygonFactory", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "makePolygonFactory", + "parameters" : [ + + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuley_Al7Polygon", + "moduleName" : "TestModule", + "parameters" : [ + + ], + "returnType" : { + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false + } + } + }, + { + "abiName" : "bjs_makePolygonInspector", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "makePolygonInspector", + "parameters" : [ + + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModuleAl7Polygon_Si", + "moduleName" : "TestModule", + "parameters" : [ + { + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.swift new file mode 100644 index 000000000..3613ead7e --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.swift @@ -0,0 +1,188 @@ +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleAl7Polygon_Si") +fileprivate func invoke_js_callback_TestModule_10TestModuleAl7Polygon_Si_extern(_ callback: Int32, _ param0: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func invoke_js_callback_TestModule_10TestModuleAl7Polygon_Si_extern(_ callback: Int32, _ param0: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleAl7Polygon_Si(_ callback: Int32, _ param0: UnsafeMutableRawPointer) -> Int32 { + return invoke_js_callback_TestModule_10TestModuleAl7Polygon_Si_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModuleAl7Polygon_Si") +fileprivate func make_swift_closure_TestModule_10TestModuleAl7Polygon_Si_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModuleAl7Polygon_Si_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModuleAl7Polygon_Si(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModuleAl7Polygon_Si_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModuleAl7Polygon_Si { + static func bridgeJSLift(_ callbackId: Int32) -> (Polygon) -> Int { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let param0Pointer = param0.bridgeToJS().bridgeJSLowerParameter() + let ret = invoke_js_callback_TestModule_10TestModuleAl7Polygon_Si(callbackValue, param0Pointer) + return Int.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (Polygon) -> Int { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Polygon) -> Int) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModuleAl7Polygon_Si, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuleAl7Polygon_Si") +@_cdecl("invoke_swift_closure_TestModule_10TestModuleAl7Polygon_Si") +public func _invoke_swift_closure_TestModule_10TestModuleAl7Polygon_Si(_ boxPtr: UnsafeMutableRawPointer, _ param0: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Polygon) -> Int>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Polygon.bridgeFromJS(PolygonReference.bridgeJSLiftParameter(param0))) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuley_Al7Polygon") +fileprivate func invoke_js_callback_TestModule_10TestModuley_Al7Polygon_extern(_ callback: Int32) -> UnsafeMutableRawPointer +#else +fileprivate func invoke_js_callback_TestModule_10TestModuley_Al7Polygon_extern(_ callback: Int32) -> UnsafeMutableRawPointer { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuley_Al7Polygon(_ callback: Int32) -> UnsafeMutableRawPointer { + return invoke_js_callback_TestModule_10TestModuley_Al7Polygon_extern(callback) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModuley_Al7Polygon") +fileprivate func make_swift_closure_TestModule_10TestModuley_Al7Polygon_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModuley_Al7Polygon_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModuley_Al7Polygon(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModuley_Al7Polygon_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModuley_Al7Polygon { + static func bridgeJSLift(_ callbackId: Int32) -> () -> Polygon { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let ret = invoke_js_callback_TestModule_10TestModuley_Al7Polygon(callbackValue) + return Polygon.bridgeFromJS(PolygonReference.bridgeJSLiftReturn(ret)) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == () -> Polygon { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping () -> Polygon) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModuley_Al7Polygon, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModuley_Al7Polygon") +@_cdecl("invoke_swift_closure_TestModule_10TestModuley_Al7Polygon") +public func _invoke_swift_closure_TestModule_10TestModuley_Al7Polygon(_ boxPtr: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<() -> Polygon>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure() + return result.bridgeToJS().bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_makePolygonFactory") +@_cdecl("bjs_makePolygonFactory") +public func _bjs_makePolygonFactory() -> Int32 { + #if arch(wasm32) + let ret = makePolygonFactory() + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_makePolygonInspector") +@_cdecl("bjs_makePolygonInspector") +public func _bjs_makePolygonInspector() -> Int32 { + #if arch(wasm32) + let ret = makePolygonInspector() + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_PolygonReference_init") +@_cdecl("bjs_PolygonReference_init") +public func _bjs_PolygonReference_init(_ sides: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = PolygonReference(sides: Int.bridgeJSLiftParameter(sides)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_PolygonReference_deinit") +@_cdecl("bjs_PolygonReference_deinit") +public func _bjs_PolygonReference_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension PolygonReference: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_PolygonReference_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_PolygonReference_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_PolygonReference_wrap") +fileprivate func _bjs_PolygonReference_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_PolygonReference_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_PolygonReference_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_PolygonReference_wrap_extern(pointer) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.json index d4ac7a15f..0fac3bf21 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ { "methods" : [ diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.json index 8684291f0..41cbc5017 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ ], diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.json index 4c8d575b0..bfa71444c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtension.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ { "constructor" : { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.ReverseOrder.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.ReverseOrder.json index 6c589de87..053757256 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.ReverseOrder.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.ReverseOrder.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ { "constructor" : { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.json index 9bec040f1..41aa858ac 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileFunctionTypes.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ { "constructor" : { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.ReverseOrder.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.ReverseOrder.json index edf8177c1..49d656dcd 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.ReverseOrder.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.ReverseOrder.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ { "methods" : [ diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.json index 58bfadab7..377e875bd 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileTypeResolution.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ { "constructor" : { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.json index e7874c072..40e3672b7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ { "constructor" : { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.json index b1185c644..6830240eb 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ { "methods" : [ diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAlias.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAlias.json new file mode 100644 index 000000000..0d63db899 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAlias.json @@ -0,0 +1,96 @@ +{ + "exported" : { + "aliases" : [ + { + "swiftCallName" : "Color", + "underlying" : { + "swiftHeapObject" : { + "_0" : "ColorBox" + } + } + } + ], + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_ColorBox_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "name", + "name" : "name", + "type" : { + "string" : { + + } + } + } + ] + }, + "methods" : [ + + ], + "name" : "ColorBox", + "properties" : [ + + ], + "swiftCallName" : "ColorBox" + } + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_roundtripColor", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundtripColor", + "parameters" : [ + { + "label" : "_", + "name" : "color", + "type" : { + "alias" : { + "name" : "Color", + "underlying" : { + "swiftHeapObject" : { + "_0" : "ColorBox" + } + } + } + } + } + ], + "returnType" : { + "alias" : { + "name" : "Color", + "underlying" : { + "swiftHeapObject" : { + "_0" : "ColorBox" + } + } + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAlias.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAlias.swift new file mode 100644 index 000000000..615110c90 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAlias.swift @@ -0,0 +1,52 @@ +@_expose(wasm, "bjs_roundtripColor") +@_cdecl("bjs_roundtripColor") +public func _bjs_roundtripColor(_ color: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = roundtripColor(_: Color.bridgeFromJS(ColorBox.bridgeJSLiftParameter(color))) + return ret.bridgeToJS().bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ColorBox_init") +@_cdecl("bjs_ColorBox_init") +public func _bjs_ColorBox_init(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = ColorBox(name: String.bridgeJSLiftParameter(nameBytes, nameLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ColorBox_deinit") +@_cdecl("bjs_ColorBox_deinit") +public func _bjs_ColorBox_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension ColorBox: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_ColorBox_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_ColorBox_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_ColorBox_wrap") +fileprivate func _bjs_ColorBox_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_ColorBox_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_ColorBox_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_ColorBox_wrap_extern(pointer) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.json index 873c5c49f..39b9d7211 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ { "methods" : [ diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCase.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCase.json index c4095b502..8fbb08f28 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCase.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCase.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ ], diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.json index 103a67999..be74590c6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ { "constructor" : { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.json index f9890d36b..175c4fa03 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ { "constructor" : { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.json index 1cf99cd39..2adb178a3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ ], diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/FixedWidthIntegers.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/FixedWidthIntegers.json index 1186ad27d..0844c7475 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/FixedWidthIntegers.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/FixedWidthIntegers.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ ], diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/IdentityModeClass.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/IdentityModeClass.json index f4a4440c6..bca32c30d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/IdentityModeClass.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/IdentityModeClass.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ { "constructor" : { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.json index 600ae8c89..e4d10d07b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ ], diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSTypedArrayTypes.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSTypedArrayTypes.json index a7b9c8623..5d4425096 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSTypedArrayTypes.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSTypedArrayTypes.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ ], diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSValue.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSValue.json index f0cd29565..eba5d34fb 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSValue.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSValue.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ { "constructor" : { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedGlobal.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedGlobal.json index 0d30063ee..05279a762 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedGlobal.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedGlobal.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ { "constructor" : { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedPrivate.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedPrivate.json index e6bcf2e5c..0f46b4ddb 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedPrivate.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/MixedPrivate.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ { "constructor" : { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.json index ef9e0b758..243f3c885 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.Global.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ { "constructor" : { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.json index 397d1123c..7823e5fdc 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Namespaces.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ { "constructor" : { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedType.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedType.json index f924b3eba..c741304a7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedType.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedType.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ { "methods" : [ diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.json index e9d78cbbc..d86d06f86 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ { "constructor" : { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveParameters.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveParameters.json index 320499ff3..8b7ee7338 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveParameters.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveParameters.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ ], diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveReturn.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveReturn.json index 414fedbbd..a2b08f4c6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveReturn.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveReturn.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ ], diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PropertyTypes.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PropertyTypes.json index 281538dd6..8e6496336 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PropertyTypes.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PropertyTypes.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ { "constructor" : { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.json index feca4615b..bc443c6c0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ { "constructor" : { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.json index 70273f8b3..56f8e26e0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ { "constructor" : { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.json index 800018440..c023fd8ab 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ { "constructor" : { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.json index 36110488c..c80a6bb3e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ { "constructor" : { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.json index 1cbe44619..7935c2aa1 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ { "constructor" : { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.json index 8fc0667b0..35a94cddd 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ { "constructor" : { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringParameter.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringParameter.json index d9dc0ec43..68b13c0b0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringParameter.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringParameter.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ ], diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringReturn.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringReturn.json index e2cf9ffac..f1e2ccbfd 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringReturn.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StringReturn.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ ], diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json index a3ddab63e..e1bb767c1 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClass.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ { "constructor" : { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.json index b1e306c07..0085dd6c4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ { "constructor" : { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json index bfde01318..d1a4b6882 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ { "constructor" : { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.json index a9b0d22bf..ba5aa11de 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ ], diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Throws.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Throws.json index 942e5fb45..0e45eefca 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Throws.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Throws.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ ], diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/UnsafePointer.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/UnsafePointer.json index a382778e9..1b1a1088b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/UnsafePointer.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/UnsafePointer.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ ], diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/VoidParameterVoidReturn.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/VoidParameterVoidReturn.json index d31f775fb..4fef14d6a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/VoidParameterVoidReturn.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/VoidParameterVoidReturn.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ ], diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.d.ts new file mode 100644 index 000000000..3ee338254 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.d.ts @@ -0,0 +1,71 @@ +// 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`. + +export interface HasOptionalUserId { + readonly userId: number | null; +} + +export const InnerTagValues: { + readonly Tag: { + readonly Payload: 0; + readonly Empty: 1; + }; +}; + +export type InnerTagTag = + { tag: typeof InnerTagValues.Tag.Payload; param0: number } | { tag: typeof InnerTagValues.Tag.Empty } + +export type InnerTagObject = typeof InnerTagValues; + +/// Represents a Swift heap object like a class instance or an actor instance. +export interface SwiftHeapObject { + /// Release the heap object. + /// + /// Note: Calling this method will release the heap object and it will no longer be accessible. + release(): void; +} +export interface PolygonReference extends SwiftHeapObject { + snapshot(): PolygonReference; + merge(other: PolygonReference): PolygonReference; +} +export interface TagReference extends SwiftHeapObject { +} +export interface Surface { + readonly label: string; +} +export type Exports = { + PolygonReference: { + new(underlying: PolygonReference): PolygonReference; + origin(): PolygonReference; + } + TagReference: { + new(underlying: TagReference): TagReference; + } + roundtripPolygon(polygon: PolygonReference): PolygonReference; + optionalPolygon(polygon: PolygonReference | null): PolygonReference | null; + polygonArray(polygons: PolygonReference[]): PolygonReference[]; + validatePolygon(polygon: PolygonReference): PolygonReference; + makeTag(name: string): TagReference; + roundtripTags(xs: (InnerTagTag | null)[]): (InnerTagTag | null)[]; + describeUser(owner: HasOptionalUserId): HasOptionalUserId; + InnerTag: InnerTagObject +} +export type Imports = { + acceptTagged(tagged: string): void; + acceptOptionalTagged(tagged: string | null): void; + roundtripTagged(tagged: string): string; + produceOptionalCanvas(): Surface | null; + Surface: { + new(): Surface; + } +} +export function createInstantiator(options: { + imports: Imports; +}, swift: any): Promise<{ + addImports: (importObject: WebAssembly.Imports) => void; + setInstance: (instance: WebAssembly.Instance) => void; + createExports: (instance: WebAssembly.Instance) => Exports; +}>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js new file mode 100644 index 000000000..c55e429d5 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js @@ -0,0 +1,517 @@ +// 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`. + +export const InnerTagValues = { + Tag: { + Payload: 0, + Empty: 1, + }, +}; +export async function createInstantiator(options, swift) { + let instance; + let memory; + let setException; + let decodeString; + const textDecoder = new TextDecoder("utf-8"); + const textEncoder = new TextEncoder("utf-8"); + let tmpRetString; + let tmpRetBytes; + let tmpRetException; + let tmpRetOptionalBool; + let tmpRetOptionalInt; + let tmpRetOptionalFloat; + let tmpRetOptionalDouble; + let tmpRetOptionalHeapObject; + let strStack = []; + let i32Stack = []; + let i64Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; + let taStack = []; + const enumHelpers = {}; + const structHelpers = {}; + + let _exports = null; + let bjs = null; + const __bjs_createInnerTagValuesHelpers = () => ({ + lower: (value) => { + const enumTag = value.tag; + switch (enumTag) { + case InnerTagValues.Tag.Payload: { + i32Stack.push((value.param0 | 0)); + return InnerTagValues.Tag.Payload; + } + case InnerTagValues.Tag.Empty: { + return InnerTagValues.Tag.Empty; + } + default: throw new Error("Unknown InnerTagValues tag: " + String(enumTag)); + } + }, + lift: (tag) => { + tag = tag | 0; + switch (tag) { + case InnerTagValues.Tag.Payload: { + const int = i32Stack.pop(); + return { tag: InnerTagValues.Tag.Payload, param0: int }; + } + case InnerTagValues.Tag.Empty: return { tag: InnerTagValues.Tag.Empty }; + default: throw new Error("Unknown InnerTagValues tag returned from Swift: " + String(tag)); + } + } + }); + + return { + /** + * @param {WebAssembly.Imports} importObject + */ + addImports: (importObject, importsContext) => { + bjs = {}; + importObject["bjs"] = bjs; + const imports = options.getImports(importsContext); + bjs["swift_js_return_string"] = function(ptr, len) { + tmpRetString = decodeString(ptr, len); + } + bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { + const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); + const bytes = new Uint8Array(memory.buffer, bytesPtr); + bytes.set(source); + } + bjs["swift_js_make_js_string"] = function(ptr, len) { + return swift.memory.retain(decodeString(ptr, len)); + } + bjs["swift_js_init_memory_with_result"] = function(ptr, len) { + const target = new Uint8Array(memory.buffer, ptr, len); + target.set(tmpRetBytes); + tmpRetBytes = undefined; + } + bjs["swift_js_throw"] = function(id) { + tmpRetException = swift.memory.retainByRef(id); + } + bjs["swift_js_retain"] = function(id) { + return swift.memory.retainByRef(id); + } + bjs["swift_js_release"] = function(id) { + swift.memory.release(id); + } + bjs["swift_js_push_i32"] = function(v) { + i32Stack.push(v | 0); + } + bjs["swift_js_push_f32"] = function(v) { + f32Stack.push(Math.fround(v)); + } + bjs["swift_js_push_f64"] = function(v) { + f64Stack.push(v); + } + bjs["swift_js_push_string"] = function(ptr, len) { + const value = decodeString(ptr, len); + strStack.push(value); + } + bjs["swift_js_pop_i32"] = function() { + return i32Stack.pop(); + } + bjs["swift_js_pop_f32"] = function() { + return f32Stack.pop(); + } + bjs["swift_js_pop_f64"] = function() { + return f64Stack.pop(); + } + bjs["swift_js_push_pointer"] = function(pointer) { + ptrStack.push(pointer); + } + bjs["swift_js_pop_pointer"] = function() { + return ptrStack.pop(); + } + bjs["swift_js_push_i64"] = function(v) { + i64Stack.push(v); + } + bjs["swift_js_pop_i64"] = function() { + return i64Stack.pop(); + } + const taCtors = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array]; + bjs["swift_js_push_typed_array"] = function(kind, ptr, count) { + const Ctor = taCtors[kind]; + const byteLen = count * Ctor.BYTES_PER_ELEMENT; + const copy = memory.buffer.slice(ptr, ptr + byteLen); + taStack.push(Array.from(new Ctor(copy))); + } + bjs["swift_js_return_optional_bool"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalBool = null; + } else { + tmpRetOptionalBool = value !== 0; + } + } + bjs["swift_js_return_optional_int"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalInt = null; + } else { + tmpRetOptionalInt = value | 0; + } + } + bjs["swift_js_return_optional_float"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalFloat = null; + } else { + tmpRetOptionalFloat = Math.fround(value); + } + } + bjs["swift_js_return_optional_double"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalDouble = null; + } else { + tmpRetOptionalDouble = value; + } + } + bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = decodeString(ptr, len); + } + } + bjs["swift_js_return_optional_object"] = function(isSome, objectId) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = swift.memory.getObject(objectId); + } + } + bjs["swift_js_return_optional_heap_object"] = function(isSome, pointer) { + if (isSome === 0) { + tmpRetOptionalHeapObject = null; + } else { + tmpRetOptionalHeapObject = pointer; + } + } + bjs["swift_js_get_optional_int_presence"] = function() { + return tmpRetOptionalInt != null ? 1 : 0; + } + bjs["swift_js_get_optional_int_value"] = function() { + const value = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; + return value; + } + bjs["swift_js_get_optional_string"] = function() { + const str = tmpRetString; + tmpRetString = undefined; + if (str == null) { + return -1; + } else { + const bytes = textEncoder.encode(str); + tmpRetBytes = bytes; + return bytes.length; + } + } + bjs["swift_js_get_optional_float_presence"] = function() { + return tmpRetOptionalFloat != null ? 1 : 0; + } + bjs["swift_js_get_optional_float_value"] = function() { + const value = tmpRetOptionalFloat; + tmpRetOptionalFloat = undefined; + return value; + } + bjs["swift_js_get_optional_double_presence"] = function() { + return tmpRetOptionalDouble != null ? 1 : 0; + } + bjs["swift_js_get_optional_double_value"] = function() { + const value = tmpRetOptionalDouble; + tmpRetOptionalDouble = undefined; + return value; + } + bjs["swift_js_get_optional_heap_object_pointer"] = function() { + const pointer = tmpRetOptionalHeapObject; + tmpRetOptionalHeapObject = undefined; + return pointer || 0; + } + bjs["swift_js_closure_unregister"] = function(funcRef) {} + // Wrapper functions for module: TestModule + if (!importObject["TestModule"]) { + importObject["TestModule"] = {}; + } + importObject["TestModule"]["bjs_PolygonReference_wrap"] = function(pointer) { + const obj = _exports['PolygonReference'].__construct(pointer); + return swift.memory.retain(obj); + }; + importObject["TestModule"]["bjs_TagReference_wrap"] = function(pointer) { + const obj = _exports['TagReference'].__construct(pointer); + return swift.memory.retain(obj); + }; + const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; + TestModule["bjs_acceptTagged"] = function bjs_acceptTagged(taggedBytes, taggedCount) { + try { + const string = decodeString(taggedBytes, taggedCount); + imports.acceptTagged(string); + } catch (error) { + setException(error); + } + } + TestModule["bjs_acceptOptionalTagged"] = function bjs_acceptOptionalTagged(taggedIsSome, taggedBytes, taggedCount) { + try { + let optResult; + if (taggedIsSome) { + const string = decodeString(taggedBytes, taggedCount); + optResult = string; + } else { + optResult = null; + } + imports.acceptOptionalTagged(optResult); + } catch (error) { + setException(error); + } + } + TestModule["bjs_roundtripTagged"] = function bjs_roundtripTagged(taggedBytes, taggedCount) { + try { + const string = decodeString(taggedBytes, taggedCount); + let ret = imports.roundtripTagged(string); + tmpRetBytes = textEncoder.encode(ret); + return tmpRetBytes.length; + } catch (error) { + setException(error); + } + } + TestModule["bjs_produceOptionalCanvas"] = function bjs_produceOptionalCanvas() { + try { + let ret = imports.produceOptionalCanvas(); + const isSome = ret != null; + if (isSome) { + const objId = swift.memory.retain(ret); + i32Stack.push(objId); + } + i32Stack.push(isSome ? 1 : 0); + } catch (error) { + setException(error); + } + } + TestModule["bjs_Surface_init"] = function bjs_Surface_init() { + try { + return swift.memory.retain(new imports.Surface()); + } catch (error) { + setException(error); + return 0 + } + } + TestModule["bjs_Surface_label_get"] = function bjs_Surface_label_get(self) { + try { + let ret = swift.memory.getObject(self).label; + tmpRetBytes = textEncoder.encode(ret); + return tmpRetBytes.length; + } catch (error) { + setException(error); + } + } + TestModule["bjs_HasOptionalUserId_userId_get"] = function bjs_HasOptionalUserId_userId_get(self) { + try { + let ret = swift.memory.getObject(self).userId; + tmpRetOptionalInt = ret; + } catch (error) { + setException(error); + } + } + }, + setInstance: (i) => { + instance = i; + memory = instance.exports.memory; + + decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + + setException = (error) => { + instance.exports._swift_js_exception.value = swift.memory.retain(error) + } + }, + /** @param {WebAssembly.Instance} instance */ + createExports: (instance) => { + const js = swift.memory.heap; + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.identityMap?.delete(state.pointer); + state.deinit(state.pointer); + }); + + /// Represents a Swift heap object like a class instance or an actor instance. + class SwiftHeapObject { + static __wrap(pointer, deinit, prototype, identityCache) { + const makeFresh = (identityMap) => { + const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false, identityMap }; + obj.pointer = pointer; + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); + if (identityMap) { + identityMap.set(pointer, new WeakRef(obj)); + } + return obj; + }; + + if (!identityCache) { + return makeFresh(null); + } + + const cached = identityCache.get(pointer)?.deref(); + if (cached && !cached.__swiftHeapObjectState.hasReleased) { + deinit(pointer); + return cached; + } + if (identityCache.has(pointer)) { + identityCache.delete(pointer); + } + + return makeFresh(identityCache); + } + + release() { + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.identityMap?.delete(state.pointer); + state.deinit(state.pointer); + } + } + class PolygonReference extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_PolygonReference_deinit, PolygonReference.prototype, null); + } + + constructor(underlying) { + const ret = instance.exports.bjs_PolygonReference_init(underlying.pointer); + return PolygonReference.__construct(ret); + } + snapshot() { + const ret = instance.exports.bjs_PolygonReference_snapshot(this.pointer); + return PolygonReference.__construct(ret); + } + merge(other) { + const ret = instance.exports.bjs_PolygonReference_merge(this.pointer, other.pointer); + return PolygonReference.__construct(ret); + } + static origin() { + const ret = instance.exports.bjs_PolygonReference_static_origin(); + return PolygonReference.__construct(ret); + } + } + class TagReference extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_TagReference_deinit, TagReference.prototype, null); + } + + constructor(underlying) { + const ret = instance.exports.bjs_TagReference_init(underlying.pointer); + return TagReference.__construct(ret); + } + } + const InnerTagHelpers = __bjs_createInnerTagValuesHelpers(); + enumHelpers.InnerTag = InnerTagHelpers; + + const exports = { + PolygonReference, + TagReference, + roundtripPolygon: function bjs_roundtripPolygon(polygon) { + const ret = instance.exports.bjs_roundtripPolygon(polygon.pointer); + return PolygonReference.__construct(ret); + }, + optionalPolygon: function bjs_optionalPolygon(polygon) { + const isSome = polygon != null; + let result; + if (isSome) { + result = polygon.pointer; + } else { + result = 0; + } + instance.exports.bjs_optionalPolygon(+isSome, result); + const pointer = tmpRetOptionalHeapObject; + tmpRetOptionalHeapObject = undefined; + const optResult = pointer === null ? null : PolygonReference.__construct(pointer); + return optResult; + }, + polygonArray: function bjs_polygonArray(polygons) { + for (const elem of polygons) { + ptrStack.push(elem.pointer); + } + i32Stack.push(polygons.length); + instance.exports.bjs_polygonArray(); + const arrayLen = i32Stack.pop(); + let arrayResult; + if (arrayLen === -1) { + arrayResult = taStack.pop(); + } else { + arrayResult = []; + for (let i = 0; i < arrayLen; i++) { + const ptr = ptrStack.pop(); + const obj = PolygonReference.__construct(ptr); + arrayResult.push(obj); + } + arrayResult.reverse(); + } + return arrayResult; + }, + validatePolygon: function bjs_validatePolygon(polygon) { + const ret = instance.exports.bjs_validatePolygon(polygon.pointer); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + return PolygonReference.__construct(ret); + }, + makeTag: function bjs_makeTag(name) { + const nameBytes = textEncoder.encode(name); + const nameId = swift.memory.retain(nameBytes); + const ret = instance.exports.bjs_makeTag(nameId, nameBytes.length); + return TagReference.__construct(ret); + }, + roundtripTags: function bjs_roundtripTags(xs) { + for (const elem of xs) { + const isSome = elem != null ? 1 : 0; + if (isSome) { + const caseId = enumHelpers.InnerTag.lower(elem); + i32Stack.push(caseId); + } else { + i32Stack.push(-1); + } + } + i32Stack.push(xs.length); + instance.exports.bjs_roundtripTags(); + const arrayLen = i32Stack.pop(); + let arrayResult; + if (arrayLen === -1) { + arrayResult = taStack.pop(); + } else { + arrayResult = []; + for (let i = 0; i < arrayLen; i++) { + const caseId1 = i32Stack.pop(); + let optValue; + if (caseId1 === -1) { + optValue = null; + } else { + optValue = enumHelpers.InnerTag.lift(caseId1); + } + arrayResult.push(optValue); + } + arrayResult.reverse(); + } + return arrayResult; + }, + describeUser: function bjs_describeUser(owner) { + const ret = instance.exports.bjs_describeUser(swift.memory.retain(owner)); + const ret1 = swift.memory.getObject(ret); + swift.memory.release(ret); + return ret1; + }, + InnerTag: InnerTagValues, + }; + _exports = exports; + return exports; + }, + } +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.d.ts new file mode 100644 index 000000000..f1d5d5fa9 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.d.ts @@ -0,0 +1,31 @@ +// 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`. + +/// Represents a Swift heap object like a class instance or an actor instance. +export interface SwiftHeapObject { + /// Release the heap object. + /// + /// Note: Calling this method will release the heap object and it will no longer be accessible. + release(): void; +} +export interface PolygonReference extends SwiftHeapObject { +} +export type Exports = { + PolygonReference: { + new(sides: number): PolygonReference; + } + makePolygonFactory(): () => PolygonReference; + makePolygonInspector(): (arg0: PolygonReference) => number; +} +export type Imports = { +} +export function createInstantiator(options: { + imports: Imports; +}, swift: any): Promise<{ + addImports: (importObject: WebAssembly.Imports) => void; + setInstance: (instance: WebAssembly.Instance) => void; + createExports: (instance: WebAssembly.Instance) => Exports; +}>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js new file mode 100644 index 000000000..21c96aed6 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js @@ -0,0 +1,372 @@ +// 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`. + +export async function createInstantiator(options, swift) { + let instance; + let memory; + let setException; + let decodeString; + const textDecoder = new TextDecoder("utf-8"); + const textEncoder = new TextEncoder("utf-8"); + let tmpRetString; + let tmpRetBytes; + let tmpRetException; + let tmpRetOptionalBool; + let tmpRetOptionalInt; + let tmpRetOptionalFloat; + let tmpRetOptionalDouble; + let tmpRetOptionalHeapObject; + let strStack = []; + let i32Stack = []; + let i64Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; + let taStack = []; + const enumHelpers = {}; + const structHelpers = {}; + + let _exports = null; + let bjs = null; + const swiftClosureRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.unregistered) { return; } + instance?.exports?.bjs_release_swift_closure(state.pointer); + }); + const makeClosure = (pointer, file, line, func) => { + const state = { pointer, file, line, unregistered: false }; + const real = (...args) => { + if (state.unregistered) { + const bytes = new Uint8Array(memory.buffer, state.file); + let length = 0; + while (bytes[length] !== 0) { length += 1; } + const fileID = decodeString(state.file, length); + throw new Error(`Attempted to call a released JSTypedClosure created at ${fileID}:${state.line}`); + } + return func(...args); + }; + real.__unregister = () => { + if (state.unregistered) { return; } + state.unregistered = true; + swiftClosureRegistry.unregister(state); + }; + swiftClosureRegistry.register(real, state, state); + return swift.memory.retain(real); + }; + + + return { + /** + * @param {WebAssembly.Imports} importObject + */ + addImports: (importObject, importsContext) => { + bjs = {}; + importObject["bjs"] = bjs; + bjs["swift_js_return_string"] = function(ptr, len) { + tmpRetString = decodeString(ptr, len); + } + bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { + const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); + const bytes = new Uint8Array(memory.buffer, bytesPtr); + bytes.set(source); + } + bjs["swift_js_make_js_string"] = function(ptr, len) { + return swift.memory.retain(decodeString(ptr, len)); + } + bjs["swift_js_init_memory_with_result"] = function(ptr, len) { + const target = new Uint8Array(memory.buffer, ptr, len); + target.set(tmpRetBytes); + tmpRetBytes = undefined; + } + bjs["swift_js_throw"] = function(id) { + tmpRetException = swift.memory.retainByRef(id); + } + bjs["swift_js_retain"] = function(id) { + return swift.memory.retainByRef(id); + } + bjs["swift_js_release"] = function(id) { + swift.memory.release(id); + } + bjs["swift_js_push_i32"] = function(v) { + i32Stack.push(v | 0); + } + bjs["swift_js_push_f32"] = function(v) { + f32Stack.push(Math.fround(v)); + } + bjs["swift_js_push_f64"] = function(v) { + f64Stack.push(v); + } + bjs["swift_js_push_string"] = function(ptr, len) { + const value = decodeString(ptr, len); + strStack.push(value); + } + bjs["swift_js_pop_i32"] = function() { + return i32Stack.pop(); + } + bjs["swift_js_pop_f32"] = function() { + return f32Stack.pop(); + } + bjs["swift_js_pop_f64"] = function() { + return f64Stack.pop(); + } + bjs["swift_js_push_pointer"] = function(pointer) { + ptrStack.push(pointer); + } + bjs["swift_js_pop_pointer"] = function() { + return ptrStack.pop(); + } + bjs["swift_js_push_i64"] = function(v) { + i64Stack.push(v); + } + bjs["swift_js_pop_i64"] = function() { + return i64Stack.pop(); + } + const taCtors = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array]; + bjs["swift_js_push_typed_array"] = function(kind, ptr, count) { + const Ctor = taCtors[kind]; + const byteLen = count * Ctor.BYTES_PER_ELEMENT; + const copy = memory.buffer.slice(ptr, ptr + byteLen); + taStack.push(Array.from(new Ctor(copy))); + } + bjs["swift_js_return_optional_bool"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalBool = null; + } else { + tmpRetOptionalBool = value !== 0; + } + } + bjs["swift_js_return_optional_int"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalInt = null; + } else { + tmpRetOptionalInt = value | 0; + } + } + bjs["swift_js_return_optional_float"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalFloat = null; + } else { + tmpRetOptionalFloat = Math.fround(value); + } + } + bjs["swift_js_return_optional_double"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalDouble = null; + } else { + tmpRetOptionalDouble = value; + } + } + bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = decodeString(ptr, len); + } + } + bjs["swift_js_return_optional_object"] = function(isSome, objectId) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = swift.memory.getObject(objectId); + } + } + bjs["swift_js_return_optional_heap_object"] = function(isSome, pointer) { + if (isSome === 0) { + tmpRetOptionalHeapObject = null; + } else { + tmpRetOptionalHeapObject = pointer; + } + } + bjs["swift_js_get_optional_int_presence"] = function() { + return tmpRetOptionalInt != null ? 1 : 0; + } + bjs["swift_js_get_optional_int_value"] = function() { + const value = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; + return value; + } + bjs["swift_js_get_optional_string"] = function() { + const str = tmpRetString; + tmpRetString = undefined; + if (str == null) { + return -1; + } else { + const bytes = textEncoder.encode(str); + tmpRetBytes = bytes; + return bytes.length; + } + } + bjs["swift_js_get_optional_float_presence"] = function() { + return tmpRetOptionalFloat != null ? 1 : 0; + } + bjs["swift_js_get_optional_float_value"] = function() { + const value = tmpRetOptionalFloat; + tmpRetOptionalFloat = undefined; + return value; + } + bjs["swift_js_get_optional_double_presence"] = function() { + return tmpRetOptionalDouble != null ? 1 : 0; + } + bjs["swift_js_get_optional_double_value"] = function() { + const value = tmpRetOptionalDouble; + tmpRetOptionalDouble = undefined; + return value; + } + bjs["swift_js_get_optional_heap_object_pointer"] = function() { + const pointer = tmpRetOptionalHeapObject; + tmpRetOptionalHeapObject = undefined; + return pointer || 0; + } + bjs["swift_js_closure_unregister"] = function(funcRef) {} + bjs["swift_js_closure_unregister"] = function(funcRef) { + const func = swift.memory.getObject(funcRef); + func.__unregister(); + } + bjs["invoke_js_callback_TestModule_10TestModuleAl7Polygon_Si"] = function(callbackId, param0) { + try { + const callback = swift.memory.getObject(callbackId); + let ret = callback(_exports['PolygonReference'].__construct(param0)); + return ret; + } catch (error) { + setException(error); + return 0 + } + } + bjs["make_swift_closure_TestModule_10TestModuleAl7Polygon_Si"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModuleAl7Polygon_Si = function(param0) { + const ret = instance.exports.invoke_swift_closure_TestModule_10TestModuleAl7Polygon_Si(boxPtr, param0.pointer); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + return ret; + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleAl7Polygon_Si); + } + bjs["invoke_js_callback_TestModule_10TestModuley_Al7Polygon"] = function(callbackId) { + try { + const callback = swift.memory.getObject(callbackId); + let ret = callback(); + return ret.pointer; + } catch (error) { + setException(error); + return 0 + } + } + bjs["make_swift_closure_TestModule_10TestModuley_Al7Polygon"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModuley_Al7Polygon = function() { + const ret = instance.exports.invoke_swift_closure_TestModule_10TestModuley_Al7Polygon(boxPtr); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + return _exports['PolygonReference'].__construct(ret); + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuley_Al7Polygon); + } + // Wrapper functions for module: TestModule + if (!importObject["TestModule"]) { + importObject["TestModule"] = {}; + } + importObject["TestModule"]["bjs_PolygonReference_wrap"] = function(pointer) { + const obj = _exports['PolygonReference'].__construct(pointer); + return swift.memory.retain(obj); + }; + }, + setInstance: (i) => { + instance = i; + memory = instance.exports.memory; + + decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + + setException = (error) => { + instance.exports._swift_js_exception.value = swift.memory.retain(error) + } + }, + /** @param {WebAssembly.Instance} instance */ + createExports: (instance) => { + const js = swift.memory.heap; + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.identityMap?.delete(state.pointer); + state.deinit(state.pointer); + }); + + /// Represents a Swift heap object like a class instance or an actor instance. + class SwiftHeapObject { + static __wrap(pointer, deinit, prototype, identityCache) { + const makeFresh = (identityMap) => { + const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false, identityMap }; + obj.pointer = pointer; + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); + if (identityMap) { + identityMap.set(pointer, new WeakRef(obj)); + } + return obj; + }; + + if (!identityCache) { + return makeFresh(null); + } + + const cached = identityCache.get(pointer)?.deref(); + if (cached && !cached.__swiftHeapObjectState.hasReleased) { + deinit(pointer); + return cached; + } + if (identityCache.has(pointer)) { + identityCache.delete(pointer); + } + + return makeFresh(identityCache); + } + + release() { + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.identityMap?.delete(state.pointer); + state.deinit(state.pointer); + } + } + class PolygonReference extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_PolygonReference_deinit, PolygonReference.prototype, null); + } + + constructor(sides) { + const ret = instance.exports.bjs_PolygonReference_init(sides); + return PolygonReference.__construct(ret); + } + } + const exports = { + PolygonReference, + makePolygonFactory: function bjs_makePolygonFactory() { + const ret = instance.exports.bjs_makePolygonFactory(); + return swift.memory.getObject(ret); + }, + makePolygonInspector: function bjs_makePolygonInspector() { + const ret = instance.exports.bjs_makePolygonInspector(); + return swift.memory.getObject(ret); + }, + }; + _exports = exports; + return exports; + }, + } +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.d.ts new file mode 100644 index 000000000..9525038e6 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.d.ts @@ -0,0 +1,30 @@ +// 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`. + +/// Represents a Swift heap object like a class instance or an actor instance. +export interface SwiftHeapObject { + /// Release the heap object. + /// + /// Note: Calling this method will release the heap object and it will no longer be accessible. + release(): void; +} +export interface ColorBox extends SwiftHeapObject { +} +export type Exports = { + ColorBox: { + new(name: string): ColorBox; + } + roundtripColor(color: ColorBox): ColorBox; +} +export type Imports = { +} +export function createInstantiator(options: { + imports: Imports; +}, swift: any): Promise<{ + addImports: (importObject: WebAssembly.Imports) => void; + setInstance: (instance: WebAssembly.Instance) => void; + createExports: (instance: WebAssembly.Instance) => Exports; +}>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js new file mode 100644 index 000000000..01f0472ab --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js @@ -0,0 +1,295 @@ +// 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`. + +export async function createInstantiator(options, swift) { + let instance; + let memory; + let setException; + let decodeString; + const textDecoder = new TextDecoder("utf-8"); + const textEncoder = new TextEncoder("utf-8"); + let tmpRetString; + let tmpRetBytes; + let tmpRetException; + let tmpRetOptionalBool; + let tmpRetOptionalInt; + let tmpRetOptionalFloat; + let tmpRetOptionalDouble; + let tmpRetOptionalHeapObject; + let strStack = []; + let i32Stack = []; + let i64Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; + let taStack = []; + const enumHelpers = {}; + const structHelpers = {}; + + let _exports = null; + let bjs = null; + + return { + /** + * @param {WebAssembly.Imports} importObject + */ + addImports: (importObject, importsContext) => { + bjs = {}; + importObject["bjs"] = bjs; + bjs["swift_js_return_string"] = function(ptr, len) { + tmpRetString = decodeString(ptr, len); + } + bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { + const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); + const bytes = new Uint8Array(memory.buffer, bytesPtr); + bytes.set(source); + } + bjs["swift_js_make_js_string"] = function(ptr, len) { + return swift.memory.retain(decodeString(ptr, len)); + } + bjs["swift_js_init_memory_with_result"] = function(ptr, len) { + const target = new Uint8Array(memory.buffer, ptr, len); + target.set(tmpRetBytes); + tmpRetBytes = undefined; + } + bjs["swift_js_throw"] = function(id) { + tmpRetException = swift.memory.retainByRef(id); + } + bjs["swift_js_retain"] = function(id) { + return swift.memory.retainByRef(id); + } + bjs["swift_js_release"] = function(id) { + swift.memory.release(id); + } + bjs["swift_js_push_i32"] = function(v) { + i32Stack.push(v | 0); + } + bjs["swift_js_push_f32"] = function(v) { + f32Stack.push(Math.fround(v)); + } + bjs["swift_js_push_f64"] = function(v) { + f64Stack.push(v); + } + bjs["swift_js_push_string"] = function(ptr, len) { + const value = decodeString(ptr, len); + strStack.push(value); + } + bjs["swift_js_pop_i32"] = function() { + return i32Stack.pop(); + } + bjs["swift_js_pop_f32"] = function() { + return f32Stack.pop(); + } + bjs["swift_js_pop_f64"] = function() { + return f64Stack.pop(); + } + bjs["swift_js_push_pointer"] = function(pointer) { + ptrStack.push(pointer); + } + bjs["swift_js_pop_pointer"] = function() { + return ptrStack.pop(); + } + bjs["swift_js_push_i64"] = function(v) { + i64Stack.push(v); + } + bjs["swift_js_pop_i64"] = function() { + return i64Stack.pop(); + } + const taCtors = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array]; + bjs["swift_js_push_typed_array"] = function(kind, ptr, count) { + const Ctor = taCtors[kind]; + const byteLen = count * Ctor.BYTES_PER_ELEMENT; + const copy = memory.buffer.slice(ptr, ptr + byteLen); + taStack.push(Array.from(new Ctor(copy))); + } + bjs["swift_js_return_optional_bool"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalBool = null; + } else { + tmpRetOptionalBool = value !== 0; + } + } + bjs["swift_js_return_optional_int"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalInt = null; + } else { + tmpRetOptionalInt = value | 0; + } + } + bjs["swift_js_return_optional_float"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalFloat = null; + } else { + tmpRetOptionalFloat = Math.fround(value); + } + } + bjs["swift_js_return_optional_double"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalDouble = null; + } else { + tmpRetOptionalDouble = value; + } + } + bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = decodeString(ptr, len); + } + } + bjs["swift_js_return_optional_object"] = function(isSome, objectId) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = swift.memory.getObject(objectId); + } + } + bjs["swift_js_return_optional_heap_object"] = function(isSome, pointer) { + if (isSome === 0) { + tmpRetOptionalHeapObject = null; + } else { + tmpRetOptionalHeapObject = pointer; + } + } + bjs["swift_js_get_optional_int_presence"] = function() { + return tmpRetOptionalInt != null ? 1 : 0; + } + bjs["swift_js_get_optional_int_value"] = function() { + const value = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; + return value; + } + bjs["swift_js_get_optional_string"] = function() { + const str = tmpRetString; + tmpRetString = undefined; + if (str == null) { + return -1; + } else { + const bytes = textEncoder.encode(str); + tmpRetBytes = bytes; + return bytes.length; + } + } + bjs["swift_js_get_optional_float_presence"] = function() { + return tmpRetOptionalFloat != null ? 1 : 0; + } + bjs["swift_js_get_optional_float_value"] = function() { + const value = tmpRetOptionalFloat; + tmpRetOptionalFloat = undefined; + return value; + } + bjs["swift_js_get_optional_double_presence"] = function() { + return tmpRetOptionalDouble != null ? 1 : 0; + } + bjs["swift_js_get_optional_double_value"] = function() { + const value = tmpRetOptionalDouble; + tmpRetOptionalDouble = undefined; + return value; + } + bjs["swift_js_get_optional_heap_object_pointer"] = function() { + const pointer = tmpRetOptionalHeapObject; + tmpRetOptionalHeapObject = undefined; + return pointer || 0; + } + bjs["swift_js_closure_unregister"] = function(funcRef) {} + // Wrapper functions for module: TestModule + if (!importObject["TestModule"]) { + importObject["TestModule"] = {}; + } + importObject["TestModule"]["bjs_ColorBox_wrap"] = function(pointer) { + const obj = _exports['ColorBox'].__construct(pointer); + return swift.memory.retain(obj); + }; + }, + setInstance: (i) => { + instance = i; + memory = instance.exports.memory; + + decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + + setException = (error) => { + instance.exports._swift_js_exception.value = swift.memory.retain(error) + } + }, + /** @param {WebAssembly.Instance} instance */ + createExports: (instance) => { + const js = swift.memory.heap; + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.identityMap?.delete(state.pointer); + state.deinit(state.pointer); + }); + + /// Represents a Swift heap object like a class instance or an actor instance. + class SwiftHeapObject { + static __wrap(pointer, deinit, prototype, identityCache) { + const makeFresh = (identityMap) => { + const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false, identityMap }; + obj.pointer = pointer; + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); + if (identityMap) { + identityMap.set(pointer, new WeakRef(obj)); + } + return obj; + }; + + if (!identityCache) { + return makeFresh(null); + } + + const cached = identityCache.get(pointer)?.deref(); + if (cached && !cached.__swiftHeapObjectState.hasReleased) { + deinit(pointer); + return cached; + } + if (identityCache.has(pointer)) { + identityCache.delete(pointer); + } + + return makeFresh(identityCache); + } + + release() { + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.identityMap?.delete(state.pointer); + state.deinit(state.pointer); + } + } + class ColorBox extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_ColorBox_deinit, ColorBox.prototype, null); + } + + constructor(name) { + const nameBytes = textEncoder.encode(name); + const nameId = swift.memory.retain(nameBytes); + const ret = instance.exports.bjs_ColorBox_init(nameId, nameBytes.length); + return ColorBox.__construct(ret); + } + } + const exports = { + ColorBox, + roundtripColor: function bjs_roundtripColor(color) { + const ret = instance.exports.bjs_roundtripColor(color.pointer); + return ColorBox.__construct(ret); + }, + }; + _exports = exports; + return exports; + }, + } +} \ No newline at end of file diff --git a/Sources/JavaScriptKit/Macros.swift b/Sources/JavaScriptKit/Macros.swift index 3189cdeab..191cf15d6 100644 --- a/Sources/JavaScriptKit/Macros.swift +++ b/Sources/JavaScriptKit/Macros.swift @@ -113,8 +113,12 @@ public enum JSImportFrom: String { /// /// - Important: This feature is still experimental. No API stability is guaranteed, and the API may change in future releases. @attached(peer) -public macro JS(namespace: String? = nil, enumStyle: JSEnumStyle = .const, identityMode: Bool = false) = - Builtin.ExternalMacro +public macro JS( + as aliasOf: Any.Type? = nil, + namespace: String? = nil, + enumStyle: JSEnumStyle = .const, + identityMode: Bool = false +) = Builtin.ExternalMacro /// A macro that generates a Swift getter that reads a value from JavaScript. /// diff --git a/Tests/BridgeJSGlobalTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSGlobalTests/Generated/JavaScript/BridgeJS.json index 5e9626840..48c0904bf 100644 --- a/Tests/BridgeJSGlobalTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSGlobalTests/Generated/JavaScript/BridgeJS.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ { "constructor" : { diff --git a/Tests/BridgeJSIdentityTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSIdentityTests/Generated/JavaScript/BridgeJS.json index 56db0a3ed..53d837ece 100644 --- a/Tests/BridgeJSIdentityTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSIdentityTests/Generated/JavaScript/BridgeJS.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ { "constructor" : { diff --git a/Tests/BridgeJSRuntimeTests/AliasAPIs.swift b/Tests/BridgeJSRuntimeTests/AliasAPIs.swift new file mode 100644 index 000000000..bd6737b77 --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/AliasAPIs.swift @@ -0,0 +1,401 @@ +import JavaScriptKit + +@JS(as: PolygonReference.self) struct Polygon { + var vertices: [Double] + var label: String + + consuming func bridgeToJS() -> PolygonReference { + return PolygonReference(underlying: self) + } + + static func bridgeFromJS(_ value: consuming PolygonReference) -> Polygon { + return value.underlying + } +} + +@JS final class PolygonReference { + var underlying: Polygon + + @JS init(verticesData: [Double], label: String) { + self.underlying = Polygon(vertices: verticesData, label: label) + } + + init(underlying: Polygon) { + self.underlying = underlying + } + + @JS func vertexCount() -> Int { + return underlying.vertices.count + } + + @JS func summary() -> String { + return "\(underlying.label)(\(underlying.vertices.count))" + } + + @JS func snapshot() -> Polygon { + return underlying + } + + @JS func merge(_ other: Polygon) -> Polygon { + var combined = underlying + combined.vertices.append(contentsOf: other.vertices) + return combined + } + + @JS static func origin(label: String) -> Polygon { + return Polygon(vertices: [], label: label) + } +} + +@JS(as: TagReference.self) struct Tag { + var name: String + + consuming func bridgeToJS() -> TagReference { + return TagReference(underlying: self) + } + + static func bridgeFromJS(_ value: consuming TagReference) -> Tag { + return value.underlying + } +} + +@JS final class TagReference { + var underlying: Tag + + init(underlying: Tag) { + self.underlying = underlying + } + + @JS func describe() -> String { + return "tag:\(underlying.name)" + } +} + +@JS func makeTag(_ name: String) -> Tag { + return Tag(name: name) +} + +@JS func roundTripPolygon(_ polygon: Polygon) -> Polygon { + return polygon +} + +@JS func appendVertex(_ polygon: Polygon, _ value: Double) -> Polygon { + var copy = polygon + copy.vertices.append(value) + return copy +} + +@JS func optionalRoundTripPolygon(_ polygon: Polygon?) -> Polygon? { + return polygon +} + +@JS func polygonVertexCount(_ polygon: Polygon) -> Int { + return polygon.vertices.count +} + +@JS func roundTripPolygonArray(_ polygons: [Polygon]) -> [Polygon] { + return polygons +} + +@JS func concatPolygons(_ polygons: [Polygon]) -> Polygon { + var combined = Polygon(vertices: [], label: "concat") + for p in polygons { + combined.vertices.append(contentsOf: p.vertices) + } + return combined +} + +@JS func validatePolygon(_ polygon: Polygon) throws(JSException) -> Polygon { + if polygon.vertices.isEmpty { + throw JSException(JSError(message: "empty polygon").jsValue) + } + return polygon +} + +@JS func splitPolygon(_ polygon: Polygon) -> [Polygon] { + return polygon.vertices.map { Polygon(vertices: [$0], label: polygon.label) } +} + +@JS(as: TokenReference.self) struct Token: ~Copyable { + let value: Int + + consuming func bridgeToJS() -> TokenReference { + return TokenReference(value: value) + } + + static func bridgeFromJS(_ value: consuming TokenReference) -> Token { + return Token(value: value.value) + } +} + +@JS final class TokenReference { + let value: Int + + @JS init(value: Int) { + self.value = value + } + + @JS func read() -> Int { + return value + } +} + +@JS func incrementToken(_ token: borrowing Token) -> Token { + return Token(value: token.value + 1) +} + +@JS func makeToken(_ value: Int) -> Token { + return Token(value: value) +} + +@JS func makePolygonInspector() -> (Polygon) -> Int { + return { polygon in polygon.vertices.count } +} + +@JS func asyncMakePolygon(_ label: String) async -> Polygon { + return Polygon(vertices: [9, 9], label: label) +} + +@JS func roundTripOptionalPolygonArray(_ polygons: [Polygon?]) -> [Polygon?] { + return polygons +} + +@JS(as: TagHolderReference.self) struct TagHolder { + var tag: Tag + var version: Int + + consuming func bridgeToJS() -> TagHolderReference { + return TagHolderReference(tag: tag, version: version) + } + + static func bridgeFromJS(_ value: consuming TagHolderReference) -> TagHolder { + return TagHolder(tag: value.tag, version: value.version) + } +} + +@JS final class TagHolderReference { + @JS var tag: Tag + @JS var version: Int + + @JS init(tag: Tag, version: Int) { + self.tag = tag + self.version = version + } + + @JS func describe() -> String { + return "holder(\(tag.name), v\(version))" + } +} + +@JS func makeTagHolder(_ name: String, _ version: Int) -> TagHolder { + return TagHolder(tag: Tag(name: name), version: version) +} + +@JS(as: JSCoordinate.self) struct Coordinate { + var latitude: Double + var longitude: Double + + var hemisphere: String { + latitude >= 0 ? "northern" : "southern" + } + + consuming func bridgeToJS() -> JSCoordinate { + return JSCoordinate(latitude: latitude, longitude: longitude) + } + + static func bridgeFromJS(_ value: consuming JSCoordinate) -> Coordinate { + return Coordinate(latitude: value.latitude, longitude: value.longitude) + } +} + +@JS struct JSCoordinate { + var latitude: Double + var longitude: Double + + @JS init(latitude: Double, longitude: Double) { + self.latitude = latitude + self.longitude = longitude + } +} + +@JS func roundTripCoordinate(_ coordinate: Coordinate) -> Coordinate { + return coordinate +} + +@JS(as: PriorityReference.self) enum Priority { + case low, medium, high + + consuming func bridgeToJS() -> PriorityReference { + return PriorityReference(underlying: self) + } + + static func bridgeFromJS(_ value: consuming PriorityReference) -> Priority { + return value.underlying + } +} + +@JS final class PriorityReference { + let underlying: Priority + + init(underlying: Priority) { + self.underlying = underlying + } + + @JS func describe() -> String { + switch underlying { + case .low: return "low" + case .medium: return "medium" + case .high: return "high" + } + } + + @JS func weight() -> Int { + switch underlying { + case .low: return 1 + case .medium: return 5 + case .high: return 10 + } + } + + @JS static func low() -> Priority { return .low } + @JS static func medium() -> Priority { return .medium } + @JS static func high() -> Priority { return .high } +} + +@JS func roundTripPriority(_ priority: Priority) -> Priority { + return priority +} + +@JS(as: Severity.self) struct Alert { + let level: Severity + + var requiresImmediateAction: Bool { + level == .error + } + + consuming func bridgeToJS() -> Severity { + return level + } + + static func bridgeFromJS(_ value: consuming Severity) -> Alert { + return Alert(level: value) + } +} + +@JS enum Severity { + case notice, warning, error +} + +@JS func roundTripAlert(_ alert: Alert) -> Alert { + return alert +} + +@JS func makeAlert(_ level: Severity) -> Alert { + return Alert(level: level) +} + +@JS(as: SessionState.self) class Session { + var token: String + + init(token: String) { + self.token = token + } + + consuming func bridgeToJS() -> SessionState { + return SessionState(token: token) + } + + static func bridgeFromJS(_ value: consuming SessionState) -> Session { + return Session(token: value.token) + } +} + +@JS struct SessionState { + var token: String + + @JS init(token: String) { + self.token = token + } +} + +@JS func roundTripSession(_ session: Session) -> Session { + return session +} + +@JS func makeSession(_ token: String) -> Session { + return Session(token: token) +} + +@JS enum Shape { + case polygon(Polygon) + case empty +} + +@JS func roundTripShape(_ s: Shape) -> Shape { + return s +} + +@JS func makeShapePolygon(_ polygon: Polygon) -> Shape { + return .polygon(polygon) +} + +@JS func makeShapeEmpty() -> Shape { + return .empty +} + +// MARK: - Imports + +@JS(as: String.self) struct Tagged { + var raw: String + + consuming func bridgeToJS() -> String { + return raw + } + + static func bridgeFromJS(_ value: consuming String) -> Tagged { + return Tagged(raw: value) + } +} + +@JSClass struct Surface { + @JSFunction init(_ label: String) throws(JSException) + @JSGetter var label: String +} + +@JS(as: Surface.self) struct Canvas { + var label: String + + consuming func bridgeToJS() -> Surface { + return try! Surface(label) + } + + static func bridgeFromJS(_ value: consuming Surface) -> Canvas { + return Canvas(label: (try? value.label) ?? "") + } +} + +@JS enum InnerTag { + case payload(Int) + case empty +} + +@JS(as: InnerTag.self) struct AliasedTag { + var underlying: InnerTag + + consuming func bridgeToJS() -> InnerTag { + return underlying + } + + static func bridgeFromJS(_ value: consuming InnerTag) -> AliasedTag { + return AliasedTag(underlying: value) + } +} + +@JSClass struct AliasImports { + @JSFunction static func jsRoundTripTagged(_ value: Tagged) throws(JSException) -> Tagged + @JSFunction static func jsRoundTripOptionalTagged(_ value: Tagged?) throws(JSException) -> Tagged? + @JSFunction static func jsProduceOptionalCanvas(_ label: String?) throws(JSException) -> Canvas? + @JSFunction static func jsRoundTripAliasedTags(_ values: [AliasedTag?]) throws(JSException) -> [AliasedTag?] + @JSFunction static func jsRoundTripPolygon(_ value: Polygon) throws(JSException) -> Polygon + @JSFunction static func jsRoundTripCoordinate(_ value: Coordinate) throws(JSException) -> Coordinate +} diff --git a/Tests/BridgeJSRuntimeTests/AliasTests.swift b/Tests/BridgeJSRuntimeTests/AliasTests.swift new file mode 100644 index 000000000..2e4548ec9 --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/AliasTests.swift @@ -0,0 +1,72 @@ +import XCTest +import JavaScriptKit + +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "runAliasWorks") +@_extern(c) +func runAliasWorks() -> Void + +final class AliasTests: XCTestCase { + func testAliasEndToEnd() { + runAliasWorks() + } + + func testAliasAsyncEndToEnd() async throws { + try await runAliasAsyncWorks() + } + + // MARK: - Imports + + func testRoundTripTagged() throws { + let result = try AliasImports.jsRoundTripTagged(Tagged(raw: "hello")) + XCTAssertEqual(result.raw, "hello") + } + + func testRoundTripOptionalTagged() throws { + XCTAssertNil(try AliasImports.jsRoundTripOptionalTagged(nil)) + let echoed = try AliasImports.jsRoundTripOptionalTagged(Tagged(raw: "present")) + XCTAssertEqual(echoed?.raw, "present") + } + + func testProduceOptionalCanvas() throws { + XCTAssertNil(try AliasImports.jsProduceOptionalCanvas(nil)) + let canvas = try AliasImports.jsProduceOptionalCanvas("hello") + XCTAssertEqual(canvas?.label, "hello") + } + + func testRoundTripAliasedTagArray() throws { + let inputs: [AliasedTag?] = [ + AliasedTag(underlying: .payload(7)), + nil, + AliasedTag(underlying: .empty), + nil, + ] + let echoed = try AliasImports.jsRoundTripAliasedTags(inputs) + XCTAssertEqual(echoed.count, 4) + if case .payload(let n) = echoed[0]?.underlying { + XCTAssertEqual(n, 7) + } else { + XCTFail("expected .payload(7) at index 0") + } + XCTAssertNil(echoed[1]) + if case .empty = echoed[2]?.underlying { + // ok + } else { + XCTFail("expected .empty at index 2") + } + XCTAssertNil(echoed[3]) + } + + func testRoundTripPolygonImport() throws { + let polygon = Polygon(vertices: [1, 2, 3], label: "import") + let echoed = try AliasImports.jsRoundTripPolygon(polygon) + XCTAssertEqual(echoed.label, "import") + XCTAssertEqual(echoed.vertices, [1, 2, 3]) + } + + func testRoundTripCoordinateImport() throws { + let coordinate = Coordinate(latitude: 12.5, longitude: -34.25) + let echoed = try AliasImports.jsRoundTripCoordinate(coordinate) + XCTAssertEqual(echoed.latitude, 12.5) + XCTAssertEqual(echoed.longitude, -34.25) + } +} diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.Macros.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.Macros.swift index 08d0db2a7..b2f7795cc 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.Macros.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.Macros.swift @@ -44,6 +44,8 @@ extension FeatureFlag: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum {} @JSFunction func runAsyncWorks() async throws(JSException) -> Void +@JSFunction func runAliasAsyncWorks() async throws(JSException) -> Void + @JSFunction func fetchWeatherData(_ city: String) async throws(JSException) -> WeatherData @JSClass struct WeatherData { diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index b2afb6d5b..1192d4b33 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -645,126 +645,37 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9Di } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsAl7Polygon_Si") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsAl7Polygon_Si_extern(_ callback: Int32, _ param0: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsAl7Polygon_Si_extern(_ callback: Int32, _ param0: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb_extern(callback, param0Bytes, param0Length) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsAl7Polygon_Si(_ callback: Int32, _ param0: UnsafeMutableRawPointer) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsAl7Polygon_Si_extern(callback, param0) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsAl7Polygon_Si") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsAl7Polygon_Si_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsAl7Polygon_Si_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb_extern(boxPtr, file, line) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsAl7Polygon_Si(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsAl7Polygon_Si_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestsKSS_Sb { - static func bridgeJSLift(_ callbackId: Int32) -> (String) throws(JSException) -> Bool { +private enum _BJS_Closure_20BridgeJSRuntimeTestsAl7Polygon_Si { + static func bridgeJSLift(_ callbackId: Int32) -> (Polygon) -> Int { let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] (param0: String) throws(JSException) -> Bool in - #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() - let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in - let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb(callbackValue, param0Bytes, param0Length) - return ret - } - let ret = ret0 - if let error = _swift_js_take_exception() { - throw error - } - return Bool.bridgeJSLiftReturn(ret) - #else - fatalError("Only available on WebAssembly") - #endif - } - } -} - -extension JSTypedClosure where Signature == (String) throws(JSException) -> Bool { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (String) throws(JSException) -> Bool) { - self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb, - body: body, - fileID: fileID, - line: line - ) - } -} - -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { - #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(String) throws(JSException) -> Bool>>.fromOpaque(boxPtr).takeUnretainedValue().closure - do { - let result = try closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) - return result.bridgeJSLowerReturn() - } catch let error { - if let error = error.thrownValue.object { - withExtendedLifetime(error) { - _swift_js_throw(Int32(bitPattern: $0.id)) - } - } else { - let jsError = JSError(message: error.description) - withExtendedLifetime(jsError.jsObject) { - _swift_js_throw(Int32(bitPattern: $0.id)) - } - } - return 0 - } - #else - fatalError("Only available on WebAssembly") - #endif -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 -#else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si_extern(callback, param0Bytes, param0Length) -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 -#else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si_extern(boxPtr, file, line) -} - -private enum _BJS_Closure_20BridgeJSRuntimeTestsKSS_Si { - static func bridgeJSLift(_ callbackId: Int32) -> (String) throws(JSException) -> Int { - let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] (param0: String) throws(JSException) -> Int in + return { [callback] param0 in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() - let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in - let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si(callbackValue, param0Bytes, param0Length) - return ret - } - let ret = ret0 - if let error = _swift_js_take_exception() { - throw error - } + let param0Pointer = param0.bridgeToJS().bridgeJSLowerParameter() + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsAl7Polygon_Si(callbackValue, param0Pointer) return Int.bridgeJSLiftReturn(ret) #else fatalError("Only available on WebAssembly") @@ -773,10 +684,10 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsKSS_Si { } } -extension JSTypedClosure where Signature == (String) throws(JSException) -> Int { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (String) throws(JSException) -> Int) { +extension JSTypedClosure where Signature == (Polygon) -> Int { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Polygon) -> Int) { self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si, + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsAl7Polygon_Si, body: body, fileID: fileID, line: line @@ -784,27 +695,13 @@ extension JSTypedClosure where Signature == (String) throws(JSException) -> Int } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsAl7Polygon_Si") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsAl7Polygon_Si") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsAl7Polygon_Si(_ boxPtr: UnsafeMutableRawPointer, _ param0: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(String) throws(JSException) -> Int>>.fromOpaque(boxPtr).takeUnretainedValue().closure - do { - let result = try closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) - return result.bridgeJSLowerReturn() - } catch let error { - if let error = error.thrownValue.object { - withExtendedLifetime(error) { - _swift_js_throw(Int32(bitPattern: $0.id)) - } - } else { - let jsError = JSError(message: error.description) - withExtendedLifetime(jsError.jsObject) { - _swift_js_throw(Int32(bitPattern: $0.id)) - } - } - return 0 - } + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Polygon) -> Int>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Polygon.bridgeFromJS(PolygonReference.bridgeJSLiftParameter(param0))) + return result.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -1968,45 +1865,38 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqS } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS_extern(resolveRef, rejectRef, callback, param0Bytes, param0Length) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y_extern(callback, param0Bytes, param0Length) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS_extern(boxPtr, file, line) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestsYaKSS_SS { - static func bridgeJSLift(_ callbackId: Int32) -> (String) async throws(JSException) -> String { +private enum _BJS_Closure_20BridgeJSRuntimeTestss11FeatureFlagO_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending FeatureFlag) -> Void { let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] (param0: String) async throws(JSException) -> String in + return { [callback] param0 in #if arch(wasm32) - let resolved = try await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<(sending String) -> Void>($0) - }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) - }) { resolveRef, rejectRef in - let callbackValue = callback.bridgeJSLowerParameter() - param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS(resolveRef, rejectRef, callbackValue, param0Bytes, param0Length) - } + let callbackValue = callback.bridgeJSLowerParameter() + param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y(callbackValue, param0Bytes, param0Length) } - return resolved #else fatalError("Only available on WebAssembly") #endif @@ -2014,10 +1904,10 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsYaKSS_SS { } } -extension JSTypedClosure where Signature == (String) async throws(JSException) -> String { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (String) async throws(JSException) -> String) { +extension JSTypedClosure where Signature == (sending FeatureFlag) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending FeatureFlag) -> Void) { self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS, + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y, body: body, fileID: fileID, line: line @@ -2025,58 +1915,49 @@ extension JSTypedClosure where Signature == (String) async throws(JSException) - } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(String) async throws(JSException) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure - return _bjs_makePromise(resolve: Promise_resolve_SS, reject: Promise_reject) { () async throws(JSException) -> String in - return try await closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) - } + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending FeatureFlag) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(FeatureFlag.bridgeJSLiftParameter(param0Bytes, param0Length)) #else fatalError("Only available on WebAssembly") #endif } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y_extern(_ callback: Int32, _ param0: Int32) -> Void #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y_extern(_ callback: Int32, _ param0: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y_extern(resolveRef, rejectRef, callback, param0Bytes, param0Length) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y(_ callback: Int32, _ param0: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y_extern(callback, param0) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y_extern(boxPtr, file, line) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestsYaKSS_y { - static func bridgeJSLift(_ callbackId: Int32) -> (String) async throws(JSException) -> Void { +private enum _BJS_Closure_20BridgeJSRuntimeTestss11WeatherDataC_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending WeatherData) -> Void { let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] (param0: String) async throws(JSException) -> Void in + return { [callback] param0 in #if arch(wasm32) - try await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<() -> Void>($0) - }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) - }) { resolveRef, rejectRef in - let callbackValue = callback.bridgeJSLowerParameter() - param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y(resolveRef, rejectRef, callbackValue, param0Bytes, param0Length) - } - } + let callbackValue = callback.bridgeJSLowerParameter() + let param0Value = param0.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y(callbackValue, param0Value) #else fatalError("Only available on WebAssembly") #endif @@ -2084,10 +1965,10 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsYaKSS_y { } } -extension JSTypedClosure where Signature == (String) async throws(JSException) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (String) async throws(JSException) -> Void) { +extension JSTypedClosure where Signature == (sending WeatherData) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending WeatherData) -> Void) { self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y, + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y, body: body, fileID: fileID, line: line @@ -2095,58 +1976,49 @@ extension JSTypedClosure where Signature == (String) async throws(JSException) - } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(String) async throws(JSException) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - return _bjs_makePromise(resolve: Promise_resolve_y, reject: Promise_reject) { () async throws(JSException) in - try await closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) - } + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending WeatherData) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(WeatherData.bridgeJSLiftParameter(param0)) #else fatalError("Only available on WebAssembly") #endif } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0: Int32) -> Void +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y_extern(_ callback: Int32, _ param0Kind: Int32, _ param0Payload1: Int32, _ param0Payload2: Float64) -> Void #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0: Int32) -> Void { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y_extern(_ callback: Int32, _ param0Kind: Int32, _ param0Payload1: Int32, _ param0Payload2: Float64) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0: Int32) -> Void { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO_extern(resolveRef, rejectRef, callback, param0) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y(_ callback: Int32, _ param0Kind: Int32, _ param0Payload1: Int32, _ param0Payload2: Float64) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y_extern(callback, param0Kind, param0Payload1, param0Payload2) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO_extern(boxPtr, file, line) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO { - static func bridgeJSLift(_ callbackId: Int32) -> (Bool) async throws(JSException) -> AsyncPayloadResult { +private enum _BJS_Closure_20BridgeJSRuntimeTestss7JSValueV_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending JSValue) -> Void { let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] (param0: Bool) async throws(JSException) -> AsyncPayloadResult in + return { [callback] param0 in #if arch(wasm32) - let resolved = try await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<(sending AsyncPayloadResult) -> Void>($0) - }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) - }) { resolveRef, rejectRef in - let callbackValue = callback.bridgeJSLowerParameter() - let param0Value = param0.bridgeJSLowerParameter() - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO(resolveRef, rejectRef, callbackValue, param0Value) - } - return resolved + let callbackValue = callback.bridgeJSLowerParameter() + let (param0Kind, param0Payload1, param0Payload2) = param0.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y(callbackValue, param0Kind, param0Payload1, param0Payload2) #else fatalError("Only available on WebAssembly") #endif @@ -2154,10 +2026,10 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO { } } -extension JSTypedClosure where Signature == (Bool) async throws(JSException) -> AsyncPayloadResult { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Bool) async throws(JSException) -> AsyncPayloadResult) { +extension JSTypedClosure where Signature == (sending JSValue) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending JSValue) -> Void) { self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO, + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y, body: body, fileID: fileID, line: line @@ -2165,59 +2037,50 @@ extension JSTypedClosure where Signature == (Bool) async throws(JSException) -> } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Int32 { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y(_ boxPtr: UnsafeMutableRawPointer, _ param0Kind: Int32, _ param0Payload1: Int32, _ param0Payload2: Float64) -> Void { #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(Bool) async throws(JSException) -> AsyncPayloadResult>>.fromOpaque(boxPtr).takeUnretainedValue().closure - return _bjs_makePromise(resolve: Promise_resolve_18AsyncPayloadResultO, reject: Promise_reject) { () async throws(JSException) -> AsyncPayloadResult in - return try await closure(Bool.bridgeJSLiftParameter(param0)) - } + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending JSValue) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(JSValue.bridgeJSLiftParameter(param0Kind, param0Payload1, param0Payload2)) #else fatalError("Only available on WebAssembly") #endif } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS_extern(resolveRef, rejectRef, callback, param0Bytes, param0Length) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y_extern(callback, param0Bytes, param0Length) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS_extern(boxPtr, file, line) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestsYaSS_SS { - static func bridgeJSLift(_ callbackId: Int32) -> (String) async -> String { +private enum _BJS_Closure_20BridgeJSRuntimeTestssSS_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending String) -> Void { let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] (param0: String) async -> String in + return { [callback] param0 in #if arch(wasm32) - let resolved = try! await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<(sending String) -> Void>($0) - }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) - }) { resolveRef, rejectRef in - let callbackValue = callback.bridgeJSLowerParameter() - param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS(resolveRef, rejectRef, callbackValue, param0Bytes, param0Length) - } + let callbackValue = callback.bridgeJSLowerParameter() + param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y(callbackValue, param0Bytes, param0Length) } - return resolved #else fatalError("Only available on WebAssembly") #endif @@ -2225,10 +2088,10 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsYaSS_SS { } } -extension JSTypedClosure where Signature == (String) async -> String { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (String) async -> String) { +extension JSTypedClosure where Signature == (sending String) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending String) -> Void) { self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS, + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y, body: body, fileID: fileID, line: line @@ -2236,58 +2099,49 @@ extension JSTypedClosure where Signature == (String) async -> String { } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(String) async -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure - return _bjs_makePromise(resolve: Promise_resolve_SS, reject: Promise_reject) { - return await closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) - } + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending String) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) #else fatalError("Only available on WebAssembly") #endif } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0: Float64) -> Void +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y_extern(_ callback: Int32) -> Void #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0: Float64) -> Void { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y_extern(_ callback: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0: Float64) -> Void { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV_extern(resolveRef, rejectRef, callback, param0) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y(_ callback: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y_extern(callback) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV_extern(boxPtr, file, line) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestsYaSd_9DataPointV { - static func bridgeJSLift(_ callbackId: Int32) -> (Double) async -> DataPoint { +private enum _BJS_Closure_20BridgeJSRuntimeTestssSaSS_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending [String]) -> Void { let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] (param0: Double) async -> DataPoint in + return { [callback] param0 in #if arch(wasm32) - let resolved = try! await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<(sending DataPoint) -> Void>($0) - }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) - }) { resolveRef, rejectRef in - let callbackValue = callback.bridgeJSLowerParameter() - let param0Value = param0.bridgeJSLowerParameter() - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV(resolveRef, rejectRef, callbackValue, param0Value) - } - return resolved + let callbackValue = callback.bridgeJSLowerParameter() + let _ = param0.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y(callbackValue) #else fatalError("Only available on WebAssembly") #endif @@ -2295,10 +2149,10 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsYaSd_9DataPointV { } } -extension JSTypedClosure where Signature == (Double) async -> DataPoint { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Double) async -> DataPoint) { +extension JSTypedClosure where Signature == (sending [String]) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending [String]) -> Void) { self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV, + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y, body: body, fileID: fileID, line: line @@ -2306,52 +2160,49 @@ extension JSTypedClosure where Signature == (Double) async -> DataPoint { } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV(_ boxPtr: UnsafeMutableRawPointer, _ param0: Float64) -> Int32 { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y(_ boxPtr: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(Double) async -> DataPoint>>.fromOpaque(boxPtr).takeUnretainedValue().closure - return _bjs_makePromise(resolve: Promise_resolve_9DataPointV, reject: Promise_reject) { - return await closure(Double.bridgeJSLiftParameter(param0)) - } + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending [String]) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure([String].bridgeJSLiftParameter()) #else fatalError("Only available on WebAssembly") #endif } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y_extern(_ callback: Int32) -> Void #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y_extern(_ callback: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y_extern(callback, param0Bytes, param0Length) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y(_ callback: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y_extern(callback) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y_extern(boxPtr, file, line) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestss11FeatureFlagO_y { - static func bridgeJSLift(_ callbackId: Int32) -> (sending FeatureFlag) -> Void { +private enum _BJS_Closure_20BridgeJSRuntimeTestssSaSb_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending [Bool]) -> Void { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() - param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y(callbackValue, param0Bytes, param0Length) - } + let _ = param0.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y(callbackValue) #else fatalError("Only available on WebAssembly") #endif @@ -2359,10 +2210,10 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestss11FeatureFlagO_y { } } -extension JSTypedClosure where Signature == (sending FeatureFlag) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending FeatureFlag) -> Void) { +extension JSTypedClosure where Signature == (sending [Bool]) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending [Bool]) -> Void) { self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y, + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y, body: body, fileID: fileID, line: line @@ -2370,49 +2221,49 @@ extension JSTypedClosure where Signature == (sending FeatureFlag) -> Void { } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y(_ boxPtr: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending FeatureFlag) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(FeatureFlag.bridgeJSLiftParameter(param0Bytes, param0Length)) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending [Bool]) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure([Bool].bridgeJSLiftParameter()) #else fatalError("Only available on WebAssembly") #endif } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y_extern(_ callback: Int32, _ param0: Int32) -> Void +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y_extern(_ callback: Int32) -> Void #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y_extern(_ callback: Int32, _ param0: Int32) -> Void { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y_extern(_ callback: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y(_ callback: Int32, _ param0: Int32) -> Void { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y_extern(callback, param0) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y(_ callback: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y_extern(callback) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y_extern(boxPtr, file, line) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestss11WeatherDataC_y { - static func bridgeJSLift(_ callbackId: Int32) -> (sending WeatherData) -> Void { +private enum _BJS_Closure_20BridgeJSRuntimeTestssSaSd_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending [Double]) -> Void { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() - let param0Value = param0.bridgeJSLowerParameter() - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y(callbackValue, param0Value) + let _ = param0.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y(callbackValue) #else fatalError("Only available on WebAssembly") #endif @@ -2420,10 +2271,10 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestss11WeatherDataC_y { } } -extension JSTypedClosure where Signature == (sending WeatherData) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending WeatherData) -> Void) { +extension JSTypedClosure where Signature == (sending [Double]) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending [Double]) -> Void) { self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y, + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y, body: body, fileID: fileID, line: line @@ -2431,49 +2282,49 @@ extension JSTypedClosure where Signature == (sending WeatherData) -> Void { } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y(_ boxPtr: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending WeatherData) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(WeatherData.bridgeJSLiftParameter(param0)) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending [Double]) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure([Double].bridgeJSLiftParameter()) #else fatalError("Only available on WebAssembly") #endif } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y_extern(_ callback: Int32, _ param0: Int32) -> Void +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y_extern(_ callback: Int32, _ param0: Int32) -> Void #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y_extern(_ callback: Int32, _ param0: Int32) -> Void { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y_extern(_ callback: Int32, _ param0: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y(_ callback: Int32, _ param0: Int32) -> Void { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y_extern(callback, param0) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y(_ callback: Int32, _ param0: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y_extern(callback, param0) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y_extern(boxPtr, file, line) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y { - static func bridgeJSLift(_ callbackId: Int32) -> (sending AsyncPayloadResult) -> Void { +private enum _BJS_Closure_20BridgeJSRuntimeTestssSb_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending Bool) -> Void { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() - let param0CaseId = param0.bridgeJSLowerParameter() - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y(callbackValue, param0CaseId) + let param0Value = param0.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y(callbackValue, param0Value) #else fatalError("Only available on WebAssembly") #endif @@ -2481,10 +2332,10 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y { } } -extension JSTypedClosure where Signature == (sending AsyncPayloadResult) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending AsyncPayloadResult) -> Void) { +extension JSTypedClosure where Signature == (sending Bool) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Bool) -> Void) { self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y, + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y, body: body, fileID: fileID, line: line @@ -2492,49 +2343,49 @@ extension JSTypedClosure where Signature == (sending AsyncPayloadResult) -> Void } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending AsyncPayloadResult) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(AsyncPayloadResult.bridgeJSLiftParameter(param0)) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending Bool) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(Bool.bridgeJSLiftParameter(param0)) #else fatalError("Only available on WebAssembly") #endif } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y_extern(_ callback: Int32, _ param0: Int32) -> Void +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y_extern(_ callback: Int32, _ param0: Float64) -> Void #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y_extern(_ callback: Int32, _ param0: Int32) -> Void { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y_extern(_ callback: Int32, _ param0: Float64) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y(_ callback: Int32, _ param0: Int32) -> Void { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y_extern(callback, param0) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y(_ callback: Int32, _ param0: Float64) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y_extern(callback, param0) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y_extern(boxPtr, file, line) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y { - static func bridgeJSLift(_ callbackId: Int32) -> (sending AsyncImportedPayloadResult) -> Void { +private enum _BJS_Closure_20BridgeJSRuntimeTestssSd_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending Double) -> Void { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() - let param0CaseId = param0.bridgeJSLowerParameter() - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y(callbackValue, param0CaseId) + let param0Value = param0.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y(callbackValue, param0Value) #else fatalError("Only available on WebAssembly") #endif @@ -2542,10 +2393,10 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y } } -extension JSTypedClosure where Signature == (sending AsyncImportedPayloadResult) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending AsyncImportedPayloadResult) -> Void) { +extension JSTypedClosure where Signature == (sending Double) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Double) -> Void) { self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y, + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y, body: body, fileID: fileID, line: line @@ -2553,49 +2404,50 @@ extension JSTypedClosure where Signature == (sending AsyncImportedPayloadResult) } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Float64) -> Void { #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending AsyncImportedPayloadResult) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(AsyncImportedPayloadResult.bridgeJSLiftParameter(param0)) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending Double) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(Double.bridgeJSLiftParameter(param0)) #else fatalError("Only available on WebAssembly") #endif } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y_extern(_ callback: Int32, _ param0Kind: Int32, _ param0Payload1: Int32, _ param0Payload2: Float64) -> Void +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y_extern(_ callback: Int32, _ param0Kind: Int32, _ param0Payload1: Int32, _ param0Payload2: Float64) -> Void { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y(_ callback: Int32, _ param0Kind: Int32, _ param0Payload1: Int32, _ param0Payload2: Float64) -> Void { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y_extern(callback, param0Kind, param0Payload1, param0Payload2) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y_extern(callback, param0IsSome, param0Bytes, param0Length) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y_extern(boxPtr, file, line) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestss7JSValueV_y { - static func bridgeJSLift(_ callbackId: Int32) -> (sending JSValue) -> Void { +private enum _BJS_Closure_20BridgeJSRuntimeTestssSqSS_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending Optional) -> Void { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() - let (param0Kind, param0Payload1, param0Payload2) = param0.bridgeJSLowerParameter() - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y(callbackValue, param0Kind, param0Payload1, param0Payload2) + param0.bridgeJSWithLoweredParameter { (param0IsSome, param0Bytes, param0Length) in + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y(callbackValue, param0IsSome, param0Bytes, param0Length) + } #else fatalError("Only available on WebAssembly") #endif @@ -2603,10 +2455,10 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestss7JSValueV_y { } } -extension JSTypedClosure where Signature == (sending JSValue) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending JSValue) -> Void) { +extension JSTypedClosure where Signature == (sending Optional) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Optional) -> Void) { self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y, + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y, body: body, fileID: fileID, line: line @@ -2614,49 +2466,49 @@ extension JSTypedClosure where Signature == (sending JSValue) -> Void { } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y(_ boxPtr: UnsafeMutableRawPointer, _ param0Kind: Int32, _ param0Payload1: Int32, _ param0Payload2: Float64) -> Void { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending JSValue) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(JSValue.bridgeJSLiftParameter(param0Kind, param0Payload1, param0Payload2)) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending Optional) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Bytes, param0Length)) #else fatalError("Only available on WebAssembly") #endif } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y_extern(_ callback: Int32) -> Void +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Float64) -> Void #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y_extern(_ callback: Int32) -> Void { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Float64) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y(_ callback: Int32) -> Void { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y_extern(callback) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Float64) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y_extern(callback, param0IsSome, param0Value) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y_extern(boxPtr, file, line) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestss9DataPointV_y { - static func bridgeJSLift(_ callbackId: Int32) -> (sending DataPoint) -> Void { +private enum _BJS_Closure_20BridgeJSRuntimeTestssSqSd_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending Optional) -> Void { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() - let _ = param0.bridgeJSLowerParameter() - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y(callbackValue) + let (param0IsSome, param0Value) = param0.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y(callbackValue, param0IsSome, param0Value) #else fatalError("Only available on WebAssembly") #endif @@ -2664,10 +2516,10 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestss9DataPointV_y { } } -extension JSTypedClosure where Signature == (sending DataPoint) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending DataPoint) -> Void) { +extension JSTypedClosure where Signature == (sending Optional) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Optional) -> Void) { self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y, + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y, body: body, fileID: fileID, line: line @@ -2675,50 +2527,49 @@ extension JSTypedClosure where Signature == (sending DataPoint) -> Void { } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y(_ boxPtr: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Value: Float64) -> Void { #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending DataPoint) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(DataPoint.bridgeJSLiftParameter()) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending Optional) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) #else fatalError("Only available on WebAssembly") #endif } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP_extern(_ callback: Int32) -> Int32 #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP_extern(_ callback: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y_extern(callback, param0Bytes, param0Length) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP(_ callback: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP_extern(callback) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y_extern(boxPtr, file, line) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestssSS_y { - static func bridgeJSLift(_ callbackId: Int32) -> (sending String) -> Void { +private enum _BJS_Closure_20BridgeJSRuntimeTestsy_13DataProcessorP { + static func bridgeJSLift(_ callbackId: Int32) -> () -> any DataProcessor { let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] param0 in + return { [callback] in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() - param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y(callbackValue, param0Bytes, param0Length) - } + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP(callbackValue) + return AnyDataProcessor.bridgeJSLiftReturn(ret) #else fatalError("Only available on WebAssembly") #endif @@ -2726,10 +2577,10 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestssSS_y { } } -extension JSTypedClosure where Signature == (sending String) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending String) -> Void) { +extension JSTypedClosure where Signature == () -> any DataProcessor { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping () -> any DataProcessor) { self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y, + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP, body: body, fileID: fileID, line: line @@ -2737,49 +2588,50 @@ extension JSTypedClosure where Signature == (sending String) -> Void { } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP(_ boxPtr: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending String) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) + let closure = Unmanaged<_BridgeJSTypedClosureBox<() -> any DataProcessor>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure() + return (result as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn() #else fatalError("Only available on WebAssembly") #endif } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y_extern(_ callback: Int32) -> Void +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb_extern(_ callback: Int32) -> Int32 #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y_extern(_ callback: Int32) -> Void { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb_extern(_ callback: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y(_ callback: Int32) -> Void { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y_extern(callback) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb(_ callback: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb_extern(callback) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y_extern(boxPtr, file, line) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestssSaSS_y { - static func bridgeJSLift(_ callbackId: Int32) -> (sending [String]) -> Void { +private enum _BJS_Closure_20BridgeJSRuntimeTestsy_Sb { + static func bridgeJSLift(_ callbackId: Int32) -> () -> Bool { let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] param0 in + return { [callback] in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() - let _ = param0.bridgeJSLowerParameter() - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y(callbackValue) + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb(callbackValue) + return Bool.bridgeJSLiftReturn(ret) #else fatalError("Only available on WebAssembly") #endif @@ -2787,10 +2639,10 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestssSaSS_y { } } -extension JSTypedClosure where Signature == (sending [String]) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending [String]) -> Void) { +extension JSTypedClosure where Signature == () -> Bool { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping () -> Bool) { self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y, + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb, body: body, fileID: fileID, line: line @@ -2798,574 +2650,23 @@ extension JSTypedClosure where Signature == (sending [String]) -> Void { } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y(_ boxPtr: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb(_ boxPtr: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending [String]) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure([String].bridgeJSLiftParameter()) + let closure = Unmanaged<_BridgeJSTypedClosureBox<() -> Bool>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure() + return result.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y_extern(_ callback: Int32) -> Void +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC_extern(_ callback: Int32) -> UnsafeMutableRawPointer #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y_extern(_ callback: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y(_ callback: Int32) -> Void { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y_extern(callback) -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 -#else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y_extern(boxPtr, file, line) -} - -private enum _BJS_Closure_20BridgeJSRuntimeTestssSaSb_y { - static func bridgeJSLift(_ callbackId: Int32) -> (sending [Bool]) -> Void { - let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] param0 in - #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() - let _ = param0.bridgeJSLowerParameter() - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y(callbackValue) - #else - fatalError("Only available on WebAssembly") - #endif - } - } -} - -extension JSTypedClosure where Signature == (sending [Bool]) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending [Bool]) -> Void) { - self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y, - body: body, - fileID: fileID, - line: line - ) - } -} - -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y(_ boxPtr: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending [Bool]) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure([Bool].bridgeJSLiftParameter()) - #else - fatalError("Only available on WebAssembly") - #endif -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y_extern(_ callback: Int32) -> Void -#else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y_extern(_ callback: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y(_ callback: Int32) -> Void { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y_extern(callback) -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 -#else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y_extern(boxPtr, file, line) -} - -private enum _BJS_Closure_20BridgeJSRuntimeTestssSaSd_y { - static func bridgeJSLift(_ callbackId: Int32) -> (sending [Double]) -> Void { - let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] param0 in - #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() - let _ = param0.bridgeJSLowerParameter() - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y(callbackValue) - #else - fatalError("Only available on WebAssembly") - #endif - } - } -} - -extension JSTypedClosure where Signature == (sending [Double]) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending [Double]) -> Void) { - self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y, - body: body, - fileID: fileID, - line: line - ) - } -} - -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y(_ boxPtr: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending [Double]) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure([Double].bridgeJSLiftParameter()) - #else - fatalError("Only available on WebAssembly") - #endif -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y_extern(_ callback: Int32, _ param0: Int32) -> Void -#else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y_extern(_ callback: Int32, _ param0: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y(_ callback: Int32, _ param0: Int32) -> Void { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y_extern(callback, param0) -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 -#else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y_extern(boxPtr, file, line) -} - -private enum _BJS_Closure_20BridgeJSRuntimeTestssSb_y { - static func bridgeJSLift(_ callbackId: Int32) -> (sending Bool) -> Void { - let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] param0 in - #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() - let param0Value = param0.bridgeJSLowerParameter() - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y(callbackValue, param0Value) - #else - fatalError("Only available on WebAssembly") - #endif - } - } -} - -extension JSTypedClosure where Signature == (sending Bool) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Bool) -> Void) { - self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y, - body: body, - fileID: fileID, - line: line - ) - } -} - -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { - #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending Bool) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(Bool.bridgeJSLiftParameter(param0)) - #else - fatalError("Only available on WebAssembly") - #endif -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y_extern(_ callback: Int32, _ param0: Float64) -> Void -#else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y_extern(_ callback: Int32, _ param0: Float64) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y(_ callback: Int32, _ param0: Float64) -> Void { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y_extern(callback, param0) -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 -#else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y_extern(boxPtr, file, line) -} - -private enum _BJS_Closure_20BridgeJSRuntimeTestssSd_y { - static func bridgeJSLift(_ callbackId: Int32) -> (sending Double) -> Void { - let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] param0 in - #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() - let param0Value = param0.bridgeJSLowerParameter() - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y(callbackValue, param0Value) - #else - fatalError("Only available on WebAssembly") - #endif - } - } -} - -extension JSTypedClosure where Signature == (sending Double) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Double) -> Void) { - self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y, - body: body, - fileID: fileID, - line: line - ) - } -} - -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Float64) -> Void { - #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending Double) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(Double.bridgeJSLiftParameter(param0)) - #else - fatalError("Only available on WebAssembly") - #endif -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0CaseId: Int32) -> Void -#else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0CaseId: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y(_ callback: Int32, _ param0IsSome: Int32, _ param0CaseId: Int32) -> Void { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y_extern(callback, param0IsSome, param0CaseId) -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 -#else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y_extern(boxPtr, file, line) -} - -private enum _BJS_Closure_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y { - static func bridgeJSLift(_ callbackId: Int32) -> (sending Optional) -> Void { - let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] param0 in - #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() - let (param0IsSome, param0CaseId) = param0.bridgeJSLowerParameter() - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y(callbackValue, param0IsSome, param0CaseId) - #else - fatalError("Only available on WebAssembly") - #endif - } - } -} - -extension JSTypedClosure where Signature == (sending Optional) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Optional) -> Void) { - self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y, - body: body, - fileID: fileID, - line: line - ) - } -} - -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0CaseId: Int32) -> Void { - #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending Optional) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(Optional.bridgeJSLiftParameter(param0IsSome, param0CaseId)) - #else - fatalError("Only available on WebAssembly") - #endif -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void -#else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y_extern(callback, param0IsSome, param0Bytes, param0Length) -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 -#else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y_extern(boxPtr, file, line) -} - -private enum _BJS_Closure_20BridgeJSRuntimeTestssSqSS_y { - static func bridgeJSLift(_ callbackId: Int32) -> (sending Optional) -> Void { - let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] param0 in - #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() - param0.bridgeJSWithLoweredParameter { (param0IsSome, param0Bytes, param0Length) in - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y(callbackValue, param0IsSome, param0Bytes, param0Length) - } - #else - fatalError("Only available on WebAssembly") - #endif - } - } -} - -extension JSTypedClosure where Signature == (sending Optional) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Optional) -> Void) { - self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y, - body: body, - fileID: fileID, - line: line - ) - } -} - -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { - #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending Optional) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Bytes, param0Length)) - #else - fatalError("Only available on WebAssembly") - #endif -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Float64) -> Void -#else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Float64) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Float64) -> Void { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y_extern(callback, param0IsSome, param0Value) -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 -#else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y_extern(boxPtr, file, line) -} - -private enum _BJS_Closure_20BridgeJSRuntimeTestssSqSd_y { - static func bridgeJSLift(_ callbackId: Int32) -> (sending Optional) -> Void { - let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] param0 in - #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() - let (param0IsSome, param0Value) = param0.bridgeJSLowerParameter() - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y(callbackValue, param0IsSome, param0Value) - #else - fatalError("Only available on WebAssembly") - #endif - } - } -} - -extension JSTypedClosure where Signature == (sending Optional) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Optional) -> Void) { - self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y, - body: body, - fileID: fileID, - line: line - ) - } -} - -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Value: Float64) -> Void { - #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending Optional) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) - #else - fatalError("Only available on WebAssembly") - #endif -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP_extern(_ callback: Int32) -> Int32 -#else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP_extern(_ callback: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP(_ callback: Int32) -> Int32 { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP_extern(callback) -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 -#else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP_extern(boxPtr, file, line) -} - -private enum _BJS_Closure_20BridgeJSRuntimeTestsy_13DataProcessorP { - static func bridgeJSLift(_ callbackId: Int32) -> () -> any DataProcessor { - let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] in - #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() - let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP(callbackValue) - return AnyDataProcessor.bridgeJSLiftReturn(ret) - #else - fatalError("Only available on WebAssembly") - #endif - } - } -} - -extension JSTypedClosure where Signature == () -> any DataProcessor { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping () -> any DataProcessor) { - self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP, - body: body, - fileID: fileID, - line: line - ) - } -} - -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP(_ boxPtr: UnsafeMutableRawPointer) -> Int32 { - #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<() -> any DataProcessor>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure() - return (result as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb_extern(_ callback: Int32) -> Int32 -#else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb_extern(_ callback: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb(_ callback: Int32) -> Int32 { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb_extern(callback) -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 -#else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb_extern(boxPtr, file, line) -} - -private enum _BJS_Closure_20BridgeJSRuntimeTestsy_Sb { - static func bridgeJSLift(_ callbackId: Int32) -> () -> Bool { - let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] in - #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() - let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb(callbackValue) - return Bool.bridgeJSLiftReturn(ret) - #else - fatalError("Only available on WebAssembly") - #endif - } - } -} - -extension JSTypedClosure where Signature == () -> Bool { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping () -> Bool) { - self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb, - body: body, - fileID: fileID, - line: line - ) - } -} - -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb(_ boxPtr: UnsafeMutableRawPointer) -> Int32 { - #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<() -> Bool>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure() - return result.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC_extern(_ callback: Int32) -> UnsafeMutableRawPointer -#else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC_extern(_ callback: Int32) -> UnsafeMutableRawPointer { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC_extern(_ callback: Int32) -> UnsafeMutableRawPointer { fatalError("Only available on WebAssembly") } #endif @@ -4094,6 +3395,91 @@ fileprivate func bjs_DataProcessor_optionalHelper_set_extern(_ jsObject: Int32, return bjs_DataProcessor_optionalHelper_set_extern(jsObject, newValueIsSome, newValuePointer) } +extension Severity: _BridgedSwiftCaseEnum { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + return bridgeJSRawValue + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> Severity { + return bridgeJSLiftParameter(value) + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> Severity { + return Severity(bridgeJSRawValue: value)! + } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { + return bridgeJSLowerParameter() + } + + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { + switch bridgeJSRawValue { + case 0: + self = .notice + case 1: + self = .warning + case 2: + self = .error + default: + return nil + } + } + + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { + switch self { + case .notice: + return 0 + case .warning: + return 1 + case .error: + return 2 + } + } +} + +extension Shape: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> Shape { + switch caseId { + case 0: + return .polygon(Polygon.bridgeFromJS(PolygonReference.bridgeJSStackPop())) + case 1: + return .empty + default: + fatalError("Unknown Shape case ID: \(caseId)") + } + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { + switch self { + case .polygon(let param0): + param0.bridgeToJS().bridgeJSStackPush() + return Int32(0) + case .empty: + return Int32(1) + } + } +} + +extension InnerTag: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> InnerTag { + switch caseId { + case 0: + return .payload(Int.bridgeJSStackPop()) + case 1: + return .empty + default: + fatalError("Unknown InnerTag case ID: \(caseId)") + } + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { + switch self { + case .payload(let param0): + param0.bridgeJSStackPush() + return Int32(0) + case .empty: + return Int32(1) + } + } +} + @_expose(wasm, "bjs_ArraySupportExports_static_roundTripIntArray") @_cdecl("bjs_ArraySupportExports_static_roundTripIntArray") public func _bjs_ArraySupportExports_static_roundTripIntArray() -> Void { @@ -4565,47 +3951,19 @@ public func _bjs_ArraySupportExports_static_multiOptionalArrayFirst() -> Void { #endif } -@_expose(wasm, "bjs_ArraySupportExports_static_multiOptionalArraySecond") -@_cdecl("bjs_ArraySupportExports_static_multiOptionalArraySecond") -public func _bjs_ArraySupportExports_static_multiOptionalArraySecond() -> Void { - #if arch(wasm32) - let _tmp_b = Optional<[String]>.bridgeJSLiftParameter() - let _tmp_a = Optional<[Int]>.bridgeJSLiftParameter() - let ret = ArraySupportExports.multiOptionalArraySecond(_: _tmp_a, _: _tmp_b) - ret.bridgeJSStackPush() - #else - fatalError("Only available on WebAssembly") - #endif -} - -extension AsyncImportedPayloadResult: _BridgedSwiftAssociatedValueEnum { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> AsyncImportedPayloadResult { - switch caseId { - case 0: - return .success(String.bridgeJSStackPop()) - case 1: - return .failure(Int.bridgeJSStackPop()) - case 2: - return .idle - default: - fatalError("Unknown AsyncImportedPayloadResult case ID: \(caseId)") - } - } - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { - switch self { - case .success(let param0): - param0.bridgeJSStackPush() - return Int32(0) - case .failure(let param0): - param0.bridgeJSStackPush() - return Int32(1) - case .idle: - return Int32(2) - } - } -} - +@_expose(wasm, "bjs_ArraySupportExports_static_multiOptionalArraySecond") +@_cdecl("bjs_ArraySupportExports_static_multiOptionalArraySecond") +public func _bjs_ArraySupportExports_static_multiOptionalArraySecond() -> Void { + #if arch(wasm32) + let _tmp_b = Optional<[String]>.bridgeJSLiftParameter() + let _tmp_a = Optional<[Int]>.bridgeJSLiftParameter() + let ret = ArraySupportExports.multiOptionalArraySecond(_: _tmp_a, _: _tmp_b) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_DefaultArgumentExports_static_testStringDefault") @_cdecl("bjs_DefaultArgumentExports_static_testStringDefault") public func _bjs_DefaultArgumentExports_static_testStringDefault(_ messageBytes: Int32, _ messageLength: Int32) -> Void { @@ -4917,34 +4275,6 @@ extension TSDirection: _BridgedSwiftCaseEnum { extension TSTheme: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } -extension AsyncPayloadResult: _BridgedSwiftAssociatedValueEnum { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> AsyncPayloadResult { - switch caseId { - case 0: - return .success(String.bridgeJSStackPop()) - case 1: - return .failure(Int.bridgeJSStackPop()) - case 2: - return .idle - default: - fatalError("Unknown AsyncPayloadResult case ID: \(caseId)") - } - } - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { - switch self { - case .success(let param0): - param0.bridgeJSStackPush() - return Int32(0) - case .failure(let param0): - param0.bridgeJSStackPush() - return Int32(1) - case .idle: - return Int32(2) - } - } -} - @_expose(wasm, "bjs_Utils_StringUtils_static_uppercase") @_cdecl("bjs_Utils_StringUtils_static_uppercase") public func _bjs_Utils_StringUtils_static_uppercase(_ textBytes: Int32, _ textLength: Int32) -> Void { @@ -5649,73 +4979,6 @@ public func _bjs_NestedStructGroupB_static_roundtripMetadata() -> Void { #endif } -extension LightColor: _BridgedSwiftCaseEnum { - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { - return bridgeJSRawValue - } - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> LightColor { - return bridgeJSLiftParameter(value) - } - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> LightColor { - return LightColor(bridgeJSRawValue: value)! - } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { - return bridgeJSLowerParameter() - } - - @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { - switch bridgeJSRawValue { - case 0: - self = .red - case 1: - self = .yellow - case 2: - self = .green - default: - return nil - } - } - - @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { - switch self { - case .red: - return 0 - case .yellow: - return 1 - case .green: - return 2 - } - } -} - -extension ImportedPayloadSignal: _BridgedSwiftAssociatedValueEnum { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> ImportedPayloadSignal { - switch caseId { - case 0: - return .start(String.bridgeJSStackPop()) - case 1: - return .stop(Int.bridgeJSStackPop()) - case 2: - return .idle - default: - fatalError("Unknown ImportedPayloadSignal case ID: \(caseId)") - } - } - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { - switch self { - case .start(let param0): - param0.bridgeJSStackPush() - return Int32(0) - case .stop(let param0): - param0.bridgeJSStackPush() - return Int32(1) - case .idle: - return Int32(2) - } - } -} - @_expose(wasm, "bjs_IntegerTypesSupportExports_static_roundTripInt") @_cdecl("bjs_IntegerTypesSupportExports_static_roundTripInt") public func _bjs_IntegerTypesSupportExports_static_roundTripInt(_ v: Int32) -> Int32 { @@ -6270,6 +5533,122 @@ extension APIOptionalResult: _BridgedSwiftAssociatedValueEnum { } } +extension JSCoordinate: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> JSCoordinate { + let longitude = Double.bridgeJSStackPop() + let latitude = Double.bridgeJSStackPop() + return JSCoordinate(latitude: latitude, longitude: longitude) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.latitude.bridgeJSStackPush() + self.longitude.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_JSCoordinate(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_JSCoordinate())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_JSCoordinate") +fileprivate func _bjs_struct_lower_JSCoordinate_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_JSCoordinate_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_JSCoordinate(_ objectId: Int32) -> Void { + return _bjs_struct_lower_JSCoordinate_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_JSCoordinate") +fileprivate func _bjs_struct_lift_JSCoordinate_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_JSCoordinate_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_JSCoordinate() -> Int32 { + return _bjs_struct_lift_JSCoordinate_extern() +} + +@_expose(wasm, "bjs_JSCoordinate_init") +@_cdecl("bjs_JSCoordinate_init") +public func _bjs_JSCoordinate_init(_ latitude: Float64, _ longitude: Float64) -> Void { + #if arch(wasm32) + let ret = JSCoordinate(latitude: Double.bridgeJSLiftParameter(latitude), longitude: Double.bridgeJSLiftParameter(longitude)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension SessionState: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> SessionState { + let token = String.bridgeJSStackPop() + return SessionState(token: token) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.token.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_SessionState(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_SessionState())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_SessionState") +fileprivate func _bjs_struct_lower_SessionState_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_SessionState_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_SessionState(_ objectId: Int32) -> Void { + return _bjs_struct_lower_SessionState_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_SessionState") +fileprivate func _bjs_struct_lift_SessionState_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_SessionState_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_SessionState() -> Int32 { + return _bjs_struct_lift_SessionState_extern() +} + +@_expose(wasm, "bjs_SessionState_init") +@_cdecl("bjs_SessionState_init") +public func _bjs_SessionState_init(_ tokenBytes: Int32, _ tokenLength: Int32) -> Void { + #if arch(wasm32) + let ret = SessionState(token: String.bridgeJSLiftParameter(tokenBytes, tokenLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + extension NestedStructGroupA.Metadata: _BridgedSwiftStruct { @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> NestedStructGroupA.Metadata { let count = Int.bridgeJSStackPop() @@ -7544,197 +6923,351 @@ fileprivate func _bjs_struct_lift_FooContainer_extern() -> Int32 { return _bjs_struct_lift_FooContainer_extern() } -extension ArrayMembers: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> ArrayMembers { - let optStrings = Optional<[String]>.bridgeJSStackPop() - let ints = [Int].bridgeJSStackPop() - return ArrayMembers(ints: ints, optStrings: optStrings) - } - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { - self.ints.bridgeJSStackPush() - self.optStrings.bridgeJSStackPush() - } +extension ArrayMembers: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> ArrayMembers { + let optStrings = Optional<[String]>.bridgeJSStackPop() + let ints = [Int].bridgeJSStackPop() + return ArrayMembers(ints: ints, optStrings: optStrings) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.ints.bridgeJSStackPush() + self.optStrings.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_ArrayMembers(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_ArrayMembers())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_ArrayMembers") +fileprivate func _bjs_struct_lower_ArrayMembers_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_ArrayMembers_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_ArrayMembers(_ objectId: Int32) -> Void { + return _bjs_struct_lower_ArrayMembers_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_ArrayMembers") +fileprivate func _bjs_struct_lift_ArrayMembers_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_ArrayMembers_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_ArrayMembers() -> Int32 { + return _bjs_struct_lift_ArrayMembers_extern() +} + +@_expose(wasm, "bjs_ArrayMembers_sumValues") +@_cdecl("bjs_ArrayMembers_sumValues") +public func _bjs_ArrayMembers_sumValues() -> Int32 { + #if arch(wasm32) + let ret = ArrayMembers.bridgeJSLiftParameter().sumValues(_: [Int].bridgeJSStackPop()) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ArrayMembers_firstString") +@_cdecl("bjs_ArrayMembers_firstString") +public func _bjs_ArrayMembers_firstString() -> Void { + #if arch(wasm32) + let ret = ArrayMembers.bridgeJSLiftParameter().firstString(_: [String].bridgeJSStackPop()) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_makeTag") +@_cdecl("bjs_makeTag") +public func _bjs_makeTag(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = makeTag(_: String.bridgeJSLiftParameter(nameBytes, nameLength)) + return ret.bridgeToJS().bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripPolygon") +@_cdecl("bjs_roundTripPolygon") +public func _bjs_roundTripPolygon(_ polygon: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = roundTripPolygon(_: Polygon.bridgeFromJS(PolygonReference.bridgeJSLiftParameter(polygon))) + return ret.bridgeToJS().bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_appendVertex") +@_cdecl("bjs_appendVertex") +public func _bjs_appendVertex(_ polygon: UnsafeMutableRawPointer, _ value: Float64) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = appendVertex(_: Polygon.bridgeFromJS(PolygonReference.bridgeJSLiftParameter(polygon)), _: Double.bridgeJSLiftParameter(value)) + return ret.bridgeToJS().bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_optionalRoundTripPolygon") +@_cdecl("bjs_optionalRoundTripPolygon") +public func _bjs_optionalRoundTripPolygon(_ polygonIsSome: Int32, _ polygonValue: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = optionalRoundTripPolygon(_: Optional.bridgeJSLiftParameter(polygonIsSome, polygonValue).map { Polygon.bridgeFromJS($0) }) + return ret.map { $0.bridgeToJS() }.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_polygonVertexCount") +@_cdecl("bjs_polygonVertexCount") +public func _bjs_polygonVertexCount(_ polygon: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let ret = polygonVertexCount(_: Polygon.bridgeFromJS(PolygonReference.bridgeJSLiftParameter(polygon))) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripPolygonArray") +@_cdecl("bjs_roundTripPolygonArray") +public func _bjs_roundTripPolygonArray() -> Void { + #if arch(wasm32) + let ret = roundTripPolygonArray(_: [PolygonReference].bridgeJSStackPop().map { Polygon.bridgeFromJS($0) }) + ret.map { $0.bridgeToJS() }.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} - init(unsafelyCopying jsObject: JSObject) { - _bjs_struct_lower_ArrayMembers(jsObject.bridgeJSLowerParameter()) - self = Self.bridgeJSStackPop() - } +@_expose(wasm, "bjs_concatPolygons") +@_cdecl("bjs_concatPolygons") +public func _bjs_concatPolygons() -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = concatPolygons(_: [PolygonReference].bridgeJSStackPop().map { Polygon.bridgeFromJS($0) }) + return ret.bridgeToJS().bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} - func toJSObject() -> JSObject { - let __bjs_self = self - __bjs_self.bridgeJSStackPush() - return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_ArrayMembers())) +@_expose(wasm, "bjs_validatePolygon") +@_cdecl("bjs_validatePolygon") +public func _bjs_validatePolygon(_ polygon: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + #if arch(wasm32) + do { + let ret = try validatePolygon(_: Polygon.bridgeFromJS(PolygonReference.bridgeJSLiftParameter(polygon))) + return ret.bridgeToJS().bridgeJSLowerReturn() + } catch let error { + if let error = error.thrownValue.object { + withExtendedLifetime(error) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } else { + let jsError = JSError(message: String(describing: error)) + withExtendedLifetime(jsError.jsObject) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } + return UnsafeMutableRawPointer(bitPattern: -1).unsafelyUnwrapped } + #else + fatalError("Only available on WebAssembly") + #endif } -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_ArrayMembers") -fileprivate func _bjs_struct_lower_ArrayMembers_extern(_ objectId: Int32) -> Void -#else -fileprivate func _bjs_struct_lower_ArrayMembers_extern(_ objectId: Int32) -> Void { +@_expose(wasm, "bjs_splitPolygon") +@_cdecl("bjs_splitPolygon") +public func _bjs_splitPolygon(_ polygon: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = splitPolygon(_: Polygon.bridgeFromJS(PolygonReference.bridgeJSLiftParameter(polygon))) + ret.map { $0.bridgeToJS() }.bridgeJSStackPush() + #else fatalError("Only available on WebAssembly") + #endif } -#endif -@inline(never) fileprivate func _bjs_struct_lower_ArrayMembers(_ objectId: Int32) -> Void { - return _bjs_struct_lower_ArrayMembers_extern(objectId) + +@_expose(wasm, "bjs_incrementToken") +@_cdecl("bjs_incrementToken") +public func _bjs_incrementToken(_ token: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = incrementToken(_: Token.bridgeFromJS(TokenReference.bridgeJSLiftParameter(token))) + return ret.bridgeToJS().bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif } -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_ArrayMembers") -fileprivate func _bjs_struct_lift_ArrayMembers_extern() -> Int32 -#else -fileprivate func _bjs_struct_lift_ArrayMembers_extern() -> Int32 { +@_expose(wasm, "bjs_makeToken") +@_cdecl("bjs_makeToken") +public func _bjs_makeToken(_ value: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = makeToken(_: Int.bridgeJSLiftParameter(value)) + return ret.bridgeToJS().bridgeJSLowerReturn() + #else fatalError("Only available on WebAssembly") + #endif } -#endif -@inline(never) fileprivate func _bjs_struct_lift_ArrayMembers() -> Int32 { - return _bjs_struct_lift_ArrayMembers_extern() + +@_expose(wasm, "bjs_makePolygonInspector") +@_cdecl("bjs_makePolygonInspector") +public func _bjs_makePolygonInspector() -> Int32 { + #if arch(wasm32) + let ret = makePolygonInspector() + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif } -@_expose(wasm, "bjs_ArrayMembers_sumValues") -@_cdecl("bjs_ArrayMembers_sumValues") -public func _bjs_ArrayMembers_sumValues() -> Int32 { +@_expose(wasm, "bjs_asyncMakePolygon") +@_cdecl("bjs_asyncMakePolygon") +public func _bjs_asyncMakePolygon(_ labelBytes: Int32, _ labelLength: Int32) -> Int32 { #if arch(wasm32) - let ret = ArrayMembers.bridgeJSLiftParameter().sumValues(_: [Int].bridgeJSStackPop()) + let ret = JSPromise.async { + return await asyncMakePolygon(_: String.bridgeJSLiftParameter(labelBytes, labelLength)).bridgeToJS().jsValue + }.jsObject return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_ArrayMembers_firstString") -@_cdecl("bjs_ArrayMembers_firstString") -public func _bjs_ArrayMembers_firstString() -> Void { +@_expose(wasm, "bjs_roundTripOptionalPolygonArray") +@_cdecl("bjs_roundTripOptionalPolygonArray") +public func _bjs_roundTripOptionalPolygonArray() -> Void { #if arch(wasm32) - let ret = ArrayMembers.bridgeJSLiftParameter().firstString(_: [String].bridgeJSStackPop()) - return ret.bridgeJSLowerReturn() + let ret = roundTripOptionalPolygonArray(_: [Optional].bridgeJSStackPop().map { $0.map { Polygon.bridgeFromJS($0) } }) + ret.map { $0.map { $0.bridgeToJS() } }.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_awaitAsyncCallback") -@_cdecl("bjs_awaitAsyncCallback") -public func _bjs_awaitAsyncCallback(_ fetch: Int32) -> Int32 { +@_expose(wasm, "bjs_makeTagHolder") +@_cdecl("bjs_makeTagHolder") +public func _bjs_makeTagHolder(_ nameBytes: Int32, _ nameLength: Int32, _ version: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - return _bjs_makePromise(resolve: Promise_resolve_SS, reject: Promise_reject) { () async throws(JSException) -> String in - return try await awaitAsyncCallback(_: _BJS_Closure_20BridgeJSRuntimeTestsYaKSS_SS.bridgeJSLift(fetch)) - } + let ret = makeTagHolder(_: String.bridgeJSLiftParameter(nameBytes, nameLength), _: Int.bridgeJSLiftParameter(version)) + return ret.bridgeToJS().bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeAsyncParser") -@_cdecl("bjs_makeAsyncParser") -public func _bjs_makeAsyncParser() -> Int32 { +@_expose(wasm, "bjs_roundTripCoordinate") +@_cdecl("bjs_roundTripCoordinate") +public func _bjs_roundTripCoordinate() -> Void { #if arch(wasm32) - let ret = makeAsyncParser() - return ret.bridgeJSLowerReturn() + let ret = roundTripCoordinate(_: Coordinate.bridgeFromJS(JSCoordinate.bridgeJSLiftParameter())) + return ret.bridgeToJS().bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeAsyncEcho") -@_cdecl("bjs_makeAsyncEcho") -public func _bjs_makeAsyncEcho() -> Int32 { +@_expose(wasm, "bjs_roundTripPriority") +@_cdecl("bjs_roundTripPriority") +public func _bjs_roundTripPriority(_ priority: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = makeAsyncEcho() - return ret.bridgeJSLowerReturn() + let ret = roundTripPriority(_: Priority.bridgeFromJS(PriorityReference.bridgeJSLiftParameter(priority))) + return ret.bridgeToJS().bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeAsyncRecorder") -@_cdecl("bjs_makeAsyncRecorder") -public func _bjs_makeAsyncRecorder() -> Int32 { +@_expose(wasm, "bjs_roundTripAlert") +@_cdecl("bjs_roundTripAlert") +public func _bjs_roundTripAlert(_ alert: Int32) -> Int32 { #if arch(wasm32) - let ret = makeAsyncRecorder() - return ret.bridgeJSLowerReturn() + let ret = roundTripAlert(_: Alert.bridgeFromJS(Severity.bridgeJSLiftParameter(alert))) + return ret.bridgeToJS().bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_lastRecordedValue") -@_cdecl("bjs_lastRecordedValue") -public func _bjs_lastRecordedValue() -> Void { +@_expose(wasm, "bjs_makeAlert") +@_cdecl("bjs_makeAlert") +public func _bjs_makeAlert(_ level: Int32) -> Int32 { #if arch(wasm32) - let ret = lastRecordedValue() - return ret.bridgeJSLowerReturn() + let ret = makeAlert(_: Severity.bridgeJSLiftParameter(level)) + return ret.bridgeToJS().bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeAsyncPayloadLoader") -@_cdecl("bjs_makeAsyncPayloadLoader") -public func _bjs_makeAsyncPayloadLoader() -> Int32 { +@_expose(wasm, "bjs_roundTripSession") +@_cdecl("bjs_roundTripSession") +public func _bjs_roundTripSession() -> Void { #if arch(wasm32) - let ret = makeAsyncPayloadLoader() - return ret.bridgeJSLowerReturn() + let ret = roundTripSession(_: Session.bridgeFromJS(SessionState.bridgeJSLiftParameter())) + return ret.bridgeToJS().bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_awaitPayloadCallback") -@_cdecl("bjs_awaitPayloadCallback") -public func _bjs_awaitPayloadCallback(_ load: Int32) -> Int32 { +@_expose(wasm, "bjs_makeSession") +@_cdecl("bjs_makeSession") +public func _bjs_makeSession(_ tokenBytes: Int32, _ tokenLength: Int32) -> Void { #if arch(wasm32) - return _bjs_makePromise(resolve: Promise_resolve_SS, reject: Promise_reject) { () async throws(JSException) -> String in - return try await awaitPayloadCallback(_: _BJS_Closure_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO.bridgeJSLift(load)) - } + let ret = makeSession(_: String.bridgeJSLiftParameter(tokenBytes, tokenLength)) + return ret.bridgeToJS().bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeAsyncPointMaker") -@_cdecl("bjs_makeAsyncPointMaker") -public func _bjs_makeAsyncPointMaker() -> Int32 { +@_expose(wasm, "bjs_roundTripShape") +@_cdecl("bjs_roundTripShape") +public func _bjs_roundTripShape(_ s: Int32) -> Void { #if arch(wasm32) - let ret = makeAsyncPointMaker() + let ret = roundTripShape(_: Shape.bridgeJSLiftParameter(s)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeThrowingParser") -@_cdecl("bjs_makeThrowingParser") -public func _bjs_makeThrowingParser() -> Int32 { +@_expose(wasm, "bjs_makeShapePolygon") +@_cdecl("bjs_makeShapePolygon") +public func _bjs_makeShapePolygon(_ polygon: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = makeThrowingParser() + let ret = makeShapePolygon(_: Polygon.bridgeFromJS(PolygonReference.bridgeJSLiftParameter(polygon))) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_runValidator") -@_cdecl("bjs_runValidator") -public func _bjs_runValidator(_ validate: Int32) -> Int32 { +@_expose(wasm, "bjs_makeShapeEmpty") +@_cdecl("bjs_makeShapeEmpty") +public func _bjs_makeShapeEmpty() -> Void { #if arch(wasm32) - do { - let ret = try runValidator(_: _BJS_Closure_20BridgeJSRuntimeTestsKSS_Sb.bridgeJSLift(validate)) - return ret.bridgeJSLowerReturn() - } catch let error { - if let error = error.thrownValue.object { - withExtendedLifetime(error) { - _swift_js_throw(Int32(bitPattern: $0.id)) - } - } else { - let jsError = JSError(message: error.description) - withExtendedLifetime(jsError.jsObject) { - _swift_js_throw(Int32(bitPattern: $0.id)) - } - } - return 0 - } + let ret = makeShapeEmpty() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -7939,7 +7472,7 @@ public func _bjs_makeImportedFoo(_ valueBytes: Int32, _ valueLength: Int32) -> I _swift_js_throw(Int32(bitPattern: $0.id)) } } else { - let jsError = JSError(message: error.description) + let jsError = JSError(message: String(describing: error)) withExtendedLifetime(jsError.jsObject) { _swift_js_throw(Int32(bitPattern: $0.id)) } @@ -7951,17 +7484,6 @@ public func _bjs_makeImportedFoo(_ valueBytes: Int32, _ valueLength: Int32) -> I #endif } -@_expose(wasm, "bjs_roundTripOptionalImportedClass") -@_cdecl("bjs_roundTripOptionalImportedClass") -public func _bjs_roundTripOptionalImportedClass(_ vIsSome: Int32, _ vValue: Int32) -> Void { - #if arch(wasm32) - let ret = roundTripOptionalImportedClass(v: Optional.bridgeJSLiftParameter(vIsSome, vValue)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - @_expose(wasm, "bjs_throwsSwiftError") @_cdecl("bjs_throwsSwiftError") public func _bjs_throwsSwiftError(_ shouldThrow: Int32) -> Void { @@ -7974,7 +7496,7 @@ public func _bjs_throwsSwiftError(_ shouldThrow: Int32) -> Void { _swift_js_throw(Int32(bitPattern: $0.id)) } } else { - let jsError = JSError(message: error.description) + let jsError = JSError(message: String(describing: error)) withExtendedLifetime(jsError.jsObject) { _swift_js_throw(Int32(bitPattern: $0.id)) } @@ -7999,7 +7521,7 @@ public func _bjs_throwsWithIntResult() -> Int32 { _swift_js_throw(Int32(bitPattern: $0.id)) } } else { - let jsError = JSError(message: error.description) + let jsError = JSError(message: String(describing: error)) withExtendedLifetime(jsError.jsObject) { _swift_js_throw(Int32(bitPattern: $0.id)) } @@ -8024,7 +7546,7 @@ public func _bjs_throwsWithStringResult() -> Void { _swift_js_throw(Int32(bitPattern: $0.id)) } } else { - let jsError = JSError(message: error.description) + let jsError = JSError(message: String(describing: error)) withExtendedLifetime(jsError.jsObject) { _swift_js_throw(Int32(bitPattern: $0.id)) } @@ -8049,7 +7571,7 @@ public func _bjs_throwsWithBoolResult() -> Int32 { _swift_js_throw(Int32(bitPattern: $0.id)) } } else { - let jsError = JSError(message: error.description) + let jsError = JSError(message: String(describing: error)) withExtendedLifetime(jsError.jsObject) { _swift_js_throw(Int32(bitPattern: $0.id)) } @@ -8074,7 +7596,7 @@ public func _bjs_throwsWithFloatResult() -> Float32 { _swift_js_throw(Int32(bitPattern: $0.id)) } } else { - let jsError = JSError(message: error.description) + let jsError = JSError(message: String(describing: error)) withExtendedLifetime(jsError.jsObject) { _swift_js_throw(Int32(bitPattern: $0.id)) } @@ -8099,7 +7621,7 @@ public func _bjs_throwsWithDoubleResult() -> Float64 { _swift_js_throw(Int32(bitPattern: $0.id)) } } else { - let jsError = JSError(message: error.description) + let jsError = JSError(message: String(describing: error)) withExtendedLifetime(jsError.jsObject) { _swift_js_throw(Int32(bitPattern: $0.id)) } @@ -8124,7 +7646,7 @@ public func _bjs_throwsWithSwiftHeapObjectResult() -> UnsafeMutableRawPointer { _swift_js_throw(Int32(bitPattern: $0.id)) } } else { - let jsError = JSError(message: error.description) + let jsError = JSError(message: String(describing: error)) withExtendedLifetime(jsError.jsObject) { _swift_js_throw(Int32(bitPattern: $0.id)) } @@ -8149,7 +7671,7 @@ public func _bjs_throwsWithJSObjectResult() -> Int32 { _swift_js_throw(Int32(bitPattern: $0.id)) } } else { - let jsError = JSError(message: error.description) + let jsError = JSError(message: String(describing: error)) withExtendedLifetime(jsError.jsObject) { _swift_js_throw(Int32(bitPattern: $0.id)) } @@ -8161,27 +7683,14 @@ public func _bjs_throwsWithJSObjectResult() -> Int32 { #endif } -@_expose(wasm, "bjs_zeroArgAsyncThrows") -@_cdecl("bjs_zeroArgAsyncThrows") -public func _bjs_zeroArgAsyncThrows() -> Int32 { - #if arch(wasm32) - let __bjs_capture = 0 - return _bjs_makePromise(resolve: Promise_resolve_SS, reject: Promise_reject) { [__bjs_capture] () async throws(JSException) -> String in - _ = __bjs_capture - return try await zeroArgAsyncThrows() - } - #else - fatalError("Only available on WebAssembly") - #endif -} - @_expose(wasm, "bjs_asyncRoundTripVoid") @_cdecl("bjs_asyncRoundTripVoid") public func _bjs_asyncRoundTripVoid() -> Int32 { #if arch(wasm32) - return _bjs_makePromise(resolve: Promise_resolve_y, reject: Promise_reject) { + let ret = JSPromise.async { await asyncRoundTripVoid() - } + }.jsObject + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -8191,9 +7700,10 @@ public func _bjs_asyncRoundTripVoid() -> Int32 { @_cdecl("bjs_asyncRoundTripInt") public func _bjs_asyncRoundTripInt(_ v: Int32) -> Int32 { #if arch(wasm32) - return _bjs_makePromise(resolve: Promise_resolve_Si, reject: Promise_reject) { - return await asyncRoundTripInt(v: Int.bridgeJSLiftParameter(v)) - } + let ret = JSPromise.async { + return await asyncRoundTripInt(v: Int.bridgeJSLiftParameter(v)).jsValue + }.jsObject + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -8203,9 +7713,10 @@ public func _bjs_asyncRoundTripInt(_ v: Int32) -> Int32 { @_cdecl("bjs_asyncRoundTripFloat") public func _bjs_asyncRoundTripFloat(_ v: Float32) -> Int32 { #if arch(wasm32) - return _bjs_makePromise(resolve: Promise_resolve_Sf, reject: Promise_reject) { - return await asyncRoundTripFloat(v: Float.bridgeJSLiftParameter(v)) - } + let ret = JSPromise.async { + return await asyncRoundTripFloat(v: Float.bridgeJSLiftParameter(v)).jsValue + }.jsObject + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -8215,9 +7726,10 @@ public func _bjs_asyncRoundTripFloat(_ v: Float32) -> Int32 { @_cdecl("bjs_asyncRoundTripDouble") public func _bjs_asyncRoundTripDouble(_ v: Float64) -> Int32 { #if arch(wasm32) - return _bjs_makePromise(resolve: Promise_resolve_Sd, reject: Promise_reject) { - return await asyncRoundTripDouble(v: Double.bridgeJSLiftParameter(v)) - } + let ret = JSPromise.async { + return await asyncRoundTripDouble(v: Double.bridgeJSLiftParameter(v)).jsValue + }.jsObject + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -8227,9 +7739,10 @@ public func _bjs_asyncRoundTripDouble(_ v: Float64) -> Int32 { @_cdecl("bjs_asyncRoundTripBool") public func _bjs_asyncRoundTripBool(_ v: Int32) -> Int32 { #if arch(wasm32) - return _bjs_makePromise(resolve: Promise_resolve_Sb, reject: Promise_reject) { - return await asyncRoundTripBool(v: Bool.bridgeJSLiftParameter(v)) - } + let ret = JSPromise.async { + return await asyncRoundTripBool(v: Bool.bridgeJSLiftParameter(v)).jsValue + }.jsObject + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -8239,9 +7752,10 @@ public func _bjs_asyncRoundTripBool(_ v: Int32) -> Int32 { @_cdecl("bjs_asyncRoundTripString") public func _bjs_asyncRoundTripString(_ vBytes: Int32, _ vLength: Int32) -> Int32 { #if arch(wasm32) - return _bjs_makePromise(resolve: Promise_resolve_SS, reject: Promise_reject) { - return await asyncRoundTripString(v: String.bridgeJSLiftParameter(vBytes, vLength)) - } + let ret = JSPromise.async { + return await asyncRoundTripString(v: String.bridgeJSLiftParameter(vBytes, vLength)).jsValue + }.jsObject + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -8251,9 +7765,10 @@ public func _bjs_asyncRoundTripString(_ vBytes: Int32, _ vLength: Int32) -> Int3 @_cdecl("bjs_asyncRoundTripSwiftHeapObject") public func _bjs_asyncRoundTripSwiftHeapObject(_ v: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - return _bjs_makePromise(resolve: Promise_resolve_7GreeterC, reject: Promise_reject) { - return await asyncRoundTripSwiftHeapObject(v: Greeter.bridgeJSLiftParameter(v)) - } + let ret = JSPromise.async { + return await asyncRoundTripSwiftHeapObject(v: Greeter.bridgeJSLiftParameter(v)).jsValue + }.jsObject + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -8263,9 +7778,10 @@ public func _bjs_asyncRoundTripSwiftHeapObject(_ v: UnsafeMutableRawPointer) -> @_cdecl("bjs_asyncRoundTripJSObject") public func _bjs_asyncRoundTripJSObject(_ v: Int32) -> Int32 { #if arch(wasm32) - return _bjs_makePromise(resolve: Promise_resolve_8JSObjectC, reject: Promise_reject) { - return await asyncRoundTripJSObject(v: JSObject.bridgeJSLiftParameter(v)) - } + let ret = JSPromise.async { + return await asyncRoundTripJSObject(v: JSObject.bridgeJSLiftParameter(v)).jsValue + }.jsObject + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -8303,239 +7819,89 @@ public func _bjs_useCalculator(_ calc: UnsafeMutableRawPointer, _ x: Int32, _ y: #endif } -@_expose(wasm, "bjs_testGreeterToJSValue") -@_cdecl("bjs_testGreeterToJSValue") -public func _bjs_testGreeterToJSValue() -> Int32 { - #if arch(wasm32) - let ret = testGreeterToJSValue() - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_testCalculatorToJSValue") -@_cdecl("bjs_testCalculatorToJSValue") -public func _bjs_testCalculatorToJSValue() -> Int32 { - #if arch(wasm32) - let ret = testCalculatorToJSValue() - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_testSwiftClassAsJSValue") -@_cdecl("bjs_testSwiftClassAsJSValue") -public func _bjs_testSwiftClassAsJSValue(_ greeter: UnsafeMutableRawPointer) -> Int32 { - #if arch(wasm32) - let ret = testSwiftClassAsJSValue(greeter: Greeter.bridgeJSLiftParameter(greeter)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_setDirection") -@_cdecl("bjs_setDirection") -public func _bjs_setDirection(_ direction: Int32) -> Int32 { - #if arch(wasm32) - let ret = setDirection(_: Direction.bridgeJSLiftParameter(direction)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_getDirection") -@_cdecl("bjs_getDirection") -public func _bjs_getDirection() -> Int32 { - #if arch(wasm32) - let ret = getDirection() - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_processDirection") -@_cdecl("bjs_processDirection") -public func _bjs_processDirection(_ input: Int32) -> Int32 { - #if arch(wasm32) - let ret = processDirection(_: Direction.bridgeJSLiftParameter(input)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_setTheme") -@_cdecl("bjs_setTheme") -public func _bjs_setTheme(_ themeBytes: Int32, _ themeLength: Int32) -> Void { - #if arch(wasm32) - let ret = setTheme(_: Theme.bridgeJSLiftParameter(themeBytes, themeLength)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_getTheme") -@_cdecl("bjs_getTheme") -public func _bjs_getTheme() -> Void { - #if arch(wasm32) - let ret = getTheme() - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_asyncRoundTripTheme") -@_cdecl("bjs_asyncRoundTripTheme") -public func _bjs_asyncRoundTripTheme(_ vBytes: Int32, _ vLength: Int32) -> Int32 { - #if arch(wasm32) - return _bjs_makePromise(resolve: Promise_resolve_5ThemeO, reject: Promise_reject) { - return await asyncRoundTripTheme(_: Theme.bridgeJSLiftParameter(vBytes, vLength)) - } - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_asyncRoundTripDirection") -@_cdecl("bjs_asyncRoundTripDirection") -public func _bjs_asyncRoundTripDirection(_ v: Int32) -> Int32 { - #if arch(wasm32) - return _bjs_makePromise(resolve: Promise_resolve_9DirectionO, reject: Promise_reject) { - return await asyncRoundTripDirection(_: Direction.bridgeJSLiftParameter(v)) - } - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_asyncRoundTripOptionalTheme") -@_cdecl("bjs_asyncRoundTripOptionalTheme") -public func _bjs_asyncRoundTripOptionalTheme(_ vIsSome: Int32, _ vBytes: Int32, _ vLength: Int32) -> Int32 { - #if arch(wasm32) - return _bjs_makePromise(resolve: Promise_resolve_Sq5ThemeO, reject: Promise_reject) { - return await asyncRoundTripOptionalTheme(_: Optional.bridgeJSLiftParameter(vIsSome, vBytes, vLength)) - } - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_asyncRoundTripOptionalDirection") -@_cdecl("bjs_asyncRoundTripOptionalDirection") -public func _bjs_asyncRoundTripOptionalDirection(_ vIsSome: Int32, _ vValue: Int32) -> Int32 { - #if arch(wasm32) - return _bjs_makePromise(resolve: Promise_resolve_Sq9DirectionO, reject: Promise_reject) { - return await asyncRoundTripOptionalDirection(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) - } - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_asyncRoundTripDirectionArray") -@_cdecl("bjs_asyncRoundTripDirectionArray") -public func _bjs_asyncRoundTripDirectionArray() -> Int32 { +@_expose(wasm, "bjs_testGreeterToJSValue") +@_cdecl("bjs_testGreeterToJSValue") +public func _bjs_testGreeterToJSValue() -> Int32 { #if arch(wasm32) - let _tmp_v = [Direction].bridgeJSStackPop() - return _bjs_makePromise(resolve: Promise_resolve_Sa9DirectionO, reject: Promise_reject) { - return await asyncRoundTripDirectionArray(_: _tmp_v) - } + let ret = testGreeterToJSValue() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_asyncRoundTripDirectionDict") -@_cdecl("bjs_asyncRoundTripDirectionDict") -public func _bjs_asyncRoundTripDirectionDict() -> Int32 { +@_expose(wasm, "bjs_testCalculatorToJSValue") +@_cdecl("bjs_testCalculatorToJSValue") +public func _bjs_testCalculatorToJSValue() -> Int32 { #if arch(wasm32) - let _tmp_v = [String: Direction].bridgeJSLiftParameter() - return _bjs_makePromise(resolve: Promise_resolve_SD9DirectionO, reject: Promise_reject) { - return await asyncRoundTripDirectionDict(_: _tmp_v) - } + let ret = testCalculatorToJSValue() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_asyncRoundTripThemeArray") -@_cdecl("bjs_asyncRoundTripThemeArray") -public func _bjs_asyncRoundTripThemeArray() -> Int32 { +@_expose(wasm, "bjs_testSwiftClassAsJSValue") +@_cdecl("bjs_testSwiftClassAsJSValue") +public func _bjs_testSwiftClassAsJSValue(_ greeter: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let _tmp_v = [Theme].bridgeJSStackPop() - return _bjs_makePromise(resolve: Promise_resolve_Sa5ThemeO, reject: Promise_reject) { - return await asyncRoundTripThemeArray(_: _tmp_v) - } + let ret = testSwiftClassAsJSValue(greeter: Greeter.bridgeJSLiftParameter(greeter)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_asyncRoundTripThemeDict") -@_cdecl("bjs_asyncRoundTripThemeDict") -public func _bjs_asyncRoundTripThemeDict() -> Int32 { +@_expose(wasm, "bjs_setDirection") +@_cdecl("bjs_setDirection") +public func _bjs_setDirection(_ direction: Int32) -> Int32 { #if arch(wasm32) - let _tmp_v = [String: Theme].bridgeJSLiftParameter() - return _bjs_makePromise(resolve: Promise_resolve_SD5ThemeO, reject: Promise_reject) { - return await asyncRoundTripThemeDict(_: _tmp_v) - } + let ret = setDirection(_: Direction.bridgeJSLiftParameter(direction)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_asyncRoundTripFileSize") -@_cdecl("bjs_asyncRoundTripFileSize") -public func _bjs_asyncRoundTripFileSize(_ v: Int64) -> Int32 { +@_expose(wasm, "bjs_getDirection") +@_cdecl("bjs_getDirection") +public func _bjs_getDirection() -> Int32 { #if arch(wasm32) - return _bjs_makePromise(resolve: Promise_resolve_8FileSizeO, reject: Promise_reject) { - return await asyncRoundTripFileSize(_: FileSize.bridgeJSLiftParameter(v)) - } + let ret = getDirection() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_asyncRoundTripOptionalFileSize") -@_cdecl("bjs_asyncRoundTripOptionalFileSize") -public func _bjs_asyncRoundTripOptionalFileSize(_ vIsSome: Int32, _ vValue: Int64) -> Int32 { +@_expose(wasm, "bjs_processDirection") +@_cdecl("bjs_processDirection") +public func _bjs_processDirection(_ input: Int32) -> Int32 { #if arch(wasm32) - return _bjs_makePromise(resolve: Promise_resolve_Sq8FileSizeO, reject: Promise_reject) { - return await asyncRoundTripOptionalFileSize(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) - } + let ret = processDirection(_: Direction.bridgeJSLiftParameter(input)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_asyncRoundTripAssociatedValueEnum") -@_cdecl("bjs_asyncRoundTripAssociatedValueEnum") -public func _bjs_asyncRoundTripAssociatedValueEnum(_ v: Int32) -> Int32 { +@_expose(wasm, "bjs_setTheme") +@_cdecl("bjs_setTheme") +public func _bjs_setTheme(_ themeBytes: Int32, _ themeLength: Int32) -> Void { #if arch(wasm32) - let _tmp_v = AsyncPayloadResult.bridgeJSLiftParameter(v) - return _bjs_makePromise(resolve: Promise_resolve_18AsyncPayloadResultO, reject: Promise_reject) { - return await asyncRoundTripAssociatedValueEnum(_: _tmp_v) - } + let ret = setTheme(_: Theme.bridgeJSLiftParameter(themeBytes, themeLength)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_asyncRoundTripOptionalAssociatedValueEnum") -@_cdecl("bjs_asyncRoundTripOptionalAssociatedValueEnum") -public func _bjs_asyncRoundTripOptionalAssociatedValueEnum(_ vIsSome: Int32, _ vCaseId: Int32) -> Int32 { +@_expose(wasm, "bjs_getTheme") +@_cdecl("bjs_getTheme") +public func _bjs_getTheme() -> Void { #if arch(wasm32) - let _tmp_v = Optional.bridgeJSLiftParameter(vIsSome, vCaseId) - return _bjs_makePromise(resolve: Promise_resolve_Sq18AsyncPayloadResultO, reject: Promise_reject) { - return await asyncRoundTripOptionalAssociatedValueEnum(_: _tmp_v) - } + let ret = getTheme() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -8974,474 +8340,743 @@ public func _bjs_makeUtilitiesResultFailure(_ errorBytes: Int32, _ errorLength: @_cdecl("bjs_makeUtilitiesResultStatus") public func _bjs_makeUtilitiesResultStatus(_ active: Int32, _ code: Int32, _ messageBytes: Int32, _ messageLength: Int32) -> Void { #if arch(wasm32) - let ret = makeUtilitiesResultStatus(_: Bool.bridgeJSLiftParameter(active), _: Int.bridgeJSLiftParameter(code), _: String.bridgeJSLiftParameter(messageBytes, messageLength)) + let ret = makeUtilitiesResultStatus(_: Bool.bridgeJSLiftParameter(active), _: Int.bridgeJSLiftParameter(code), _: String.bridgeJSLiftParameter(messageBytes, messageLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_makeAPINetworkingResultSuccess") +@_cdecl("bjs_makeAPINetworkingResultSuccess") +public func _bjs_makeAPINetworkingResultSuccess(_ messageBytes: Int32, _ messageLength: Int32) -> Void { + #if arch(wasm32) + let ret = makeAPINetworkingResultSuccess(_: String.bridgeJSLiftParameter(messageBytes, messageLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_makeAPINetworkingResultFailure") +@_cdecl("bjs_makeAPINetworkingResultFailure") +public func _bjs_makeAPINetworkingResultFailure(_ errorBytes: Int32, _ errorLength: Int32, _ code: Int32) -> Void { + #if arch(wasm32) + let ret = makeAPINetworkingResultFailure(_: String.bridgeJSLiftParameter(errorBytes, errorLength), _: Int.bridgeJSLiftParameter(code)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundtripUtilitiesResult") +@_cdecl("bjs_roundtripUtilitiesResult") +public func _bjs_roundtripUtilitiesResult(_ result: Int32) -> Void { + #if arch(wasm32) + let ret = roundtripUtilitiesResult(_: Utilities.Result.bridgeJSLiftParameter(result)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundtripAPINetworkingResult") +@_cdecl("bjs_roundtripAPINetworkingResult") +public func _bjs_roundtripAPINetworkingResult(_ result: Int32) -> Void { + #if arch(wasm32) + let ret = roundtripAPINetworkingResult(_: API.NetworkingResult.bridgeJSLiftParameter(result)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripAllTypesResult") +@_cdecl("bjs_roundTripAllTypesResult") +public func _bjs_roundTripAllTypesResult(_ result: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripAllTypesResult(_: AllTypesResult.bridgeJSLiftParameter(result)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripTypedPayloadResult") +@_cdecl("bjs_roundTripTypedPayloadResult") +public func _bjs_roundTripTypedPayloadResult(_ result: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripTypedPayloadResult(_: TypedPayloadResult.bridgeJSLiftParameter(result)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_createPropertyHolder") +@_cdecl("bjs_createPropertyHolder") +public func _bjs_createPropertyHolder(_ intValue: Int32, _ floatValue: Float32, _ doubleValue: Float64, _ boolValue: Int32, _ stringValueBytes: Int32, _ stringValueLength: Int32, _ jsObject: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = createPropertyHolder(intValue: Int.bridgeJSLiftParameter(intValue), floatValue: Float.bridgeJSLiftParameter(floatValue), doubleValue: Double.bridgeJSLiftParameter(doubleValue), boolValue: Bool.bridgeJSLiftParameter(boolValue), stringValue: String.bridgeJSLiftParameter(stringValueBytes, stringValueLength), jsObject: JSObject.bridgeJSLiftParameter(jsObject)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_testPropertyHolder") +@_cdecl("bjs_testPropertyHolder") +public func _bjs_testPropertyHolder(_ holder: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = testPropertyHolder(holder: PropertyHolder.bridgeJSLiftParameter(holder)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_resetObserverCounts") +@_cdecl("bjs_resetObserverCounts") +public func _bjs_resetObserverCounts() -> Void { + #if arch(wasm32) + resetObserverCounts() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_getObserverStats") +@_cdecl("bjs_getObserverStats") +public func _bjs_getObserverStats() -> Void { + #if arch(wasm32) + let ret = getObserverStats() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_formatName") +@_cdecl("bjs_formatName") +public func _bjs_formatName(_ nameBytes: Int32, _ nameLength: Int32, _ transform: Int32) -> Void { + #if arch(wasm32) + let ret = formatName(_: String.bridgeJSLiftParameter(nameBytes, nameLength), transform: _BJS_Closure_20BridgeJSRuntimeTestsSS_SS.bridgeJSLift(transform)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_makeFormatter") +@_cdecl("bjs_makeFormatter") +public func _bjs_makeFormatter(_ prefixBytes: Int32, _ prefixLength: Int32) -> Int32 { + #if arch(wasm32) + let ret = makeFormatter(prefix: String.bridgeJSLiftParameter(prefixBytes, prefixLength)) + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_makeAdder") +@_cdecl("bjs_makeAdder") +public func _bjs_makeAdder(_ base: Int32) -> Int32 { + #if arch(wasm32) + let ret = makeAdder(base: Int.bridgeJSLiftParameter(base)) + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripPointerFields") +@_cdecl("bjs_roundTripPointerFields") +public func _bjs_roundTripPointerFields() -> Void { + #if arch(wasm32) + let ret = roundTripPointerFields(_: PointerFields.bridgeJSLiftParameter()) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_testStructDefault") +@_cdecl("bjs_testStructDefault") +public func _bjs_testStructDefault() -> Void { + #if arch(wasm32) + let ret = testStructDefault(point: DataPoint.bridgeJSLiftParameter()) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_cartToJSObject") +@_cdecl("bjs_cartToJSObject") +public func _bjs_cartToJSObject() -> Int32 { + #if arch(wasm32) + let ret = cartToJSObject(_: CopyableCart.bridgeJSLiftParameter()) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_nestedCartToJSObject") +@_cdecl("bjs_nestedCartToJSObject") +public func _bjs_nestedCartToJSObject() -> Int32 { + #if arch(wasm32) + let ret = nestedCartToJSObject(_: CopyableNestedCart.bridgeJSLiftParameter()) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripDataPoint") +@_cdecl("bjs_roundTripDataPoint") +public func _bjs_roundTripDataPoint() -> Void { + #if arch(wasm32) + let ret = roundTripDataPoint(_: DataPoint.bridgeJSLiftParameter()) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripPublicPoint") +@_cdecl("bjs_roundTripPublicPoint") +public func _bjs_roundTripPublicPoint() -> Void { + #if arch(wasm32) + let ret = roundTripPublicPoint(_: PublicPoint.bridgeJSLiftParameter()) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeAPINetworkingResultSuccess") -@_cdecl("bjs_makeAPINetworkingResultSuccess") -public func _bjs_makeAPINetworkingResultSuccess(_ messageBytes: Int32, _ messageLength: Int32) -> Void { +@_expose(wasm, "bjs_roundTripContact") +@_cdecl("bjs_roundTripContact") +public func _bjs_roundTripContact() -> Void { #if arch(wasm32) - let ret = makeAPINetworkingResultSuccess(_: String.bridgeJSLiftParameter(messageBytes, messageLength)) + let ret = roundTripContact(_: Contact.bridgeJSLiftParameter()) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeAPINetworkingResultFailure") -@_cdecl("bjs_makeAPINetworkingResultFailure") -public func _bjs_makeAPINetworkingResultFailure(_ errorBytes: Int32, _ errorLength: Int32, _ code: Int32) -> Void { +@_expose(wasm, "bjs_roundTripConfig") +@_cdecl("bjs_roundTripConfig") +public func _bjs_roundTripConfig() -> Void { #if arch(wasm32) - let ret = makeAPINetworkingResultFailure(_: String.bridgeJSLiftParameter(errorBytes, errorLength), _: Int.bridgeJSLiftParameter(code)) + let ret = roundTripConfig(_: Config.bridgeJSLiftParameter()) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundtripUtilitiesResult") -@_cdecl("bjs_roundtripUtilitiesResult") -public func _bjs_roundtripUtilitiesResult(_ result: Int32) -> Void { +@_expose(wasm, "bjs_roundTripSessionData") +@_cdecl("bjs_roundTripSessionData") +public func _bjs_roundTripSessionData() -> Void { #if arch(wasm32) - let ret = roundtripUtilitiesResult(_: Utilities.Result.bridgeJSLiftParameter(result)) + let ret = roundTripSessionData(_: SessionData.bridgeJSLiftParameter()) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundtripAPINetworkingResult") -@_cdecl("bjs_roundtripAPINetworkingResult") -public func _bjs_roundtripAPINetworkingResult(_ result: Int32) -> Void { +@_expose(wasm, "bjs_roundTripValidationReport") +@_cdecl("bjs_roundTripValidationReport") +public func _bjs_roundTripValidationReport() -> Void { #if arch(wasm32) - let ret = roundtripAPINetworkingResult(_: API.NetworkingResult.bridgeJSLiftParameter(result)) + let ret = roundTripValidationReport(_: ValidationReport.bridgeJSLiftParameter()) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripAllTypesResult") -@_cdecl("bjs_roundTripAllTypesResult") -public func _bjs_roundTripAllTypesResult(_ result: Int32) -> Void { +@_expose(wasm, "bjs_roundTripAdvancedConfig") +@_cdecl("bjs_roundTripAdvancedConfig") +public func _bjs_roundTripAdvancedConfig() -> Void { #if arch(wasm32) - let ret = roundTripAllTypesResult(_: AllTypesResult.bridgeJSLiftParameter(result)) + let ret = roundTripAdvancedConfig(_: AdvancedConfig.bridgeJSLiftParameter()) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripTypedPayloadResult") -@_cdecl("bjs_roundTripTypedPayloadResult") -public func _bjs_roundTripTypedPayloadResult(_ result: Int32) -> Void { +@_expose(wasm, "bjs_roundTripMeasurementConfig") +@_cdecl("bjs_roundTripMeasurementConfig") +public func _bjs_roundTripMeasurementConfig() -> Void { #if arch(wasm32) - let ret = roundTripTypedPayloadResult(_: TypedPayloadResult.bridgeJSLiftParameter(result)) + let ret = roundTripMeasurementConfig(_: MeasurementConfig.bridgeJSLiftParameter()) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_createPropertyHolder") -@_cdecl("bjs_createPropertyHolder") -public func _bjs_createPropertyHolder(_ intValue: Int32, _ floatValue: Float32, _ doubleValue: Float64, _ boolValue: Int32, _ stringValueBytes: Int32, _ stringValueLength: Int32, _ jsObject: Int32) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_updateValidationReport") +@_cdecl("bjs_updateValidationReport") +public func _bjs_updateValidationReport(_ newResultIsSome: Int32, _ newResultCaseId: Int32) -> Void { #if arch(wasm32) - let ret = createPropertyHolder(intValue: Int.bridgeJSLiftParameter(intValue), floatValue: Float.bridgeJSLiftParameter(floatValue), doubleValue: Double.bridgeJSLiftParameter(doubleValue), boolValue: Bool.bridgeJSLiftParameter(boolValue), stringValue: String.bridgeJSLiftParameter(stringValueBytes, stringValueLength), jsObject: JSObject.bridgeJSLiftParameter(jsObject)) + let _tmp_report = ValidationReport.bridgeJSLiftParameter() + let _tmp_newResult = Optional.bridgeJSLiftParameter(newResultIsSome, newResultCaseId) + let ret = updateValidationReport(_: _tmp_newResult, _: _tmp_report) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_testPropertyHolder") -@_cdecl("bjs_testPropertyHolder") -public func _bjs_testPropertyHolder(_ holder: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_testContainerWithStruct") +@_cdecl("bjs_testContainerWithStruct") +public func _bjs_testContainerWithStruct() -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = testPropertyHolder(holder: PropertyHolder.bridgeJSLiftParameter(holder)) + let ret = testContainerWithStruct(_: DataPoint.bridgeJSLiftParameter()) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_resetObserverCounts") -@_cdecl("bjs_resetObserverCounts") -public func _bjs_resetObserverCounts() -> Void { +@_expose(wasm, "bjs_roundTripJSObjectContainer") +@_cdecl("bjs_roundTripJSObjectContainer") +public func _bjs_roundTripJSObjectContainer() -> Void { #if arch(wasm32) - resetObserverCounts() + let ret = roundTripJSObjectContainer(_: JSObjectContainer.bridgeJSLiftParameter()) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_getObserverStats") -@_cdecl("bjs_getObserverStats") -public func _bjs_getObserverStats() -> Void { +@_expose(wasm, "bjs_roundTripFooContainer") +@_cdecl("bjs_roundTripFooContainer") +public func _bjs_roundTripFooContainer() -> Void { #if arch(wasm32) - let ret = getObserverStats() + let ret = roundTripFooContainer(_: FooContainer.bridgeJSLiftParameter()) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_formatName") -@_cdecl("bjs_formatName") -public func _bjs_formatName(_ nameBytes: Int32, _ nameLength: Int32, _ transform: Int32) -> Void { +@_expose(wasm, "bjs_roundTripArrayMembers") +@_cdecl("bjs_roundTripArrayMembers") +public func _bjs_roundTripArrayMembers() -> Void { #if arch(wasm32) - let ret = formatName(_: String.bridgeJSLiftParameter(nameBytes, nameLength), transform: _BJS_Closure_20BridgeJSRuntimeTestsSS_SS.bridgeJSLift(transform)) + let ret = roundTripArrayMembers(_: ArrayMembers.bridgeJSLiftParameter()) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeFormatter") -@_cdecl("bjs_makeFormatter") -public func _bjs_makeFormatter(_ prefixBytes: Int32, _ prefixLength: Int32) -> Int32 { +@_expose(wasm, "bjs_arrayMembersSum") +@_cdecl("bjs_arrayMembersSum") +public func _bjs_arrayMembersSum() -> Int32 { #if arch(wasm32) - let ret = makeFormatter(prefix: String.bridgeJSLiftParameter(prefixBytes, prefixLength)) - return JSTypedClosure(ret).bridgeJSLowerReturn() + let _tmp_values = [Int].bridgeJSStackPop() + let _tmp_value = ArrayMembers.bridgeJSLiftParameter() + let ret = arrayMembersSum(_: _tmp_value, _: _tmp_values) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeAdder") -@_cdecl("bjs_makeAdder") -public func _bjs_makeAdder(_ base: Int32) -> Int32 { +@_expose(wasm, "bjs_arrayMembersFirst") +@_cdecl("bjs_arrayMembersFirst") +public func _bjs_arrayMembersFirst() -> Void { #if arch(wasm32) - let ret = makeAdder(base: Int.bridgeJSLiftParameter(base)) - return JSTypedClosure(ret).bridgeJSLowerReturn() + let _tmp_values = [String].bridgeJSStackPop() + let _tmp_value = ArrayMembers.bridgeJSLiftParameter() + let ret = arrayMembersFirst(_: _tmp_value, _: _tmp_values) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripPointerFields") -@_cdecl("bjs_roundTripPointerFields") -public func _bjs_roundTripPointerFields() -> Void { +@_expose(wasm, "bjs_PolygonReference_init") +@_cdecl("bjs_PolygonReference_init") +public func _bjs_PolygonReference_init(_ labelBytes: Int32, _ labelLength: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = roundTripPointerFields(_: PointerFields.bridgeJSLiftParameter()) + let ret = PolygonReference(verticesData: [Double].bridgeJSStackPop(), label: String.bridgeJSLiftParameter(labelBytes, labelLength)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_testStructDefault") -@_cdecl("bjs_testStructDefault") -public func _bjs_testStructDefault() -> Void { +@_expose(wasm, "bjs_PolygonReference_vertexCount") +@_cdecl("bjs_PolygonReference_vertexCount") +public func _bjs_PolygonReference_vertexCount(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = testStructDefault(point: DataPoint.bridgeJSLiftParameter()) + let ret = PolygonReference.bridgeJSLiftParameter(_self).vertexCount() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_cartToJSObject") -@_cdecl("bjs_cartToJSObject") -public func _bjs_cartToJSObject() -> Int32 { +@_expose(wasm, "bjs_PolygonReference_summary") +@_cdecl("bjs_PolygonReference_summary") +public func _bjs_PolygonReference_summary(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = cartToJSObject(_: CopyableCart.bridgeJSLiftParameter()) + let ret = PolygonReference.bridgeJSLiftParameter(_self).summary() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_nestedCartToJSObject") -@_cdecl("bjs_nestedCartToJSObject") -public func _bjs_nestedCartToJSObject() -> Int32 { +@_expose(wasm, "bjs_PolygonReference_snapshot") +@_cdecl("bjs_PolygonReference_snapshot") +public func _bjs_PolygonReference_snapshot(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = nestedCartToJSObject(_: CopyableNestedCart.bridgeJSLiftParameter()) - return ret.bridgeJSLowerReturn() + let ret = PolygonReference.bridgeJSLiftParameter(_self).snapshot() + return ret.bridgeToJS().bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripDataPoint") -@_cdecl("bjs_roundTripDataPoint") -public func _bjs_roundTripDataPoint() -> Void { +@_expose(wasm, "bjs_PolygonReference_merge") +@_cdecl("bjs_PolygonReference_merge") +public func _bjs_PolygonReference_merge(_ _self: UnsafeMutableRawPointer, _ other: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = roundTripDataPoint(_: DataPoint.bridgeJSLiftParameter()) - return ret.bridgeJSLowerReturn() + let ret = PolygonReference.bridgeJSLiftParameter(_self).merge(_: Polygon.bridgeFromJS(PolygonReference.bridgeJSLiftParameter(other))) + return ret.bridgeToJS().bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripPublicPoint") -@_cdecl("bjs_roundTripPublicPoint") -public func _bjs_roundTripPublicPoint() -> Void { +@_expose(wasm, "bjs_PolygonReference_static_origin") +@_cdecl("bjs_PolygonReference_static_origin") +public func _bjs_PolygonReference_static_origin(_ labelBytes: Int32, _ labelLength: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = roundTripPublicPoint(_: PublicPoint.bridgeJSLiftParameter()) - return ret.bridgeJSLowerReturn() + let ret = PolygonReference.origin(label: String.bridgeJSLiftParameter(labelBytes, labelLength)) + return ret.bridgeToJS().bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_asyncRoundTripPublicPoint") -@_cdecl("bjs_asyncRoundTripPublicPoint") -public func _bjs_asyncRoundTripPublicPoint() -> Int32 { +@_expose(wasm, "bjs_PolygonReference_deinit") +@_cdecl("bjs_PolygonReference_deinit") +public func _bjs_PolygonReference_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let _tmp_point = PublicPoint.bridgeJSLiftParameter() - return _bjs_makePromise(resolve: Promise_resolve_11PublicPointV, reject: Promise_reject) { - return await asyncRoundTripPublicPoint(_: _tmp_point) - } + Unmanaged.fromOpaque(pointer).release() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_asyncRoundTripPublicPointThrows") -@_cdecl("bjs_asyncRoundTripPublicPointThrows") -public func _bjs_asyncRoundTripPublicPointThrows() -> Int32 { - #if arch(wasm32) - let _tmp_point = PublicPoint.bridgeJSLiftParameter() - return _bjs_makePromise(resolve: Promise_resolve_11PublicPointV, reject: Promise_reject) { () async throws(JSException) -> PublicPoint in - return try await asyncRoundTripPublicPointThrows(_: _tmp_point) +extension PolygonReference: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_PolygonReference_wrap(Unmanaged.passRetained(self).toOpaque())))) } - #else + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_PolygonReference_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_PolygonReference_wrap") +fileprivate func _bjs_PolygonReference_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_PolygonReference_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func _bjs_PolygonReference_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_PolygonReference_wrap_extern(pointer) } -@_expose(wasm, "bjs_asyncStructOrThrow") -@_cdecl("bjs_asyncStructOrThrow") -public func _bjs_asyncStructOrThrow(_ shouldThrow: Int32) -> Int32 { +@_expose(wasm, "bjs_TagReference_describe") +@_cdecl("bjs_TagReference_describe") +public func _bjs_TagReference_describe(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - return _bjs_makePromise(resolve: Promise_resolve_11PublicPointV, reject: Promise_reject) { () async throws(JSException) -> PublicPoint in - return try await asyncStructOrThrow(_: Bool.bridgeJSLiftParameter(shouldThrow)) - } + let ret = TagReference.bridgeJSLiftParameter(_self).describe() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_asyncCombinePublicPoints") -@_cdecl("bjs_asyncCombinePublicPoints") -public func _bjs_asyncCombinePublicPoints() -> Int32 { +@_expose(wasm, "bjs_TagReference_deinit") +@_cdecl("bjs_TagReference_deinit") +public func _bjs_TagReference_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let _tmp_b = PublicPoint.bridgeJSLiftParameter() - let _tmp_a = PublicPoint.bridgeJSLiftParameter() - return _bjs_makePromise(resolve: Promise_resolve_11PublicPointV, reject: Promise_reject) { - return await asyncCombinePublicPoints(_: _tmp_a, _: _tmp_b) - } + Unmanaged.fromOpaque(pointer).release() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_asyncRoundTripContact") -@_cdecl("bjs_asyncRoundTripContact") -public func _bjs_asyncRoundTripContact() -> Int32 { - #if arch(wasm32) - let _tmp_contact = Contact.bridgeJSLiftParameter() - return _bjs_makePromise(resolve: Promise_resolve_7ContactV, reject: Promise_reject) { - return await asyncRoundTripContact(_: _tmp_contact) +extension TagReference: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_TagReference_wrap(Unmanaged.passRetained(self).toOpaque())))) } - #else + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_TagReference_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_TagReference_wrap") +fileprivate func _bjs_TagReference_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_TagReference_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func _bjs_TagReference_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_TagReference_wrap_extern(pointer) } -@_expose(wasm, "bjs_asyncRoundTripPublicPointArray") -@_cdecl("bjs_asyncRoundTripPublicPointArray") -public func _bjs_asyncRoundTripPublicPointArray() -> Int32 { +@_expose(wasm, "bjs_TokenReference_init") +@_cdecl("bjs_TokenReference_init") +public func _bjs_TokenReference_init(_ value: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let _tmp_points = [PublicPoint].bridgeJSStackPop() - return _bjs_makePromise(resolve: Promise_resolve_Sa11PublicPointV, reject: Promise_reject) { - return await asyncRoundTripPublicPointArray(_: _tmp_points) - } + let ret = TokenReference(value: Int.bridgeJSLiftParameter(value)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_asyncRoundTripOptionalPublicPoint") -@_cdecl("bjs_asyncRoundTripOptionalPublicPoint") -public func _bjs_asyncRoundTripOptionalPublicPoint() -> Int32 { +@_expose(wasm, "bjs_TokenReference_read") +@_cdecl("bjs_TokenReference_read") +public func _bjs_TokenReference_read(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let _tmp_point = Optional.bridgeJSLiftParameter() - return _bjs_makePromise(resolve: Promise_resolve_Sq11PublicPointV, reject: Promise_reject) { - return await asyncRoundTripOptionalPublicPoint(_: _tmp_point) - } + let ret = TokenReference.bridgeJSLiftParameter(_self).read() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_asyncRoundTripPublicPointDict") -@_cdecl("bjs_asyncRoundTripPublicPointDict") -public func _bjs_asyncRoundTripPublicPointDict() -> Int32 { +@_expose(wasm, "bjs_TokenReference_deinit") +@_cdecl("bjs_TokenReference_deinit") +public func _bjs_TokenReference_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let _tmp_points = [String: PublicPoint].bridgeJSLiftParameter() - return _bjs_makePromise(resolve: Promise_resolve_SD11PublicPointV, reject: Promise_reject) { - return await asyncRoundTripPublicPointDict(_: _tmp_points) - } + Unmanaged.fromOpaque(pointer).release() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripContact") -@_cdecl("bjs_roundTripContact") -public func _bjs_roundTripContact() -> Void { +extension TokenReference: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_TokenReference_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_TokenReference_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_TokenReference_wrap") +fileprivate func _bjs_TokenReference_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_TokenReference_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_TokenReference_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_TokenReference_wrap_extern(pointer) +} + +@_expose(wasm, "bjs_TagHolderReference_init") +@_cdecl("bjs_TagHolderReference_init") +public func _bjs_TagHolderReference_init(_ tag: UnsafeMutableRawPointer, _ version: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = roundTripContact(_: Contact.bridgeJSLiftParameter()) + let ret = TagHolderReference(tag: Tag.bridgeFromJS(TagReference.bridgeJSLiftParameter(tag)), version: Int.bridgeJSLiftParameter(version)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripConfig") -@_cdecl("bjs_roundTripConfig") -public func _bjs_roundTripConfig() -> Void { +@_expose(wasm, "bjs_TagHolderReference_describe") +@_cdecl("bjs_TagHolderReference_describe") +public func _bjs_TagHolderReference_describe(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = roundTripConfig(_: Config.bridgeJSLiftParameter()) + let ret = TagHolderReference.bridgeJSLiftParameter(_self).describe() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripSessionData") -@_cdecl("bjs_roundTripSessionData") -public func _bjs_roundTripSessionData() -> Void { +@_expose(wasm, "bjs_TagHolderReference_tag_get") +@_cdecl("bjs_TagHolderReference_tag_get") +public func _bjs_TagHolderReference_tag_get(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = roundTripSessionData(_: SessionData.bridgeJSLiftParameter()) - return ret.bridgeJSLowerReturn() + let ret = TagHolderReference.bridgeJSLiftParameter(_self).tag + return ret.bridgeToJS().bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripValidationReport") -@_cdecl("bjs_roundTripValidationReport") -public func _bjs_roundTripValidationReport() -> Void { +@_expose(wasm, "bjs_TagHolderReference_tag_set") +@_cdecl("bjs_TagHolderReference_tag_set") +public func _bjs_TagHolderReference_tag_set(_ _self: UnsafeMutableRawPointer, _ value: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = roundTripValidationReport(_: ValidationReport.bridgeJSLiftParameter()) - return ret.bridgeJSLowerReturn() + TagHolderReference.bridgeJSLiftParameter(_self).tag = Tag.bridgeFromJS(TagReference.bridgeJSLiftParameter(value)) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripAdvancedConfig") -@_cdecl("bjs_roundTripAdvancedConfig") -public func _bjs_roundTripAdvancedConfig() -> Void { +@_expose(wasm, "bjs_TagHolderReference_version_get") +@_cdecl("bjs_TagHolderReference_version_get") +public func _bjs_TagHolderReference_version_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = roundTripAdvancedConfig(_: AdvancedConfig.bridgeJSLiftParameter()) + let ret = TagHolderReference.bridgeJSLiftParameter(_self).version return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripMeasurementConfig") -@_cdecl("bjs_roundTripMeasurementConfig") -public func _bjs_roundTripMeasurementConfig() -> Void { +@_expose(wasm, "bjs_TagHolderReference_version_set") +@_cdecl("bjs_TagHolderReference_version_set") +public func _bjs_TagHolderReference_version_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - let ret = roundTripMeasurementConfig(_: MeasurementConfig.bridgeJSLiftParameter()) - return ret.bridgeJSLowerReturn() + TagHolderReference.bridgeJSLiftParameter(_self).version = Int.bridgeJSLiftParameter(value) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_updateValidationReport") -@_cdecl("bjs_updateValidationReport") -public func _bjs_updateValidationReport(_ newResultIsSome: Int32, _ newResultCaseId: Int32) -> Void { +@_expose(wasm, "bjs_TagHolderReference_deinit") +@_cdecl("bjs_TagHolderReference_deinit") +public func _bjs_TagHolderReference_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let _tmp_report = ValidationReport.bridgeJSLiftParameter() - let _tmp_newResult = Optional.bridgeJSLiftParameter(newResultIsSome, newResultCaseId) - let ret = updateValidationReport(_: _tmp_newResult, _: _tmp_report) - return ret.bridgeJSLowerReturn() + Unmanaged.fromOpaque(pointer).release() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_testContainerWithStruct") -@_cdecl("bjs_testContainerWithStruct") -public func _bjs_testContainerWithStruct() -> UnsafeMutableRawPointer { +extension TagHolderReference: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_TagHolderReference_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_TagHolderReference_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_TagHolderReference_wrap") +fileprivate func _bjs_TagHolderReference_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_TagHolderReference_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_TagHolderReference_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_TagHolderReference_wrap_extern(pointer) +} + +@_expose(wasm, "bjs_PriorityReference_describe") +@_cdecl("bjs_PriorityReference_describe") +public func _bjs_PriorityReference_describe(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = testContainerWithStruct(_: DataPoint.bridgeJSLiftParameter()) + let ret = PriorityReference.bridgeJSLiftParameter(_self).describe() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripJSObjectContainer") -@_cdecl("bjs_roundTripJSObjectContainer") -public func _bjs_roundTripJSObjectContainer() -> Void { +@_expose(wasm, "bjs_PriorityReference_weight") +@_cdecl("bjs_PriorityReference_weight") +public func _bjs_PriorityReference_weight(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = roundTripJSObjectContainer(_: JSObjectContainer.bridgeJSLiftParameter()) + let ret = PriorityReference.bridgeJSLiftParameter(_self).weight() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripFooContainer") -@_cdecl("bjs_roundTripFooContainer") -public func _bjs_roundTripFooContainer() -> Void { +@_expose(wasm, "bjs_PriorityReference_static_low") +@_cdecl("bjs_PriorityReference_static_low") +public func _bjs_PriorityReference_static_low() -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = roundTripFooContainer(_: FooContainer.bridgeJSLiftParameter()) - return ret.bridgeJSLowerReturn() + let ret = PriorityReference.low() + return ret.bridgeToJS().bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripArrayMembers") -@_cdecl("bjs_roundTripArrayMembers") -public func _bjs_roundTripArrayMembers() -> Void { - #if arch(wasm32) - let ret = roundTripArrayMembers(_: ArrayMembers.bridgeJSLiftParameter()) - return ret.bridgeJSLowerReturn() +@_expose(wasm, "bjs_PriorityReference_static_medium") +@_cdecl("bjs_PriorityReference_static_medium") +public func _bjs_PriorityReference_static_medium() -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = PriorityReference.medium() + return ret.bridgeToJS().bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_arrayMembersSum") -@_cdecl("bjs_arrayMembersSum") -public func _bjs_arrayMembersSum() -> Int32 { +@_expose(wasm, "bjs_PriorityReference_static_high") +@_cdecl("bjs_PriorityReference_static_high") +public func _bjs_PriorityReference_static_high() -> UnsafeMutableRawPointer { #if arch(wasm32) - let _tmp_values = [Int].bridgeJSStackPop() - let _tmp_value = ArrayMembers.bridgeJSLiftParameter() - let ret = arrayMembersSum(_: _tmp_value, _: _tmp_values) - return ret.bridgeJSLowerReturn() + let ret = PriorityReference.high() + return ret.bridgeToJS().bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_arrayMembersFirst") -@_cdecl("bjs_arrayMembersFirst") -public func _bjs_arrayMembersFirst() -> Void { +@_expose(wasm, "bjs_PriorityReference_deinit") +@_cdecl("bjs_PriorityReference_deinit") +public func _bjs_PriorityReference_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let _tmp_values = [String].bridgeJSStackPop() - let _tmp_value = ArrayMembers.bridgeJSLiftParameter() - let ret = arrayMembersFirst(_: _tmp_value, _: _tmp_values) - return ret.bridgeJSLowerReturn() + Unmanaged.fromOpaque(pointer).release() #else fatalError("Only available on WebAssembly") #endif } +extension PriorityReference: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_PriorityReference_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_PriorityReference_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_PriorityReference_wrap") +fileprivate func _bjs_PriorityReference_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_PriorityReference_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_PriorityReference_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_PriorityReference_wrap_extern(pointer) +} + @_expose(wasm, "bjs_ClosureSupportExports_static_makeIntToInt") @_cdecl("bjs_ClosureSupportExports_static_makeIntToInt") public func _bjs_ClosureSupportExports_static_makeIntToInt(_ base: Int32) -> Int32 { @@ -9902,18 +9537,6 @@ public func _bjs_Calculator_add(_ _self: UnsafeMutableRawPointer, _ a: Int32, _ #endif } -@_expose(wasm, "bjs_Calculator_asyncMakePoint") -@_cdecl("bjs_Calculator_asyncMakePoint") -public func _bjs_Calculator_asyncMakePoint(_ _self: UnsafeMutableRawPointer, _ x: Int32, _ y: Int32) -> Int32 { - #if arch(wasm32) - return _bjs_makePromise(resolve: Promise_resolve_11PublicPointV, reject: Promise_reject) { - return await Calculator.bridgeJSLiftParameter(_self).asyncMakePoint(x: Int.bridgeJSLiftParameter(x), y: Int.bridgeJSLiftParameter(y)) - } - #else - fatalError("Only available on WebAssembly") - #endif -} - @_expose(wasm, "bjs_Calculator_deinit") @_cdecl("bjs_Calculator_deinit") public func _bjs_Calculator_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { @@ -12328,639 +11951,260 @@ public func _bjs_Container_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { Unmanaged.fromOpaque(pointer).release() #else fatalError("Only available on WebAssembly") - #endif -} - -extension Container: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { - var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_Container_wrap(Unmanaged.passRetained(self).toOpaque())))) - } - consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { - _bjs_Container_wrap(Unmanaged.passRetained(self).toOpaque()) - } -} - -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Container_wrap") -fileprivate func _bjs_Container_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 -#else -fileprivate func _bjs_Container_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func _bjs_Container_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_Container_wrap_extern(pointer) -} - -@_expose(wasm, "bjs_LeakCheck_init") -@_cdecl("bjs_LeakCheck_init") -public func _bjs_LeakCheck_init() -> UnsafeMutableRawPointer { - #if arch(wasm32) - let ret = LeakCheck() - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_LeakCheck_deinit") -@_cdecl("bjs_LeakCheck_deinit") -public func _bjs_LeakCheck_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() - #else - fatalError("Only available on WebAssembly") - #endif -} - -extension LeakCheck: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { - public var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_LeakCheck_wrap(Unmanaged.passRetained(self).toOpaque())))) - } - public consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { - _bjs_LeakCheck_wrap(Unmanaged.passRetained(self).toOpaque()) - } -} - -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_LeakCheck_wrap") -fileprivate func _bjs_LeakCheck_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 -#else -fileprivate func _bjs_LeakCheck_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func _bjs_LeakCheck_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_LeakCheck_wrap_extern(pointer) -} - -@JSFunction func Promise_reject(_ promise: JSObject, _ value: JSValue) throws(JSException) - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "promise_reject_BridgeJSRuntimeTests") -fileprivate func promise_reject_BridgeJSRuntimeTests_extern(_ promise: Int32, _ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void -#else -fileprivate func promise_reject_BridgeJSRuntimeTests_extern(_ promise: Int32, _ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func promise_reject_BridgeJSRuntimeTests(_ promise: Int32, _ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void { - return promise_reject_BridgeJSRuntimeTests_extern(promise, valueKind, valuePayload1, valuePayload2) -} - -func _$Promise_reject(_ promise: JSObject, _ value: JSValue) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() - let (valueKind, valuePayload1, valuePayload2) = value.bridgeJSLowerParameter() - promise_reject_BridgeJSRuntimeTests(promiseValue, valueKind, valuePayload1, valuePayload2) - if let error = _swift_js_take_exception() { throw error } -} - -@JSFunction func Promise_resolve_SS(_ promise: JSObject, _ value: String) throws(JSException) - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_SS") -fileprivate func promise_resolve_BridgeJSRuntimeTests_SS_extern(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void -#else -fileprivate func promise_resolve_BridgeJSRuntimeTests_SS_extern(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_SS(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { - return promise_resolve_BridgeJSRuntimeTests_SS_extern(promise, valueBytes, valueLength) -} - -func _$Promise_resolve_SS(_ promise: JSObject, _ value: String) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() - value.bridgeJSWithLoweredParameter { (valueBytes, valueLength) in - promise_resolve_BridgeJSRuntimeTests_SS(promiseValue, valueBytes, valueLength) - } - if let error = _swift_js_take_exception() { throw error } -} - -@JSFunction func Promise_resolve_y(_ promise: JSObject) throws(JSException) - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_y") -fileprivate func promise_resolve_BridgeJSRuntimeTests_y_extern(_ promise: Int32) -> Void -#else -fileprivate func promise_resolve_BridgeJSRuntimeTests_y_extern(_ promise: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_y(_ promise: Int32) -> Void { - return promise_resolve_BridgeJSRuntimeTests_y_extern(promise) -} - -func _$Promise_resolve_y(_ promise: JSObject) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() - promise_resolve_BridgeJSRuntimeTests_y(promiseValue) - if let error = _swift_js_take_exception() { throw error } -} - -@JSFunction func Promise_resolve_Si(_ promise: JSObject, _ value: Int) throws(JSException) - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Si") -fileprivate func promise_resolve_BridgeJSRuntimeTests_Si_extern(_ promise: Int32, _ value: Int32) -> Void -#else -fileprivate func promise_resolve_BridgeJSRuntimeTests_Si_extern(_ promise: Int32, _ value: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Si(_ promise: Int32, _ value: Int32) -> Void { - return promise_resolve_BridgeJSRuntimeTests_Si_extern(promise, value) -} - -func _$Promise_resolve_Si(_ promise: JSObject, _ value: Int) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() - let valueValue = value.bridgeJSLowerParameter() - promise_resolve_BridgeJSRuntimeTests_Si(promiseValue, valueValue) - if let error = _swift_js_take_exception() { throw error } -} - -@JSFunction func Promise_resolve_Sf(_ promise: JSObject, _ value: Float) throws(JSException) - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sf") -fileprivate func promise_resolve_BridgeJSRuntimeTests_Sf_extern(_ promise: Int32, _ value: Float32) -> Void -#else -fileprivate func promise_resolve_BridgeJSRuntimeTests_Sf_extern(_ promise: Int32, _ value: Float32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sf(_ promise: Int32, _ value: Float32) -> Void { - return promise_resolve_BridgeJSRuntimeTests_Sf_extern(promise, value) -} - -func _$Promise_resolve_Sf(_ promise: JSObject, _ value: Float) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() - let valueValue = value.bridgeJSLowerParameter() - promise_resolve_BridgeJSRuntimeTests_Sf(promiseValue, valueValue) - if let error = _swift_js_take_exception() { throw error } -} - -@JSFunction func Promise_resolve_Sd(_ promise: JSObject, _ value: Double) throws(JSException) - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sd") -fileprivate func promise_resolve_BridgeJSRuntimeTests_Sd_extern(_ promise: Int32, _ value: Float64) -> Void -#else -fileprivate func promise_resolve_BridgeJSRuntimeTests_Sd_extern(_ promise: Int32, _ value: Float64) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sd(_ promise: Int32, _ value: Float64) -> Void { - return promise_resolve_BridgeJSRuntimeTests_Sd_extern(promise, value) -} - -func _$Promise_resolve_Sd(_ promise: JSObject, _ value: Double) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() - let valueValue = value.bridgeJSLowerParameter() - promise_resolve_BridgeJSRuntimeTests_Sd(promiseValue, valueValue) - if let error = _swift_js_take_exception() { throw error } -} - -@JSFunction func Promise_resolve_Sb(_ promise: JSObject, _ value: Bool) throws(JSException) - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sb") -fileprivate func promise_resolve_BridgeJSRuntimeTests_Sb_extern(_ promise: Int32, _ value: Int32) -> Void -#else -fileprivate func promise_resolve_BridgeJSRuntimeTests_Sb_extern(_ promise: Int32, _ value: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sb(_ promise: Int32, _ value: Int32) -> Void { - return promise_resolve_BridgeJSRuntimeTests_Sb_extern(promise, value) -} - -func _$Promise_resolve_Sb(_ promise: JSObject, _ value: Bool) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() - let valueValue = value.bridgeJSLowerParameter() - promise_resolve_BridgeJSRuntimeTests_Sb(promiseValue, valueValue) - if let error = _swift_js_take_exception() { throw error } -} - -@JSFunction func Promise_resolve_7GreeterC(_ promise: JSObject, _ value: Greeter) throws(JSException) - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_7GreeterC") -fileprivate func promise_resolve_BridgeJSRuntimeTests_7GreeterC_extern(_ promise: Int32, _ value: UnsafeMutableRawPointer) -> Void -#else -fileprivate func promise_resolve_BridgeJSRuntimeTests_7GreeterC_extern(_ promise: Int32, _ value: UnsafeMutableRawPointer) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_7GreeterC(_ promise: Int32, _ value: UnsafeMutableRawPointer) -> Void { - return promise_resolve_BridgeJSRuntimeTests_7GreeterC_extern(promise, value) -} - -func _$Promise_resolve_7GreeterC(_ promise: JSObject, _ value: Greeter) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() - let valuePointer = value.bridgeJSLowerParameter() - promise_resolve_BridgeJSRuntimeTests_7GreeterC(promiseValue, valuePointer) - if let error = _swift_js_take_exception() { throw error } -} - -@JSFunction func Promise_resolve_8JSObjectC(_ promise: JSObject, _ value: JSObject) throws(JSException) - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_8JSObjectC") -fileprivate func promise_resolve_BridgeJSRuntimeTests_8JSObjectC_extern(_ promise: Int32, _ value: Int32) -> Void -#else -fileprivate func promise_resolve_BridgeJSRuntimeTests_8JSObjectC_extern(_ promise: Int32, _ value: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_8JSObjectC(_ promise: Int32, _ value: Int32) -> Void { - return promise_resolve_BridgeJSRuntimeTests_8JSObjectC_extern(promise, value) -} - -func _$Promise_resolve_8JSObjectC(_ promise: JSObject, _ value: JSObject) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() - let valueValue = value.bridgeJSLowerParameter() - promise_resolve_BridgeJSRuntimeTests_8JSObjectC(promiseValue, valueValue) - if let error = _swift_js_take_exception() { throw error } -} - -@JSFunction func Promise_resolve_5ThemeO(_ promise: JSObject, _ value: Theme) throws(JSException) - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_5ThemeO") -fileprivate func promise_resolve_BridgeJSRuntimeTests_5ThemeO_extern(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void -#else -fileprivate func promise_resolve_BridgeJSRuntimeTests_5ThemeO_extern(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_5ThemeO(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { - return promise_resolve_BridgeJSRuntimeTests_5ThemeO_extern(promise, valueBytes, valueLength) -} - -func _$Promise_resolve_5ThemeO(_ promise: JSObject, _ value: Theme) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() - value.bridgeJSWithLoweredParameter { (valueBytes, valueLength) in - promise_resolve_BridgeJSRuntimeTests_5ThemeO(promiseValue, valueBytes, valueLength) - } - if let error = _swift_js_take_exception() { throw error } -} - -@JSFunction func Promise_resolve_9DirectionO(_ promise: JSObject, _ value: Direction) throws(JSException) - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_9DirectionO") -fileprivate func promise_resolve_BridgeJSRuntimeTests_9DirectionO_extern(_ promise: Int32, _ value: Int32) -> Void -#else -fileprivate func promise_resolve_BridgeJSRuntimeTests_9DirectionO_extern(_ promise: Int32, _ value: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_9DirectionO(_ promise: Int32, _ value: Int32) -> Void { - return promise_resolve_BridgeJSRuntimeTests_9DirectionO_extern(promise, value) -} - -func _$Promise_resolve_9DirectionO(_ promise: JSObject, _ value: Direction) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() - let valueValue = value.bridgeJSLowerParameter() - promise_resolve_BridgeJSRuntimeTests_9DirectionO(promiseValue, valueValue) - if let error = _swift_js_take_exception() { throw error } -} - -@JSFunction func Promise_resolve_Sq5ThemeO(_ promise: JSObject, _ value: Optional) throws(JSException) - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sq5ThemeO") -fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq5ThemeO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void -#else -fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq5ThemeO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq5ThemeO(_ promise: Int32, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { - return promise_resolve_BridgeJSRuntimeTests_Sq5ThemeO_extern(promise, valueIsSome, valueBytes, valueLength) -} - -func _$Promise_resolve_Sq5ThemeO(_ promise: JSObject, _ value: Optional) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() - value.bridgeJSWithLoweredParameter { (valueIsSome, valueBytes, valueLength) in - promise_resolve_BridgeJSRuntimeTests_Sq5ThemeO(promiseValue, valueIsSome, valueBytes, valueLength) - } - if let error = _swift_js_take_exception() { throw error } -} - -@JSFunction func Promise_resolve_Sq9DirectionO(_ promise: JSObject, _ value: Optional) throws(JSException) - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sq9DirectionO") -fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq9DirectionO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Void -#else -fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq9DirectionO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq9DirectionO(_ promise: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { - return promise_resolve_BridgeJSRuntimeTests_Sq9DirectionO_extern(promise, valueIsSome, valueValue) -} - -func _$Promise_resolve_Sq9DirectionO(_ promise: JSObject, _ value: Optional) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() - let (valueIsSome, valueValue) = value.bridgeJSLowerParameter() - promise_resolve_BridgeJSRuntimeTests_Sq9DirectionO(promiseValue, valueIsSome, valueValue) - if let error = _swift_js_take_exception() { throw error } -} - -@JSFunction func Promise_resolve_Sa9DirectionO(_ promise: JSObject, _ value: [Direction]) throws(JSException) - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sa9DirectionO") -fileprivate func promise_resolve_BridgeJSRuntimeTests_Sa9DirectionO_extern(_ promise: Int32) -> Void -#else -fileprivate func promise_resolve_BridgeJSRuntimeTests_Sa9DirectionO_extern(_ promise: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sa9DirectionO(_ promise: Int32) -> Void { - return promise_resolve_BridgeJSRuntimeTests_Sa9DirectionO_extern(promise) -} - -func _$Promise_resolve_Sa9DirectionO(_ promise: JSObject, _ value: [Direction]) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() - let _ = value.bridgeJSLowerParameter() - promise_resolve_BridgeJSRuntimeTests_Sa9DirectionO(promiseValue) - if let error = _swift_js_take_exception() { throw error } -} - -@JSFunction func Promise_resolve_SD9DirectionO(_ promise: JSObject, _ value: [String: Direction]) throws(JSException) - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_SD9DirectionO") -fileprivate func promise_resolve_BridgeJSRuntimeTests_SD9DirectionO_extern(_ promise: Int32) -> Void -#else -fileprivate func promise_resolve_BridgeJSRuntimeTests_SD9DirectionO_extern(_ promise: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_SD9DirectionO(_ promise: Int32) -> Void { - return promise_resolve_BridgeJSRuntimeTests_SD9DirectionO_extern(promise) + #endif } -func _$Promise_resolve_SD9DirectionO(_ promise: JSObject, _ value: [String: Direction]) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() - let _ = value.bridgeJSLowerParameter() - promise_resolve_BridgeJSRuntimeTests_SD9DirectionO(promiseValue) - if let error = _swift_js_take_exception() { throw error } +extension Container: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_Container_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_Container_wrap(Unmanaged.passRetained(self).toOpaque()) + } } -@JSFunction func Promise_resolve_Sa5ThemeO(_ promise: JSObject, _ value: [Theme]) throws(JSException) - #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sa5ThemeO") -fileprivate func promise_resolve_BridgeJSRuntimeTests_Sa5ThemeO_extern(_ promise: Int32) -> Void +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Container_wrap") +fileprivate func _bjs_Container_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func promise_resolve_BridgeJSRuntimeTests_Sa5ThemeO_extern(_ promise: Int32) -> Void { +fileprivate func _bjs_Container_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sa5ThemeO(_ promise: Int32) -> Void { - return promise_resolve_BridgeJSRuntimeTests_Sa5ThemeO_extern(promise) +@inline(never) fileprivate func _bjs_Container_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Container_wrap_extern(pointer) } -func _$Promise_resolve_Sa5ThemeO(_ promise: JSObject, _ value: [Theme]) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() - let _ = value.bridgeJSLowerParameter() - promise_resolve_BridgeJSRuntimeTests_Sa5ThemeO(promiseValue) - if let error = _swift_js_take_exception() { throw error } +@_expose(wasm, "bjs_LeakCheck_init") +@_cdecl("bjs_LeakCheck_init") +public func _bjs_LeakCheck_init() -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = LeakCheck() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif } -@JSFunction func Promise_resolve_SD5ThemeO(_ promise: JSObject, _ value: [String: Theme]) throws(JSException) - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_SD5ThemeO") -fileprivate func promise_resolve_BridgeJSRuntimeTests_SD5ThemeO_extern(_ promise: Int32) -> Void -#else -fileprivate func promise_resolve_BridgeJSRuntimeTests_SD5ThemeO_extern(_ promise: Int32) -> Void { +@_expose(wasm, "bjs_LeakCheck_deinit") +@_cdecl("bjs_LeakCheck_deinit") +public func _bjs_LeakCheck_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_SD5ThemeO(_ promise: Int32) -> Void { - return promise_resolve_BridgeJSRuntimeTests_SD5ThemeO_extern(promise) + #endif } -func _$Promise_resolve_SD5ThemeO(_ promise: JSObject, _ value: [String: Theme]) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() - let _ = value.bridgeJSLowerParameter() - promise_resolve_BridgeJSRuntimeTests_SD5ThemeO(promiseValue) - if let error = _swift_js_take_exception() { throw error } +extension LeakCheck: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + public var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_LeakCheck_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + public consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_LeakCheck_wrap(Unmanaged.passRetained(self).toOpaque()) + } } -@JSFunction func Promise_resolve_8FileSizeO(_ promise: JSObject, _ value: FileSize) throws(JSException) - #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_8FileSizeO") -fileprivate func promise_resolve_BridgeJSRuntimeTests_8FileSizeO_extern(_ promise: Int32, _ value: Int64) -> Void +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_LeakCheck_wrap") +fileprivate func _bjs_LeakCheck_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func promise_resolve_BridgeJSRuntimeTests_8FileSizeO_extern(_ promise: Int32, _ value: Int64) -> Void { +fileprivate func _bjs_LeakCheck_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_8FileSizeO(_ promise: Int32, _ value: Int64) -> Void { - return promise_resolve_BridgeJSRuntimeTests_8FileSizeO_extern(promise, value) -} - -func _$Promise_resolve_8FileSizeO(_ promise: JSObject, _ value: FileSize) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() - let valueValue = value.bridgeJSLowerParameter() - promise_resolve_BridgeJSRuntimeTests_8FileSizeO(promiseValue, valueValue) - if let error = _swift_js_take_exception() { throw error } +@inline(never) fileprivate func _bjs_LeakCheck_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_LeakCheck_wrap_extern(pointer) } -@JSFunction func Promise_resolve_Sq8FileSizeO(_ promise: JSObject, _ value: Optional) throws(JSException) - #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sq8FileSizeO") -fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq8FileSizeO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueValue: Int64) -> Void +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Surface_init") +fileprivate func bjs_Surface_init_extern(_ labelBytes: Int32, _ labelLength: Int32) -> Int32 #else -fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq8FileSizeO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueValue: Int64) -> Void { +fileprivate func bjs_Surface_init_extern(_ labelBytes: Int32, _ labelLength: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq8FileSizeO(_ promise: Int32, _ valueIsSome: Int32, _ valueValue: Int64) -> Void { - return promise_resolve_BridgeJSRuntimeTests_Sq8FileSizeO_extern(promise, valueIsSome, valueValue) -} - -func _$Promise_resolve_Sq8FileSizeO(_ promise: JSObject, _ value: Optional) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() - let (valueIsSome, valueValue) = value.bridgeJSLowerParameter() - promise_resolve_BridgeJSRuntimeTests_Sq8FileSizeO(promiseValue, valueIsSome, valueValue) - if let error = _swift_js_take_exception() { throw error } +@inline(never) fileprivate func bjs_Surface_init(_ labelBytes: Int32, _ labelLength: Int32) -> Int32 { + return bjs_Surface_init_extern(labelBytes, labelLength) } -@JSFunction func Promise_resolve_18AsyncPayloadResultO(_ promise: JSObject, _ value: AsyncPayloadResult) throws(JSException) - #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_18AsyncPayloadResultO") -fileprivate func promise_resolve_BridgeJSRuntimeTests_18AsyncPayloadResultO_extern(_ promise: Int32, _ value: Int32) -> Void +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Surface_label_get") +fileprivate func bjs_Surface_label_get_extern(_ self: Int32) -> Int32 #else -fileprivate func promise_resolve_BridgeJSRuntimeTests_18AsyncPayloadResultO_extern(_ promise: Int32, _ value: Int32) -> Void { +fileprivate func bjs_Surface_label_get_extern(_ self: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_18AsyncPayloadResultO(_ promise: Int32, _ value: Int32) -> Void { - return promise_resolve_BridgeJSRuntimeTests_18AsyncPayloadResultO_extern(promise, value) +@inline(never) fileprivate func bjs_Surface_label_get(_ self: Int32) -> Int32 { + return bjs_Surface_label_get_extern(self) } -func _$Promise_resolve_18AsyncPayloadResultO(_ promise: JSObject, _ value: AsyncPayloadResult) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() - let valueCaseId = value.bridgeJSLowerParameter() - promise_resolve_BridgeJSRuntimeTests_18AsyncPayloadResultO(promiseValue, valueCaseId) - if let error = _swift_js_take_exception() { throw error } +func _$Surface_init(_ label: String) throws(JSException) -> JSObject { + let ret0 = label.bridgeJSWithLoweredParameter { (labelBytes, labelLength) in + let ret = bjs_Surface_init(labelBytes, labelLength) + return ret + } + let ret = ret0 + if let error = _swift_js_take_exception() { + throw error + } + return JSObject.bridgeJSLiftReturn(ret) } -@JSFunction func Promise_resolve_Sq18AsyncPayloadResultO(_ promise: JSObject, _ value: Optional) throws(JSException) +func _$Surface_label_get(_ self: JSObject) throws(JSException) -> String { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_Surface_label_get(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sq18AsyncPayloadResultO") -fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq18AsyncPayloadResultO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueCaseId: Int32) -> Void +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_AliasImports_jsRoundTripTagged_static") +fileprivate func bjs_AliasImports_jsRoundTripTagged_static_extern(_ valueBytes: Int32, _ valueLength: Int32) -> Int32 #else -fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq18AsyncPayloadResultO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueCaseId: Int32) -> Void { +fileprivate func bjs_AliasImports_jsRoundTripTagged_static_extern(_ valueBytes: Int32, _ valueLength: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq18AsyncPayloadResultO(_ promise: Int32, _ valueIsSome: Int32, _ valueCaseId: Int32) -> Void { - return promise_resolve_BridgeJSRuntimeTests_Sq18AsyncPayloadResultO_extern(promise, valueIsSome, valueCaseId) -} - -func _$Promise_resolve_Sq18AsyncPayloadResultO(_ promise: JSObject, _ value: Optional) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() - let (valueIsSome, valueCaseId) = value.bridgeJSLowerParameter() - promise_resolve_BridgeJSRuntimeTests_Sq18AsyncPayloadResultO(promiseValue, valueIsSome, valueCaseId) - if let error = _swift_js_take_exception() { throw error } +@inline(never) fileprivate func bjs_AliasImports_jsRoundTripTagged_static(_ valueBytes: Int32, _ valueLength: Int32) -> Int32 { + return bjs_AliasImports_jsRoundTripTagged_static_extern(valueBytes, valueLength) } -@JSFunction func Promise_resolve_11PublicPointV(_ promise: JSObject, _ value: PublicPoint) throws(JSException) - #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_11PublicPointV") -fileprivate func promise_resolve_BridgeJSRuntimeTests_11PublicPointV_extern(_ promise: Int32, _ value: Int32) -> Void +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_AliasImports_jsRoundTripOptionalTagged_static") +fileprivate func bjs_AliasImports_jsRoundTripOptionalTagged_static_extern(_ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void #else -fileprivate func promise_resolve_BridgeJSRuntimeTests_11PublicPointV_extern(_ promise: Int32, _ value: Int32) -> Void { +fileprivate func bjs_AliasImports_jsRoundTripOptionalTagged_static_extern(_ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_11PublicPointV(_ promise: Int32, _ value: Int32) -> Void { - return promise_resolve_BridgeJSRuntimeTests_11PublicPointV_extern(promise, value) -} - -func _$Promise_resolve_11PublicPointV(_ promise: JSObject, _ value: PublicPoint) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() - let valueObjectId = value.bridgeJSLowerParameter() - promise_resolve_BridgeJSRuntimeTests_11PublicPointV(promiseValue, valueObjectId) - if let error = _swift_js_take_exception() { throw error } +@inline(never) fileprivate func bjs_AliasImports_jsRoundTripOptionalTagged_static(_ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + return bjs_AliasImports_jsRoundTripOptionalTagged_static_extern(valueIsSome, valueBytes, valueLength) } -@JSFunction func Promise_resolve_7ContactV(_ promise: JSObject, _ value: Contact) throws(JSException) - #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_7ContactV") -fileprivate func promise_resolve_BridgeJSRuntimeTests_7ContactV_extern(_ promise: Int32, _ value: Int32) -> Void +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_AliasImports_jsProduceOptionalCanvas_static") +fileprivate func bjs_AliasImports_jsProduceOptionalCanvas_static_extern(_ labelIsSome: Int32, _ labelBytes: Int32, _ labelLength: Int32) -> Void #else -fileprivate func promise_resolve_BridgeJSRuntimeTests_7ContactV_extern(_ promise: Int32, _ value: Int32) -> Void { +fileprivate func bjs_AliasImports_jsProduceOptionalCanvas_static_extern(_ labelIsSome: Int32, _ labelBytes: Int32, _ labelLength: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_7ContactV(_ promise: Int32, _ value: Int32) -> Void { - return promise_resolve_BridgeJSRuntimeTests_7ContactV_extern(promise, value) -} - -func _$Promise_resolve_7ContactV(_ promise: JSObject, _ value: Contact) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() - let valueObjectId = value.bridgeJSLowerParameter() - promise_resolve_BridgeJSRuntimeTests_7ContactV(promiseValue, valueObjectId) - if let error = _swift_js_take_exception() { throw error } +@inline(never) fileprivate func bjs_AliasImports_jsProduceOptionalCanvas_static(_ labelIsSome: Int32, _ labelBytes: Int32, _ labelLength: Int32) -> Void { + return bjs_AliasImports_jsProduceOptionalCanvas_static_extern(labelIsSome, labelBytes, labelLength) } -@JSFunction func Promise_resolve_Sa11PublicPointV(_ promise: JSObject, _ value: [PublicPoint]) throws(JSException) - #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sa11PublicPointV") -fileprivate func promise_resolve_BridgeJSRuntimeTests_Sa11PublicPointV_extern(_ promise: Int32) -> Void +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_AliasImports_jsRoundTripAliasedTags_static") +fileprivate func bjs_AliasImports_jsRoundTripAliasedTags_static_extern() -> Void #else -fileprivate func promise_resolve_BridgeJSRuntimeTests_Sa11PublicPointV_extern(_ promise: Int32) -> Void { +fileprivate func bjs_AliasImports_jsRoundTripAliasedTags_static_extern() -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sa11PublicPointV(_ promise: Int32) -> Void { - return promise_resolve_BridgeJSRuntimeTests_Sa11PublicPointV_extern(promise) +@inline(never) fileprivate func bjs_AliasImports_jsRoundTripAliasedTags_static() -> Void { + return bjs_AliasImports_jsRoundTripAliasedTags_static_extern() } -func _$Promise_resolve_Sa11PublicPointV(_ promise: JSObject, _ value: [PublicPoint]) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() - let _ = value.bridgeJSLowerParameter() - promise_resolve_BridgeJSRuntimeTests_Sa11PublicPointV(promiseValue) - if let error = _swift_js_take_exception() { throw error } -} - -@JSFunction func Promise_resolve_Sq11PublicPointV(_ promise: JSObject, _ value: Optional) throws(JSException) - #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sq11PublicPointV") -fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq11PublicPointV_extern(_ promise: Int32, _ value: Int32) -> Void +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_AliasImports_jsRoundTripPolygon_static") +fileprivate func bjs_AliasImports_jsRoundTripPolygon_static_extern(_ value: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer #else -fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq11PublicPointV_extern(_ promise: Int32, _ value: Int32) -> Void { +fileprivate func bjs_AliasImports_jsRoundTripPolygon_static_extern(_ value: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq11PublicPointV(_ promise: Int32, _ value: Int32) -> Void { - return promise_resolve_BridgeJSRuntimeTests_Sq11PublicPointV_extern(promise, value) -} - -func _$Promise_resolve_Sq11PublicPointV(_ promise: JSObject, _ value: Optional) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() - let valueIsSome = value.bridgeJSLowerParameter() - promise_resolve_BridgeJSRuntimeTests_Sq11PublicPointV(promiseValue, valueIsSome) - if let error = _swift_js_take_exception() { throw error } +@inline(never) fileprivate func bjs_AliasImports_jsRoundTripPolygon_static(_ value: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + return bjs_AliasImports_jsRoundTripPolygon_static_extern(value) } -@JSFunction func Promise_resolve_SD11PublicPointV(_ promise: JSObject, _ value: [String: PublicPoint]) throws(JSException) - #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_SD11PublicPointV") -fileprivate func promise_resolve_BridgeJSRuntimeTests_SD11PublicPointV_extern(_ promise: Int32) -> Void +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_AliasImports_jsRoundTripCoordinate_static") +fileprivate func bjs_AliasImports_jsRoundTripCoordinate_static_extern(_ value: Int32) -> Int32 #else -fileprivate func promise_resolve_BridgeJSRuntimeTests_SD11PublicPointV_extern(_ promise: Int32) -> Void { +fileprivate func bjs_AliasImports_jsRoundTripCoordinate_static_extern(_ value: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_SD11PublicPointV(_ promise: Int32) -> Void { - return promise_resolve_BridgeJSRuntimeTests_SD11PublicPointV_extern(promise) +@inline(never) fileprivate func bjs_AliasImports_jsRoundTripCoordinate_static(_ value: Int32) -> Int32 { + return bjs_AliasImports_jsRoundTripCoordinate_static_extern(value) +} + +func _$AliasImports_jsRoundTripTagged(_ value: Tagged) throws(JSException) -> Tagged { + let ret0 = value.bridgeToJS().bridgeJSWithLoweredParameter { (valueBytes, valueLength) in + let ret = bjs_AliasImports_jsRoundTripTagged_static(valueBytes, valueLength) + return ret + } + let ret = ret0 + if let error = _swift_js_take_exception() { + throw error + } + return Tagged.bridgeFromJS(String.bridgeJSLiftReturn(ret)) } -func _$Promise_resolve_SD11PublicPointV(_ promise: JSObject, _ value: [String: PublicPoint]) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() - let _ = value.bridgeJSLowerParameter() - promise_resolve_BridgeJSRuntimeTests_SD11PublicPointV(promiseValue) - if let error = _swift_js_take_exception() { throw error } +func _$AliasImports_jsRoundTripOptionalTagged(_ value: Optional) throws(JSException) -> Optional { + value.map { + $0.bridgeToJS() + } .bridgeJSWithLoweredParameter { (valueIsSome, valueBytes, valueLength) in + bjs_AliasImports_jsRoundTripOptionalTagged_static(valueIsSome, valueBytes, valueLength) + } + if let error = _swift_js_take_exception() { + throw error + } + return Optional.bridgeJSLiftReturnFromSideChannel().map { + Tagged.bridgeFromJS($0) + } } -@JSFunction func Promise_resolve_9DataPointV(_ promise: JSObject, _ value: DataPoint) throws(JSException) +func _$AliasImports_jsProduceOptionalCanvas(_ label: Optional) throws(JSException) -> Optional { + label.bridgeJSWithLoweredParameter { (labelIsSome, labelBytes, labelLength) in + bjs_AliasImports_jsProduceOptionalCanvas_static(labelIsSome, labelBytes, labelLength) + } + if let error = _swift_js_take_exception() { + throw error + } + return Optional.bridgeJSLiftReturn().map { + Canvas.bridgeFromJS($0) + } +} -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_9DataPointV") -fileprivate func promise_resolve_BridgeJSRuntimeTests_9DataPointV_extern(_ promise: Int32, _ value: Int32) -> Void -#else -fileprivate func promise_resolve_BridgeJSRuntimeTests_9DataPointV_extern(_ promise: Int32, _ value: Int32) -> Void { - fatalError("Only available on WebAssembly") +func _$AliasImports_jsRoundTripAliasedTags(_ values: [Optional]) throws(JSException) -> [Optional] { + let _ = values.map { + $0.map { + $0.bridgeToJS() + } + } .bridgeJSLowerParameter() + bjs_AliasImports_jsRoundTripAliasedTags_static() + if let error = _swift_js_take_exception() { + throw error + } + return [Optional].bridgeJSLiftReturn().map { + $0.map { + AliasedTag.bridgeFromJS($0) + } + } } -#endif -@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_9DataPointV(_ promise: Int32, _ value: Int32) -> Void { - return promise_resolve_BridgeJSRuntimeTests_9DataPointV_extern(promise, value) + +func _$AliasImports_jsRoundTripPolygon(_ value: Polygon) throws(JSException) -> Polygon { + let valuePointer = value.bridgeToJS().bridgeJSLowerParameter() + let ret = bjs_AliasImports_jsRoundTripPolygon_static(valuePointer) + if let error = _swift_js_take_exception() { + throw error + } + return Polygon.bridgeFromJS(PolygonReference.bridgeJSLiftReturn(ret)) } -func _$Promise_resolve_9DataPointV(_ promise: JSObject, _ value: DataPoint) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() - let valueObjectId = value.bridgeJSLowerParameter() - promise_resolve_BridgeJSRuntimeTests_9DataPointV(promiseValue, valueObjectId) - if let error = _swift_js_take_exception() { throw error } +func _$AliasImports_jsRoundTripCoordinate(_ value: Coordinate) throws(JSException) -> Coordinate { + let valueObjectId = value.bridgeToJS().bridgeJSLowerParameter() + let ret = bjs_AliasImports_jsRoundTripCoordinate_static(valueObjectId) + if let error = _swift_js_take_exception() { + throw error + } + return Coordinate.bridgeFromJS(JSCoordinate.bridgeJSLiftReturn(ret)) } #if arch(wasm32) @@ -13482,30 +12726,6 @@ fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripFeatureFlag_static_exter return bjs_AsyncImportImports_jsAsyncRoundTripFeatureFlag_static_extern(resolveRef, rejectRef, vBytes, vLength) } -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_AsyncImportImports_jsAsyncRoundTripAssociatedValueEnum_static") -fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripAssociatedValueEnum_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ v: Int32) -> Void -#else -fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripAssociatedValueEnum_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ v: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripAssociatedValueEnum_static(_ resolveRef: Int32, _ rejectRef: Int32, _ v: Int32) -> Void { - return bjs_AsyncImportImports_jsAsyncRoundTripAssociatedValueEnum_static_extern(resolveRef, rejectRef, v) -} - -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_AsyncImportImports_jsAsyncRoundTripOptionalAssociatedValueEnum_static") -fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripOptionalAssociatedValueEnum_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ vIsSome: Int32, _ vCaseId: Int32) -> Void -#else -fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripOptionalAssociatedValueEnum_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ vIsSome: Int32, _ vCaseId: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripOptionalAssociatedValueEnum_static(_ resolveRef: Int32, _ rejectRef: Int32, _ vIsSome: Int32, _ vCaseId: Int32) -> Void { - return bjs_AsyncImportImports_jsAsyncRoundTripOptionalAssociatedValueEnum_static_extern(resolveRef, rejectRef, vIsSome, vCaseId) -} - func _$AsyncImportImports_jsAsyncRoundTripVoid() async throws(JSException) -> Void { try await _bjs_awaitPromise(makeResolveClosure: { JSTypedClosure<() -> Void>($0) @@ -13627,52 +12847,6 @@ func _$AsyncImportImports_jsAsyncRoundTripFeatureFlag(_ v: FeatureFlag) async th return resolved } -func _$AsyncImportImports_jsAsyncRoundTripAssociatedValueEnum(_ v: AsyncImportedPayloadResult) async throws(JSException) -> AsyncImportedPayloadResult { - let resolved = try await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<(sending AsyncImportedPayloadResult) -> Void>($0) - }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) - }) { resolveRef, rejectRef in - let vCaseId = v.bridgeJSLowerParameter() - bjs_AsyncImportImports_jsAsyncRoundTripAssociatedValueEnum_static(resolveRef, rejectRef, vCaseId) - } - return resolved -} - -func _$AsyncImportImports_jsAsyncRoundTripOptionalAssociatedValueEnum(_ v: Optional) async throws(JSException) -> Optional { - let resolved = try await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<(sending Optional) -> Void>($0) - }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) - }) { resolveRef, rejectRef in - let (vIsSome, vCaseId) = v.bridgeJSLowerParameter() - bjs_AsyncImportImports_jsAsyncRoundTripOptionalAssociatedValueEnum_static(resolveRef, rejectRef, vIsSome, vCaseId) - } - return resolved -} - -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureAsyncImports_runJsClosureAsyncTests_static") -fileprivate func bjs_ClosureAsyncImports_runJsClosureAsyncTests_static_extern(_ resolveRef: Int32, _ rejectRef: Int32) -> Void -#else -fileprivate func bjs_ClosureAsyncImports_runJsClosureAsyncTests_static_extern(_ resolveRef: Int32, _ rejectRef: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func bjs_ClosureAsyncImports_runJsClosureAsyncTests_static(_ resolveRef: Int32, _ rejectRef: Int32) -> Void { - return bjs_ClosureAsyncImports_runJsClosureAsyncTests_static_extern(resolveRef, rejectRef) -} - -func _$ClosureAsyncImports_runJsClosureAsyncTests() async throws(JSException) -> Void { - try await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<() -> Void>($0) - }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) - }) { resolveRef, rejectRef in - bjs_ClosureAsyncImports_runJsClosureAsyncTests_static(resolveRef, rejectRef) - } -} - #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportImports_jsApplyVoid_static") fileprivate func bjs_ClosureSupportImports_jsApplyVoid_static_extern(_ callback: Int32) -> Void @@ -14055,25 +13229,6 @@ func _$ClosureSupportImports_runJsClosureSupportTests() throws(JSException) -> V } } -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureThrowsImports_runJsClosureThrowsTests_static") -fileprivate func bjs_ClosureThrowsImports_runJsClosureThrowsTests_static_extern() -> Void -#else -fileprivate func bjs_ClosureThrowsImports_runJsClosureThrowsTests_static_extern() -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func bjs_ClosureThrowsImports_runJsClosureThrowsTests_static() -> Void { - return bjs_ClosureThrowsImports_runJsClosureThrowsTests_static_extern() -} - -func _$ClosureThrowsImports_runJsClosureThrowsTests() throws(JSException) -> Void { - bjs_ClosureThrowsImports_runJsClosureThrowsTests_static() - if let error = _swift_js_take_exception() { - throw error - } -} - #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DefaultArgumentImports_runJsDefaultArgumentTests_static") fileprivate func bjs_DefaultArgumentImports_runJsDefaultArgumentTests_static_extern() -> Void @@ -14519,6 +13674,28 @@ func _$runAsyncWorks() async throws(JSException) -> Void { } } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_runAliasAsyncWorks") +fileprivate func bjs_runAliasAsyncWorks_extern(_ resolveRef: Int32, _ rejectRef: Int32) -> Void +#else +fileprivate func bjs_runAliasAsyncWorks_extern(_ resolveRef: Int32, _ rejectRef: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_runAliasAsyncWorks(_ resolveRef: Int32, _ rejectRef: Int32) -> Void { + return bjs_runAliasAsyncWorks_extern(resolveRef, rejectRef) +} + +func _$runAliasAsyncWorks() async throws(JSException) -> Void { + try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<() -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + bjs_runAliasAsyncWorks(resolveRef, rejectRef) + } +} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_fetchWeatherData") fileprivate func bjs_fetchWeatherData_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ cityBytes: Int32, _ cityLength: Int32) -> Void @@ -15208,69 +14385,6 @@ func _$Animal_getIsCat(_ self: JSObject) throws(JSException) -> Bool { return Bool.bridgeJSLiftReturn(ret) } -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripLightColor") -fileprivate func bjs_jsRoundTripLightColor_extern(_ value: Int32) -> Int32 -#else -fileprivate func bjs_jsRoundTripLightColor_extern(_ value: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func bjs_jsRoundTripLightColor(_ value: Int32) -> Int32 { - return bjs_jsRoundTripLightColor_extern(value) -} - -func _$jsRoundTripLightColor(_ value: LightColor) throws(JSException) -> LightColor { - let valueValue = value.bridgeJSLowerParameter() - let ret = bjs_jsRoundTripLightColor(valueValue) - if let error = _swift_js_take_exception() { - throw error - } - return LightColor.bridgeJSLiftReturn(ret) -} - -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripImportedPayloadSignal") -fileprivate func bjs_jsRoundTripImportedPayloadSignal_extern(_ value: Int32) -> Int32 -#else -fileprivate func bjs_jsRoundTripImportedPayloadSignal_extern(_ value: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func bjs_jsRoundTripImportedPayloadSignal(_ value: Int32) -> Int32 { - return bjs_jsRoundTripImportedPayloadSignal_extern(value) -} - -func _$jsRoundTripImportedPayloadSignal(_ value: ImportedPayloadSignal) throws(JSException) -> ImportedPayloadSignal { - let valueCaseId = value.bridgeJSLowerParameter() - let ret = bjs_jsRoundTripImportedPayloadSignal(valueCaseId) - if let error = _swift_js_take_exception() { - throw error - } - return ImportedPayloadSignal.bridgeJSLiftReturn(ret) -} - -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripOptionalImportedPayloadSignal") -fileprivate func bjs_jsRoundTripOptionalImportedPayloadSignal_extern(_ valueIsSome: Int32, _ valueCaseId: Int32) -> Int32 -#else -fileprivate func bjs_jsRoundTripOptionalImportedPayloadSignal_extern(_ valueIsSome: Int32, _ valueCaseId: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func bjs_jsRoundTripOptionalImportedPayloadSignal(_ valueIsSome: Int32, _ valueCaseId: Int32) -> Int32 { - return bjs_jsRoundTripOptionalImportedPayloadSignal_extern(valueIsSome, valueCaseId) -} - -func _$jsRoundTripOptionalImportedPayloadSignal(_ value: Optional) throws(JSException) -> Optional { - let (valueIsSome, valueCaseId) = value.bridgeJSLowerParameter() - let ret = bjs_jsRoundTripOptionalImportedPayloadSignal(valueIsSome, valueCaseId) - if let error = _swift_js_take_exception() { - throw error - } - return Optional.bridgeJSLiftReturn(ret) -} - #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsTranslatePoint") fileprivate func bjs_jsTranslatePoint_extern(_ point: Int32, _ dx: Int32, _ dy: Int32) -> Int32 @@ -15294,27 +14408,6 @@ func _$jsTranslatePoint(_ point: Point, _ dx: Int, _ dy: Int) throws(JSException return Point.bridgeJSLiftReturn(ret) } -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripOptionalPoint") -fileprivate func bjs_jsRoundTripOptionalPoint_extern(_ point: Int32) -> Void -#else -fileprivate func bjs_jsRoundTripOptionalPoint_extern(_ point: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func bjs_jsRoundTripOptionalPoint(_ point: Int32) -> Void { - return bjs_jsRoundTripOptionalPoint_extern(point) -} - -func _$jsRoundTripOptionalPoint(_ point: Optional) throws(JSException) -> Optional { - let pointIsSome = point.bridgeJSLowerParameter() - bjs_jsRoundTripOptionalPoint(pointIsSome) - if let error = _swift_js_take_exception() { - throw error - } - return Optional.bridgeJSLiftReturn() -} - #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_IntegerTypesSupportImports_jsRoundTripInt_static") fileprivate func bjs_IntegerTypesSupportImports_jsRoundTripInt_static_extern(_ v: Int32) -> Int32 @@ -16112,18 +15205,6 @@ fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDic return bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryUndefined_static_extern(v) } -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_OptionalSupportImports_jsRoundTripOptionalJSObjectNull_static") -fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalJSObjectNull_static_extern(_ valueIsSome: Int32, _ valueValue: Int32) -> Void -#else -fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalJSObjectNull_static_extern(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalJSObjectNull_static(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { - return bjs_OptionalSupportImports_jsRoundTripOptionalJSObjectNull_static_extern(valueIsSome, valueValue) -} - #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_OptionalSupportImports_runJsOptionalSupportTests_static") fileprivate func bjs_OptionalSupportImports_runJsOptionalSupportTests_static_extern() -> Void @@ -16210,15 +15291,6 @@ func _$OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryUndefin return JSUndefinedOr<[String: String]>.bridgeJSLiftReturn() } -func _$OptionalSupportImports_jsRoundTripOptionalJSObjectNull(_ value: Optional) throws(JSException) -> Optional { - let (valueIsSome, valueValue) = value.bridgeJSLowerParameter() - bjs_OptionalSupportImports_jsRoundTripOptionalJSObjectNull_static(valueIsSome, valueValue) - if let error = _swift_js_take_exception() { - throw error - } - return Optional.bridgeJSLiftReturn() -} - func _$OptionalSupportImports_runJsOptionalSupportTests() throws(JSException) -> Void { bjs_OptionalSupportImports_runJsOptionalSupportTests_static() if let error = _swift_js_take_exception() { diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index 297ab5a07..fb6286e97 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -1,6 +1,559 @@ { "exported" : { + "aliases" : [ + { + "swiftCallName" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } + }, + { + "swiftCallName" : "Tag", + "underlying" : { + "swiftHeapObject" : { + "_0" : "TagReference" + } + } + }, + { + "swiftCallName" : "Token", + "underlying" : { + "swiftHeapObject" : { + "_0" : "TokenReference" + } + } + }, + { + "swiftCallName" : "TagHolder", + "underlying" : { + "swiftHeapObject" : { + "_0" : "TagHolderReference" + } + } + }, + { + "swiftCallName" : "Coordinate", + "underlying" : { + "swiftStruct" : { + "_0" : "JSCoordinate" + } + } + }, + { + "swiftCallName" : "Priority", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PriorityReference" + } + } + }, + { + "swiftCallName" : "Alert", + "underlying" : { + "caseEnum" : { + "_0" : "Severity" + } + } + }, + { + "swiftCallName" : "Session", + "underlying" : { + "swiftStruct" : { + "_0" : "SessionState" + } + } + }, + { + "swiftCallName" : "Tagged", + "underlying" : { + "string" : { + + } + } + }, + { + "swiftCallName" : "Canvas", + "underlying" : { + "jsObject" : { + "_0" : "Surface" + } + } + }, + { + "swiftCallName" : "AliasedTag", + "underlying" : { + "associatedValueEnum" : { + "_0" : "InnerTag" + } + } + } + ], "classes" : [ + { + "constructor" : { + "abiName" : "bjs_PolygonReference_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "verticesData", + "name" : "verticesData", + "type" : { + "array" : { + "_0" : { + "double" : { + + } + } + } + } + }, + { + "label" : "label", + "name" : "label", + "type" : { + "string" : { + + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_PolygonReference_vertexCount", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "vertexCount", + "parameters" : [ + + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "abiName" : "bjs_PolygonReference_summary", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "summary", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_PolygonReference_snapshot", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "snapshot", + "parameters" : [ + + ], + "returnType" : { + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } + } + } + }, + { + "abiName" : "bjs_PolygonReference_merge", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "merge", + "parameters" : [ + { + "label" : "_", + "name" : "other", + "type" : { + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } + } + } + } + ], + "returnType" : { + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } + } + } + }, + { + "abiName" : "bjs_PolygonReference_static_origin", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "origin", + "parameters" : [ + { + "label" : "label", + "name" : "label", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } + } + }, + "staticContext" : { + "className" : { + "_0" : "PolygonReference" + } + } + } + ], + "name" : "PolygonReference", + "properties" : [ + + ], + "swiftCallName" : "PolygonReference" + }, + { + "methods" : [ + { + "abiName" : "bjs_TagReference_describe", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "describe", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "name" : "TagReference", + "properties" : [ + + ], + "swiftCallName" : "TagReference" + }, + { + "constructor" : { + "abiName" : "bjs_TokenReference_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_TokenReference_read", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "read", + "parameters" : [ + + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "name" : "TokenReference", + "properties" : [ + + ], + "swiftCallName" : "TokenReference" + }, + { + "constructor" : { + "abiName" : "bjs_TagHolderReference_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "tag", + "name" : "tag", + "type" : { + "alias" : { + "name" : "Tag", + "underlying" : { + "swiftHeapObject" : { + "_0" : "TagReference" + } + } + } + } + }, + { + "label" : "version", + "name" : "version", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_TagHolderReference_describe", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "describe", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "name" : "TagHolderReference", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "tag", + "type" : { + "alias" : { + "name" : "Tag", + "underlying" : { + "swiftHeapObject" : { + "_0" : "TagReference" + } + } + } + } + }, + { + "isReadonly" : false, + "isStatic" : false, + "name" : "version", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "swiftCallName" : "TagHolderReference" + }, + { + "methods" : [ + { + "abiName" : "bjs_PriorityReference_describe", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "describe", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_PriorityReference_weight", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "weight", + "parameters" : [ + + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "abiName" : "bjs_PriorityReference_static_low", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "low", + "parameters" : [ + + ], + "returnType" : { + "alias" : { + "name" : "Priority", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PriorityReference" + } + } + } + }, + "staticContext" : { + "className" : { + "_0" : "PriorityReference" + } + } + }, + { + "abiName" : "bjs_PriorityReference_static_medium", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "medium", + "parameters" : [ + + ], + "returnType" : { + "alias" : { + "name" : "Priority", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PriorityReference" + } + } + } + }, + "staticContext" : { + "className" : { + "_0" : "PriorityReference" + } + } + }, + { + "abiName" : "bjs_PriorityReference_static_high", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "high", + "parameters" : [ + + ], + "returnType" : { + "alias" : { + "name" : "Priority", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PriorityReference" + } + } + } + }, + "staticContext" : { + "className" : { + "_0" : "PriorityReference" + } + } + } + ], + "name" : "PriorityReference", + "properties" : [ + + ], + "swiftCallName" : "PriorityReference" + }, { "methods" : [ { @@ -908,46 +1461,6 @@ } } } - }, - { - "abiName" : "bjs_Calculator_asyncMakePoint", - "effects" : { - "isAsync" : true, - "isStatic" : false, - "isThrows" : false - }, - "name" : "asyncMakePoint", - "parameters" : [ - { - "label" : "x", - "name" : "x", - "type" : { - "integer" : { - "_0" : { - "isSigned" : true, - "width" : "word" - } - } - } - }, - { - "label" : "y", - "name" : "y", - "type" : { - "integer" : { - "_0" : { - "isSigned" : true, - "width" : "word" - } - } - } - } - ], - "returnType" : { - "swiftStruct" : { - "_0" : "PublicPoint" - } - } } ], "name" : "Calculator", @@ -4423,32 +4936,136 @@ } } ], - "swiftCallName" : "Container" + "swiftCallName" : "Container" + }, + { + "constructor" : { + "abiName" : "bjs_LeakCheck_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "explicitAccessControl" : "public", + "methods" : [ + + ], + "name" : "LeakCheck", + "properties" : [ + + ], + "swiftCallName" : "LeakCheck" + } + ], + "enums" : [ + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "notice" + }, + { + "associatedValues" : [ + + ], + "name" : "warning" + }, + { + "associatedValues" : [ + + ], + "name" : "error" + } + ], + "emitStyle" : "const", + "name" : "Severity", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Severity", + "tsFullPath" : "Severity" + }, + { + "cases" : [ + { + "associatedValues" : [ + { + "type" : { + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } + } + } + } + ], + "name" : "polygon" + }, + { + "associatedValues" : [ + + ], + "name" : "empty" + } + ], + "emitStyle" : "const", + "name" : "Shape", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Shape", + "tsFullPath" : "Shape" }, { - "constructor" : { - "abiName" : "bjs_LeakCheck_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false + "cases" : [ + { + "associatedValues" : [ + { + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "name" : "payload" }, - "parameters" : [ + { + "associatedValues" : [ - ] - }, - "explicitAccessControl" : "public", - "methods" : [ + ], + "name" : "empty" + } + ], + "emitStyle" : "const", + "name" : "InnerTag", + "staticMethods" : [ ], - "name" : "LeakCheck", - "properties" : [ + "staticProperties" : [ ], - "swiftCallName" : "LeakCheck" - } - ], - "enums" : [ + "swiftCallName" : "InnerTag", + "tsFullPath" : "InnerTag" + }, { "cases" : [ @@ -6550,53 +7167,6 @@ "swiftCallName" : "ArraySupportExports", "tsFullPath" : "ArraySupportExports" }, - { - "cases" : [ - { - "associatedValues" : [ - { - "type" : { - "string" : { - - } - } - } - ], - "name" : "success" - }, - { - "associatedValues" : [ - { - "type" : { - "integer" : { - "_0" : { - "isSigned" : true, - "width" : "word" - } - } - } - } - ], - "name" : "failure" - }, - { - "associatedValues" : [ - - ], - "name" : "idle" - } - ], - "emitStyle" : "const", - "name" : "AsyncImportedPayloadResult", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "AsyncImportedPayloadResult", - "tsFullPath" : "AsyncImportedPayloadResult" - }, { "cases" : [ @@ -7762,53 +8332,6 @@ "swiftCallName" : "TSTheme", "tsFullPath" : "TSTheme" }, - { - "cases" : [ - { - "associatedValues" : [ - { - "type" : { - "string" : { - - } - } - } - ], - "name" : "success" - }, - { - "associatedValues" : [ - { - "type" : { - "integer" : { - "_0" : { - "isSigned" : true, - "width" : "word" - } - } - } - } - ], - "name" : "failure" - }, - { - "associatedValues" : [ - - ], - "name" : "idle" - } - ], - "emitStyle" : "const", - "name" : "AsyncPayloadResult", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "AsyncPayloadResult", - "tsFullPath" : "AsyncPayloadResult" - }, { "cases" : [ @@ -9388,85 +9911,6 @@ "swiftCallName" : "NestedStructGroupB", "tsFullPath" : "NestedStructGroupB" }, - { - "cases" : [ - { - "associatedValues" : [ - - ], - "name" : "red" - }, - { - "associatedValues" : [ - - ], - "name" : "yellow" - }, - { - "associatedValues" : [ - - ], - "name" : "green" - } - ], - "emitStyle" : "const", - "name" : "LightColor", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "LightColor", - "tsFullPath" : "LightColor" - }, - { - "cases" : [ - { - "associatedValues" : [ - { - "type" : { - "string" : { - - } - } - } - ], - "name" : "start" - }, - { - "associatedValues" : [ - { - "type" : { - "integer" : { - "_0" : { - "isSigned" : true, - "width" : "word" - } - } - } - } - ], - "name" : "stop" - }, - { - "associatedValues" : [ - - ], - "name" : "idle" - } - ], - "emitStyle" : "const", - "name" : "ImportedPayloadSignal", - "staticMethods" : [ - - ], - "staticProperties" : [ - - ], - "swiftCallName" : "ImportedPayloadSignal", - "tsFullPath" : "ImportedPayloadSignal" - }, { "cases" : [ @@ -11605,1074 +12049,1166 @@ "exposeToGlobal" : false, "functions" : [ { - "abiName" : "bjs_awaitAsyncCallback", + "abiName" : "bjs_makeTag", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, - "isThrows" : true + "isThrows" : false }, - "name" : "awaitAsyncCallback", + "name" : "makeTag", "parameters" : [ { "label" : "_", - "name" : "fetch", + "name" : "name", "type" : { - "closure" : { - "_0" : { - "isAsync" : true, - "isThrows" : true, - "mangleName" : "20BridgeJSRuntimeTestsYaKSS_SS", - "moduleName" : "BridgeJSRuntimeTests", - "parameters" : [ - { - "string" : { - - } - } - ], - "returnType" : { - "string" : { + "string" : { - } - }, - "sendingParameters" : false - }, - "useJSTypedClosure" : false } } } ], "returnType" : { - "string" : { - + "alias" : { + "name" : "Tag", + "underlying" : { + "swiftHeapObject" : { + "_0" : "TagReference" + } + } } } }, { - "abiName" : "bjs_makeAsyncParser", + "abiName" : "bjs_roundTripPolygon", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeAsyncParser", + "name" : "roundTripPolygon", "parameters" : [ - - ], - "returnType" : { - "closure" : { - "_0" : { - "isAsync" : true, - "isThrows" : true, - "mangleName" : "20BridgeJSRuntimeTestsYaKSS_SS", - "moduleName" : "BridgeJSRuntimeTests", - "parameters" : [ - { - "string" : { - + { + "label" : "_", + "name" : "polygon", + "type" : { + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" } } - ], - "returnType" : { - "string" : { - - } - }, - "sendingParameters" : false - }, - "useJSTypedClosure" : true + } + } + } + ], + "returnType" : { + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } } } }, { - "abiName" : "bjs_makeAsyncEcho", + "abiName" : "bjs_appendVertex", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeAsyncEcho", + "name" : "appendVertex", "parameters" : [ - - ], - "returnType" : { - "closure" : { - "_0" : { - "isAsync" : true, - "isThrows" : false, - "mangleName" : "20BridgeJSRuntimeTestsYaSS_SS", - "moduleName" : "BridgeJSRuntimeTests", - "parameters" : [ - { - "string" : { - + { + "label" : "_", + "name" : "polygon", + "type" : { + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" } } - ], - "returnType" : { - "string" : { + } + } + }, + { + "label" : "_", + "name" : "value", + "type" : { + "double" : { - } - }, - "sendingParameters" : false - }, - "useJSTypedClosure" : true + } + } + } + ], + "returnType" : { + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } } } }, { - "abiName" : "bjs_makeAsyncRecorder", + "abiName" : "bjs_optionalRoundTripPolygon", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeAsyncRecorder", + "name" : "optionalRoundTripPolygon", "parameters" : [ - + { + "label" : "_", + "name" : "polygon", + "type" : { + "nullable" : { + "_0" : { + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } + } + }, + "_1" : "null" + } + } + } ], "returnType" : { - "closure" : { + "nullable" : { "_0" : { - "isAsync" : true, - "isThrows" : true, - "mangleName" : "20BridgeJSRuntimeTestsYaKSS_y", - "moduleName" : "BridgeJSRuntimeTests", - "parameters" : [ - { - "string" : { - + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" } } - ], - "returnType" : { - "void" : { - - } - }, - "sendingParameters" : false + } }, - "useJSTypedClosure" : true + "_1" : "null" } } }, { - "abiName" : "bjs_lastRecordedValue", + "abiName" : "bjs_polygonVertexCount", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "lastRecordedValue", + "name" : "polygonVertexCount", "parameters" : [ - + { + "label" : "_", + "name" : "polygon", + "type" : { + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } + } + } + } ], "returnType" : { - "string" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, { - "abiName" : "bjs_makeAsyncPayloadLoader", + "abiName" : "bjs_roundTripPolygonArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "makeAsyncPayloadLoader", + "name" : "roundTripPolygonArray", "parameters" : [ - + { + "label" : "_", + "name" : "polygons", + "type" : { + "array" : { + "_0" : { + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } + } + } + } + } + } ], "returnType" : { - "closure" : { + "array" : { "_0" : { - "isAsync" : true, - "isThrows" : true, - "mangleName" : "20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO", - "moduleName" : "BridgeJSRuntimeTests", - "parameters" : [ - { - "bool" : { - + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" } } - ], - "returnType" : { - "associatedValueEnum" : { - "_0" : "AsyncPayloadResult" - } - }, - "sendingParameters" : false - }, - "useJSTypedClosure" : true + } + } } } }, { - "abiName" : "bjs_awaitPayloadCallback", + "abiName" : "bjs_concatPolygons", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, - "isThrows" : true + "isThrows" : false }, - "name" : "awaitPayloadCallback", + "name" : "concatPolygons", "parameters" : [ { "label" : "_", - "name" : "load", + "name" : "polygons", "type" : { - "closure" : { + "array" : { "_0" : { - "isAsync" : true, - "isThrows" : true, - "mangleName" : "20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO", - "moduleName" : "BridgeJSRuntimeTests", - "parameters" : [ - { - "bool" : { - + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" } } - ], - "returnType" : { - "associatedValueEnum" : { - "_0" : "AsyncPayloadResult" - } - }, - "sendingParameters" : false - }, - "useJSTypedClosure" : false + } + } } } } ], "returnType" : { - "string" : { - + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } } } }, { - "abiName" : "bjs_makeAsyncPointMaker", + "abiName" : "bjs_validatePolygon", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "makeAsyncPointMaker", + "name" : "validatePolygon", "parameters" : [ - - ], - "returnType" : { - "closure" : { - "_0" : { - "isAsync" : true, - "isThrows" : false, - "mangleName" : "20BridgeJSRuntimeTestsYaSd_9DataPointV", - "moduleName" : "BridgeJSRuntimeTests", - "parameters" : [ - { - "double" : { - + { + "label" : "_", + "name" : "polygon", + "type" : { + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" } } - ], - "returnType" : { - "swiftStruct" : { - "_0" : "DataPoint" - } - }, - "sendingParameters" : false - }, - "useJSTypedClosure" : true + } + } } - } - }, - { - "abiName" : "bjs_makeThrowingParser", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "makeThrowingParser", - "parameters" : [ - ], "returnType" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : true, - "mangleName" : "20BridgeJSRuntimeTestsKSS_Si", - "moduleName" : "BridgeJSRuntimeTests", - "parameters" : [ - { - "string" : { - - } - } - ], - "returnType" : { - "integer" : { - "_0" : { - "isSigned" : true, - "width" : "word" - } - } - }, - "sendingParameters" : false - }, - "useJSTypedClosure" : true + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } } } }, { - "abiName" : "bjs_runValidator", + "abiName" : "bjs_splitPolygon", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : true + "isThrows" : false }, - "name" : "runValidator", + "name" : "splitPolygon", "parameters" : [ { "label" : "_", - "name" : "validate", + "name" : "polygon", "type" : { - "closure" : { - "_0" : { - "isAsync" : false, - "isThrows" : true, - "mangleName" : "20BridgeJSRuntimeTestsKSS_Sb", - "moduleName" : "BridgeJSRuntimeTests", - "parameters" : [ - { - "string" : { - - } - } - ], - "returnType" : { - "bool" : { - - } - }, - "sendingParameters" : false - }, - "useJSTypedClosure" : false + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } } } } ], "returnType" : { - "bool" : { - + "array" : { + "_0" : { + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } + } + } } } }, { - "abiName" : "bjs_roundTripVoid", + "abiName" : "bjs_incrementToken", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripVoid", + "name" : "incrementToken", "parameters" : [ - + { + "label" : "_", + "name" : "token", + "type" : { + "alias" : { + "name" : "Token", + "underlying" : { + "swiftHeapObject" : { + "_0" : "TokenReference" + } + } + } + } + } ], "returnType" : { - "void" : { - + "alias" : { + "name" : "Token", + "underlying" : { + "swiftHeapObject" : { + "_0" : "TokenReference" + } + } } } }, { - "abiName" : "bjs_roundTripFloat", + "abiName" : "bjs_makeToken", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripFloat", + "name" : "makeToken", "parameters" : [ { - "label" : "v", - "name" : "v", + "label" : "_", + "name" : "value", "type" : { - "float" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } ], "returnType" : { - "float" : { - + "alias" : { + "name" : "Token", + "underlying" : { + "swiftHeapObject" : { + "_0" : "TokenReference" + } + } } } }, { - "abiName" : "bjs_roundTripDouble", + "abiName" : "bjs_makePolygonInspector", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripDouble", + "name" : "makePolygonInspector", "parameters" : [ - { - "label" : "v", - "name" : "v", - "type" : { - "double" : { - } - } - } ], "returnType" : { - "double" : { - + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsAl7Polygon_Si", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false } } }, { - "abiName" : "bjs_roundTripBool", + "abiName" : "bjs_asyncMakePolygon", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripBool", + "name" : "asyncMakePolygon", "parameters" : [ { - "label" : "v", - "name" : "v", + "label" : "_", + "name" : "label", "type" : { - "bool" : { + "string" : { } } } ], "returnType" : { - "bool" : { - + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } } } }, { - "abiName" : "bjs_roundTripString", + "abiName" : "bjs_roundTripOptionalPolygonArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripString", + "name" : "roundTripOptionalPolygonArray", "parameters" : [ { - "label" : "v", - "name" : "v", + "label" : "_", + "name" : "polygons", "type" : { - "string" : { - + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } + } + }, + "_1" : "null" + } + } } } } ], "returnType" : { - "string" : { - + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } + } + }, + "_1" : "null" + } + } } } }, { - "abiName" : "bjs_roundTripSwiftHeapObject", + "abiName" : "bjs_makeTagHolder", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripSwiftHeapObject", + "name" : "makeTagHolder", "parameters" : [ { - "label" : "v", - "name" : "v", + "label" : "_", + "name" : "name", "type" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "string" : { + + } + } + }, + { + "label" : "_", + "name" : "version", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } ], "returnType" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "alias" : { + "name" : "TagHolder", + "underlying" : { + "swiftHeapObject" : { + "_0" : "TagHolderReference" + } + } } } }, { - "abiName" : "bjs_roundTripUnsafeRawPointer", + "abiName" : "bjs_roundTripCoordinate", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripUnsafeRawPointer", + "name" : "roundTripCoordinate", "parameters" : [ { - "label" : "v", - "name" : "v", + "label" : "_", + "name" : "coordinate", "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeRawPointer" + "alias" : { + "name" : "Coordinate", + "underlying" : { + "swiftStruct" : { + "_0" : "JSCoordinate" + } } } } } ], "returnType" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeRawPointer" + "alias" : { + "name" : "Coordinate", + "underlying" : { + "swiftStruct" : { + "_0" : "JSCoordinate" + } } } } }, { - "abiName" : "bjs_roundTripUnsafeMutableRawPointer", + "abiName" : "bjs_roundTripPriority", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripUnsafeMutableRawPointer", + "name" : "roundTripPriority", "parameters" : [ { - "label" : "v", - "name" : "v", + "label" : "_", + "name" : "priority", "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutableRawPointer" + "alias" : { + "name" : "Priority", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PriorityReference" + } } } } } ], "returnType" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutableRawPointer" + "alias" : { + "name" : "Priority", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PriorityReference" + } } } } }, { - "abiName" : "bjs_roundTripOpaquePointer", + "abiName" : "bjs_roundTripAlert", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOpaquePointer", + "name" : "roundTripAlert", "parameters" : [ { - "label" : "v", - "name" : "v", + "label" : "_", + "name" : "alert", "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "opaquePointer" + "alias" : { + "name" : "Alert", + "underlying" : { + "caseEnum" : { + "_0" : "Severity" + } } } } } ], "returnType" : { - "unsafePointer" : { - "_0" : { - "kind" : "opaquePointer" + "alias" : { + "name" : "Alert", + "underlying" : { + "caseEnum" : { + "_0" : "Severity" + } } } } }, { - "abiName" : "bjs_roundTripUnsafePointer", + "abiName" : "bjs_makeAlert", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripUnsafePointer", + "name" : "makeAlert", "parameters" : [ { - "label" : "v", - "name" : "v", + "label" : "_", + "name" : "level", "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafePointer", - "pointee" : "UInt8" - } + "caseEnum" : { + "_0" : "Severity" } } } ], "returnType" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafePointer", - "pointee" : "UInt8" + "alias" : { + "name" : "Alert", + "underlying" : { + "caseEnum" : { + "_0" : "Severity" + } } } } }, { - "abiName" : "bjs_roundTripUnsafeMutablePointer", + "abiName" : "bjs_roundTripSession", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripUnsafeMutablePointer", + "name" : "roundTripSession", "parameters" : [ { - "label" : "v", - "name" : "v", + "label" : "_", + "name" : "session", "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutablePointer", - "pointee" : "UInt8" + "alias" : { + "name" : "Session", + "underlying" : { + "swiftStruct" : { + "_0" : "SessionState" + } } } } } ], "returnType" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutablePointer", - "pointee" : "UInt8" + "alias" : { + "name" : "Session", + "underlying" : { + "swiftStruct" : { + "_0" : "SessionState" + } } } } }, { - "abiName" : "bjs_roundTripJSObject", + "abiName" : "bjs_makeSession", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripJSObject", + "name" : "makeSession", "parameters" : [ { - "label" : "v", - "name" : "v", + "label" : "_", + "name" : "token", "type" : { - "jsObject" : { + "string" : { } } } ], "returnType" : { - "jsObject" : { - + "alias" : { + "name" : "Session", + "underlying" : { + "swiftStruct" : { + "_0" : "SessionState" + } + } } } }, { - "abiName" : "bjs_roundTripDictionaryExport", + "abiName" : "bjs_roundTripShape", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripDictionaryExport", + "name" : "roundTripShape", "parameters" : [ { - "label" : "v", - "name" : "v", + "label" : "_", + "name" : "s", "type" : { - "dictionary" : { - "_0" : { - "integer" : { - "_0" : { - "isSigned" : true, - "width" : "word" - } - } - } + "associatedValueEnum" : { + "_0" : "Shape" } } } ], - "returnType" : { - "dictionary" : { - "_0" : { - "integer" : { - "_0" : { - "isSigned" : true, - "width" : "word" - } - } - } + "returnType" : { + "associatedValueEnum" : { + "_0" : "Shape" } } }, { - "abiName" : "bjs_roundTripOptionalDictionaryExport", + "abiName" : "bjs_makeShapePolygon", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalDictionaryExport", + "name" : "makeShapePolygon", "parameters" : [ { - "label" : "v", - "name" : "v", + "label" : "_", + "name" : "polygon", "type" : { - "nullable" : { - "_0" : { - "dictionary" : { - "_0" : { - "string" : { - - } - } + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" } - }, - "_1" : "null" + } } } } ], "returnType" : { - "nullable" : { - "_0" : { - "dictionary" : { - "_0" : { - "string" : { - - } - } - } - }, - "_1" : "null" + "associatedValueEnum" : { + "_0" : "Shape" } } }, { - "abiName" : "bjs_roundTripJSValue", + "abiName" : "bjs_makeShapeEmpty", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripJSValue", + "name" : "makeShapeEmpty", "parameters" : [ - { - "label" : "v", - "name" : "v", - "type" : { - "jsValue" : { - } - } - } ], "returnType" : { - "jsValue" : { - + "associatedValueEnum" : { + "_0" : "Shape" } } }, { - "abiName" : "bjs_roundTripOptionalJSValue", + "abiName" : "bjs_roundTripVoid", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalJSValue", + "name" : "roundTripVoid", "parameters" : [ - { - "label" : "v", - "name" : "v", - "type" : { - "nullable" : { - "_0" : { - "jsValue" : { - } - }, - "_1" : "null" - } - } - } ], "returnType" : { - "nullable" : { - "_0" : { - "jsValue" : { + "void" : { - } - }, - "_1" : "null" } } }, { - "abiName" : "bjs_roundTripOptionalJSValueArray", + "abiName" : "bjs_roundTripFloat", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalJSValueArray", + "name" : "roundTripFloat", "parameters" : [ { "label" : "v", "name" : "v", "type" : { - "nullable" : { - "_0" : { - "array" : { - "_0" : { - "jsValue" : { + "float" : { - } - } - } - }, - "_1" : "null" } } } ], "returnType" : { - "nullable" : { - "_0" : { - "array" : { - "_0" : { - "jsValue" : { + "float" : { - } - } - } - }, - "_1" : "null" } } }, { - "abiName" : "bjs_makeImportedFoo", + "abiName" : "bjs_roundTripDouble", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : true + "isThrows" : false }, - "name" : "makeImportedFoo", + "name" : "roundTripDouble", "parameters" : [ { - "label" : "value", - "name" : "value", + "label" : "v", + "name" : "v", "type" : { - "string" : { + "double" : { } } } ], "returnType" : { - "jsObject" : { - "_0" : "Foo" + "double" : { + } } }, { - "abiName" : "bjs_roundTripOptionalImportedClass", + "abiName" : "bjs_roundTripBool", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalImportedClass", + "name" : "roundTripBool", "parameters" : [ { "label" : "v", "name" : "v", "type" : { - "nullable" : { - "_0" : { - "jsObject" : { - "_0" : "Foo" - } - }, - "_1" : "null" + "bool" : { + } } } ], "returnType" : { - "nullable" : { - "_0" : { - "jsObject" : { - "_0" : "Foo" - } - }, - "_1" : "null" + "bool" : { + } } }, { - "abiName" : "bjs_throwsSwiftError", + "abiName" : "bjs_roundTripString", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : true + "isThrows" : false }, - "name" : "throwsSwiftError", + "name" : "roundTripString", "parameters" : [ { - "label" : "shouldThrow", - "name" : "shouldThrow", + "label" : "v", + "name" : "v", "type" : { - "bool" : { + "string" : { } } } ], "returnType" : { - "void" : { + "string" : { } } }, { - "abiName" : "bjs_throwsWithIntResult", + "abiName" : "bjs_roundTripSwiftHeapObject", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : true + "isThrows" : false }, - "name" : "throwsWithIntResult", + "name" : "roundTripSwiftHeapObject", "parameters" : [ - + { + "label" : "v", + "name" : "v", + "type" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } + } ], "returnType" : { - "integer" : { - "_0" : { - "isSigned" : true, - "width" : "word" - } + "swiftHeapObject" : { + "_0" : "Greeter" } } }, { - "abiName" : "bjs_throwsWithStringResult", + "abiName" : "bjs_roundTripUnsafeRawPointer", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : true + "isThrows" : false }, - "name" : "throwsWithStringResult", + "name" : "roundTripUnsafeRawPointer", "parameters" : [ - + { + "label" : "v", + "name" : "v", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeRawPointer" + } + } + } + } ], "returnType" : { - "string" : { - + "unsafePointer" : { + "_0" : { + "kind" : "unsafeRawPointer" + } } } }, { - "abiName" : "bjs_throwsWithBoolResult", + "abiName" : "bjs_roundTripUnsafeMutableRawPointer", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : true + "isThrows" : false }, - "name" : "throwsWithBoolResult", + "name" : "roundTripUnsafeMutableRawPointer", "parameters" : [ - + { + "label" : "v", + "name" : "v", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutableRawPointer" + } + } + } + } ], "returnType" : { - "bool" : { - + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutableRawPointer" + } } } }, { - "abiName" : "bjs_throwsWithFloatResult", + "abiName" : "bjs_roundTripOpaquePointer", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : true + "isThrows" : false }, - "name" : "throwsWithFloatResult", + "name" : "roundTripOpaquePointer", "parameters" : [ - + { + "label" : "v", + "name" : "v", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "opaquePointer" + } + } + } + } ], "returnType" : { - "float" : { - + "unsafePointer" : { + "_0" : { + "kind" : "opaquePointer" + } } } }, { - "abiName" : "bjs_throwsWithDoubleResult", + "abiName" : "bjs_roundTripUnsafePointer", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : true + "isThrows" : false }, - "name" : "throwsWithDoubleResult", + "name" : "roundTripUnsafePointer", "parameters" : [ - + { + "label" : "v", + "name" : "v", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafePointer", + "pointee" : "UInt8" + } + } + } + } ], "returnType" : { - "double" : { - + "unsafePointer" : { + "_0" : { + "kind" : "unsafePointer", + "pointee" : "UInt8" + } } } }, { - "abiName" : "bjs_throwsWithSwiftHeapObjectResult", + "abiName" : "bjs_roundTripUnsafeMutablePointer", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : true + "isThrows" : false }, - "name" : "throwsWithSwiftHeapObjectResult", + "name" : "roundTripUnsafeMutablePointer", "parameters" : [ - + { + "label" : "v", + "name" : "v", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutablePointer", + "pointee" : "UInt8" + } + } + } + } ], "returnType" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutablePointer", + "pointee" : "UInt8" + } } } }, { - "abiName" : "bjs_throwsWithJSObjectResult", + "abiName" : "bjs_roundTripJSObject", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : true + "isThrows" : false }, - "name" : "throwsWithJSObjectResult", + "name" : "roundTripJSObject", "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "jsObject" : { + } + } + } ], "returnType" : { "jsObject" : { @@ -12681,331 +13217,353 @@ } }, { - "abiName" : "bjs_zeroArgAsyncThrows", + "abiName" : "bjs_roundTripDictionaryExport", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, - "isThrows" : true + "isThrows" : false }, - "name" : "zeroArgAsyncThrows", + "name" : "roundTripDictionaryExport", "parameters" : [ - + { + "label" : "v", + "name" : "v", + "type" : { + "dictionary" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + } + } ], "returnType" : { - "string" : { - + "dictionary" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } } } }, { - "abiName" : "bjs_asyncRoundTripVoid", + "abiName" : "bjs_roundTripOptionalDictionaryExport", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripVoid", + "name" : "roundTripOptionalDictionaryExport", "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "dictionary" : { + "_0" : { + "string" : { + } + } + } + }, + "_1" : "null" + } + } + } ], "returnType" : { - "void" : { + "nullable" : { + "_0" : { + "dictionary" : { + "_0" : { + "string" : { + } + } + } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_asyncRoundTripInt", + "abiName" : "bjs_roundTripJSValue", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripInt", + "name" : "roundTripJSValue", "parameters" : [ { "label" : "v", "name" : "v", "type" : { - "integer" : { - "_0" : { - "isSigned" : true, - "width" : "word" - } + "jsValue" : { + } } } ], "returnType" : { - "integer" : { - "_0" : { - "isSigned" : true, - "width" : "word" - } + "jsValue" : { + } } }, { - "abiName" : "bjs_asyncRoundTripFloat", + "abiName" : "bjs_roundTripOptionalJSValue", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripFloat", + "name" : "roundTripOptionalJSValue", "parameters" : [ { "label" : "v", "name" : "v", "type" : { - "float" : { + "nullable" : { + "_0" : { + "jsValue" : { + } + }, + "_1" : "null" } } } ], "returnType" : { - "float" : { + "nullable" : { + "_0" : { + "jsValue" : { + } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_asyncRoundTripDouble", + "abiName" : "bjs_roundTripOptionalJSValueArray", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripDouble", + "name" : "roundTripOptionalJSValueArray", "parameters" : [ { "label" : "v", "name" : "v", "type" : { - "double" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "jsValue" : { + } + } + } + }, + "_1" : "null" } } } ], "returnType" : { - "double" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "jsValue" : { + } + } + } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_asyncRoundTripBool", + "abiName" : "bjs_makeImportedFoo", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "asyncRoundTripBool", + "name" : "makeImportedFoo", "parameters" : [ { - "label" : "v", - "name" : "v", + "label" : "value", + "name" : "value", "type" : { - "bool" : { + "string" : { } } } ], "returnType" : { - "bool" : { - + "jsObject" : { + "_0" : "Foo" } } }, { - "abiName" : "bjs_asyncRoundTripString", + "abiName" : "bjs_throwsSwiftError", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "asyncRoundTripString", + "name" : "throwsSwiftError", "parameters" : [ { - "label" : "v", - "name" : "v", + "label" : "shouldThrow", + "name" : "shouldThrow", "type" : { - "string" : { + "bool" : { } } } ], "returnType" : { - "string" : { + "void" : { } } }, { - "abiName" : "bjs_asyncRoundTripSwiftHeapObject", + "abiName" : "bjs_throwsWithIntResult", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "asyncRoundTripSwiftHeapObject", + "name" : "throwsWithIntResult", "parameters" : [ - { - "label" : "v", - "name" : "v", - "type" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } + + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" } } + } + }, + { + "abiName" : "bjs_throwsWithStringResult", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "throwsWithStringResult", + "parameters" : [ + ], "returnType" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "string" : { + } } }, { - "abiName" : "bjs_asyncRoundTripJSObject", + "abiName" : "bjs_throwsWithBoolResult", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "asyncRoundTripJSObject", + "name" : "throwsWithBoolResult", "parameters" : [ - { - "label" : "v", - "name" : "v", - "type" : { - "jsObject" : { - } - } - } ], "returnType" : { - "jsObject" : { + "bool" : { } } }, { - "abiName" : "bjs_takeGreeter", + "abiName" : "bjs_throwsWithFloatResult", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "takeGreeter", + "name" : "throwsWithFloatResult", "parameters" : [ - { - "label" : "g", - "name" : "g", - "type" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - } - }, - { - "label" : "name", - "name" : "name", - "type" : { - "string" : { - } - } - } ], "returnType" : { - "void" : { + "float" : { } } }, { - "abiName" : "bjs_createCalculator", + "abiName" : "bjs_throwsWithDoubleResult", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "createCalculator", + "name" : "throwsWithDoubleResult", "parameters" : [ ], "returnType" : { - "swiftHeapObject" : { - "_0" : "Calculator" + "double" : { + } } }, { - "abiName" : "bjs_useCalculator", + "abiName" : "bjs_throwsWithSwiftHeapObjectResult", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "useCalculator", + "name" : "throwsWithSwiftHeapObjectResult", "parameters" : [ - { - "label" : "calc", - "name" : "calc", - "type" : { - "swiftHeapObject" : { - "_0" : "Calculator" - } - } - }, - { - "label" : "x", - "name" : "x", - "type" : { - "integer" : { - "_0" : { - "isSigned" : true, - "width" : "word" - } - } - } - }, - { - "label" : "y", - "name" : "y", - "type" : { - "integer" : { - "_0" : { - "isSigned" : true, - "width" : "word" - } - } - } - } + ], "returnType" : { - "integer" : { - "_0" : { - "isSigned" : true, - "width" : "word" - } + "swiftHeapObject" : { + "_0" : "Greeter" } } }, { - "abiName" : "bjs_testGreeterToJSValue", + "abiName" : "bjs_throwsWithJSObjectResult", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "testGreeterToJSValue", + "name" : "throwsWithJSObjectResult", "parameters" : [ ], @@ -13016,540 +13574,474 @@ } }, { - "abiName" : "bjs_testCalculatorToJSValue", + "abiName" : "bjs_asyncRoundTripVoid", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "testCalculatorToJSValue", + "name" : "asyncRoundTripVoid", "parameters" : [ ], "returnType" : { - "jsObject" : { + "void" : { } } }, { - "abiName" : "bjs_testSwiftClassAsJSValue", + "abiName" : "bjs_asyncRoundTripInt", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "testSwiftClassAsJSValue", + "name" : "asyncRoundTripInt", "parameters" : [ { - "label" : "greeter", - "name" : "greeter", + "label" : "v", + "name" : "v", "type" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } ], "returnType" : { - "jsObject" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, { - "abiName" : "bjs_setDirection", + "abiName" : "bjs_asyncRoundTripFloat", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "setDirection", + "name" : "asyncRoundTripFloat", "parameters" : [ { - "label" : "_", - "name" : "direction", + "label" : "v", + "name" : "v", "type" : { - "caseEnum" : { - "_0" : "Direction" + "float" : { + } } } ], "returnType" : { - "caseEnum" : { - "_0" : "Direction" + "float" : { + } } }, { - "abiName" : "bjs_getDirection", + "abiName" : "bjs_asyncRoundTripDouble", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "getDirection", + "name" : "asyncRoundTripDouble", "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "double" : { + } + } + } ], "returnType" : { - "caseEnum" : { - "_0" : "Direction" + "double" : { + } } }, { - "abiName" : "bjs_processDirection", + "abiName" : "bjs_asyncRoundTripBool", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "processDirection", + "name" : "asyncRoundTripBool", "parameters" : [ { - "label" : "_", - "name" : "input", + "label" : "v", + "name" : "v", "type" : { - "caseEnum" : { - "_0" : "Direction" + "bool" : { + } } } ], "returnType" : { - "caseEnum" : { - "_0" : "Status" + "bool" : { + } } }, { - "abiName" : "bjs_setTheme", + "abiName" : "bjs_asyncRoundTripString", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "setTheme", + "name" : "asyncRoundTripString", "parameters" : [ { - "label" : "_", - "name" : "theme", + "label" : "v", + "name" : "v", "type" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" + "string" : { + } } } ], "returnType" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" + "string" : { + } } }, { - "abiName" : "bjs_getTheme", + "abiName" : "bjs_asyncRoundTripSwiftHeapObject", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "getTheme", + "name" : "asyncRoundTripSwiftHeapObject", "parameters" : [ - + { + "label" : "v", + "name" : "v", + "type" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } + } ], "returnType" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" + "swiftHeapObject" : { + "_0" : "Greeter" } } }, { - "abiName" : "bjs_asyncRoundTripTheme", + "abiName" : "bjs_asyncRoundTripJSObject", "effects" : { "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripTheme", + "name" : "asyncRoundTripJSObject", "parameters" : [ { - "label" : "_", + "label" : "v", "name" : "v", "type" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" + "jsObject" : { + } } } ], "returnType" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" + "jsObject" : { + } } }, { - "abiName" : "bjs_asyncRoundTripDirection", + "abiName" : "bjs_takeGreeter", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripDirection", + "name" : "takeGreeter", "parameters" : [ { - "label" : "_", - "name" : "v", + "label" : "g", + "name" : "g", + "type" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } + }, + { + "label" : "name", + "name" : "name", "type" : { - "caseEnum" : { - "_0" : "Direction" + "string" : { + } } } ], "returnType" : { - "caseEnum" : { - "_0" : "Direction" + "void" : { + } } }, { - "abiName" : "bjs_asyncRoundTripOptionalTheme", + "abiName" : "bjs_createCalculator", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripOptionalTheme", + "name" : "createCalculator", "parameters" : [ - { - "label" : "_", - "name" : "v", - "type" : { - "nullable" : { - "_0" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" - } - }, - "_1" : "null" - } - } - } + ], "returnType" : { - "nullable" : { - "_0" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" - } - }, - "_1" : "null" + "swiftHeapObject" : { + "_0" : "Calculator" } } }, { - "abiName" : "bjs_asyncRoundTripOptionalDirection", + "abiName" : "bjs_useCalculator", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripOptionalDirection", + "name" : "useCalculator", "parameters" : [ { - "label" : "_", - "name" : "v", + "label" : "calc", + "name" : "calc", "type" : { - "nullable" : { + "swiftHeapObject" : { + "_0" : "Calculator" + } + } + }, + { + "label" : "x", + "name" : "x", + "type" : { + "integer" : { "_0" : { - "caseEnum" : { - "_0" : "Direction" - } - }, - "_1" : "null" + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "label" : "y", + "name" : "y", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } ], "returnType" : { - "nullable" : { + "integer" : { "_0" : { - "caseEnum" : { - "_0" : "Direction" - } - }, - "_1" : "null" + "isSigned" : true, + "width" : "word" + } } } }, { - "abiName" : "bjs_asyncRoundTripDirectionArray", + "abiName" : "bjs_testGreeterToJSValue", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripDirectionArray", + "name" : "testGreeterToJSValue", "parameters" : [ - { - "label" : "_", - "name" : "v", - "type" : { - "array" : { - "_0" : { - "caseEnum" : { - "_0" : "Direction" - } - } - } - } - } + ], "returnType" : { - "array" : { - "_0" : { - "caseEnum" : { - "_0" : "Direction" - } - } + "jsObject" : { + } } }, { - "abiName" : "bjs_asyncRoundTripDirectionDict", + "abiName" : "bjs_testCalculatorToJSValue", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripDirectionDict", + "name" : "testCalculatorToJSValue", "parameters" : [ - { - "label" : "_", - "name" : "v", - "type" : { - "dictionary" : { - "_0" : { - "caseEnum" : { - "_0" : "Direction" - } - } - } - } - } + ], "returnType" : { - "dictionary" : { - "_0" : { - "caseEnum" : { - "_0" : "Direction" - } - } + "jsObject" : { + } } }, { - "abiName" : "bjs_asyncRoundTripThemeArray", + "abiName" : "bjs_testSwiftClassAsJSValue", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripThemeArray", + "name" : "testSwiftClassAsJSValue", "parameters" : [ { - "label" : "_", - "name" : "v", + "label" : "greeter", + "name" : "greeter", "type" : { - "array" : { - "_0" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" - } - } + "swiftHeapObject" : { + "_0" : "Greeter" } } } ], "returnType" : { - "array" : { - "_0" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" - } - } + "jsObject" : { + } } }, { - "abiName" : "bjs_asyncRoundTripThemeDict", + "abiName" : "bjs_setDirection", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripThemeDict", + "name" : "setDirection", "parameters" : [ { "label" : "_", - "name" : "v", + "name" : "direction", "type" : { - "dictionary" : { - "_0" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" - } - } + "caseEnum" : { + "_0" : "Direction" } } } ], "returnType" : { - "dictionary" : { - "_0" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" - } - } + "caseEnum" : { + "_0" : "Direction" } } }, { - "abiName" : "bjs_asyncRoundTripFileSize", + "abiName" : "bjs_getDirection", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripFileSize", + "name" : "getDirection", "parameters" : [ - { - "label" : "_", - "name" : "v", - "type" : { - "rawValueEnum" : { - "_0" : "FileSize", - "_1" : "Int64" - } - } - } + ], "returnType" : { - "rawValueEnum" : { - "_0" : "FileSize", - "_1" : "Int64" + "caseEnum" : { + "_0" : "Direction" } } }, { - "abiName" : "bjs_asyncRoundTripOptionalFileSize", + "abiName" : "bjs_processDirection", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripOptionalFileSize", + "name" : "processDirection", "parameters" : [ { "label" : "_", - "name" : "v", + "name" : "input", "type" : { - "nullable" : { - "_0" : { - "rawValueEnum" : { - "_0" : "FileSize", - "_1" : "Int64" - } - }, - "_1" : "null" + "caseEnum" : { + "_0" : "Direction" } } } ], "returnType" : { - "nullable" : { - "_0" : { - "rawValueEnum" : { - "_0" : "FileSize", - "_1" : "Int64" - } - }, - "_1" : "null" + "caseEnum" : { + "_0" : "Status" } } }, { - "abiName" : "bjs_asyncRoundTripAssociatedValueEnum", + "abiName" : "bjs_setTheme", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripAssociatedValueEnum", + "name" : "setTheme", "parameters" : [ { "label" : "_", - "name" : "v", + "name" : "theme", "type" : { - "associatedValueEnum" : { - "_0" : "AsyncPayloadResult" + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" } } } ], "returnType" : { - "associatedValueEnum" : { - "_0" : "AsyncPayloadResult" + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" } } }, { - "abiName" : "bjs_asyncRoundTripOptionalAssociatedValueEnum", + "abiName" : "bjs_getTheme", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripOptionalAssociatedValueEnum", + "name" : "getTheme", "parameters" : [ - { - "label" : "_", - "name" : "v", - "type" : { - "nullable" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "AsyncPayloadResult" - } - }, - "_1" : "null" - } - } - } + ], "returnType" : { - "nullable" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "AsyncPayloadResult" - } - }, - "_1" : "null" + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" } } }, @@ -15138,445 +15630,210 @@ "integer" : { "_0" : { "isSigned" : true, - "width" : "word" - } - } - }, - "sendingParameters" : false - }, - "useJSTypedClosure" : false - } - } - }, - { - "abiName" : "bjs_roundTripPointerFields", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripPointerFields", - "parameters" : [ - { - "label" : "_", - "name" : "value", - "type" : { - "swiftStruct" : { - "_0" : "PointerFields" - } - } - } - ], - "returnType" : { - "swiftStruct" : { - "_0" : "PointerFields" - } - } - }, - { - "abiName" : "bjs_testStructDefault", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "testStructDefault", - "parameters" : [ - { - "defaultValue" : { - "structLiteral" : { - "_0" : "DataPoint", - "_1" : [ - { - "name" : "x", - "value" : { - "float" : { - "_0" : 1 - } - } - }, - { - "name" : "y", - "value" : { - "float" : { - "_0" : 2 - } - } - }, - { - "name" : "label", - "value" : { - "string" : { - "_0" : "default" - } - } - }, - { - "name" : "optCount", - "value" : { - "null" : { - - } - } - }, - { - "name" : "optFlag", - "value" : { - "null" : { - - } - } - } - ] - } - }, - "label" : "point", - "name" : "point", - "type" : { - "swiftStruct" : { - "_0" : "DataPoint" - } - } - } - ], - "returnType" : { - "string" : { - - } - } - }, - { - "abiName" : "bjs_cartToJSObject", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "cartToJSObject", - "parameters" : [ - { - "label" : "_", - "name" : "cart", - "type" : { - "swiftStruct" : { - "_0" : "CopyableCart" - } - } - } - ], - "returnType" : { - "jsObject" : { - - } - } - }, - { - "abiName" : "bjs_nestedCartToJSObject", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "nestedCartToJSObject", - "parameters" : [ - { - "label" : "_", - "name" : "cart", - "type" : { - "swiftStruct" : { - "_0" : "CopyableNestedCart" - } - } - } - ], - "returnType" : { - "jsObject" : { - - } - } - }, - { - "abiName" : "bjs_roundTripDataPoint", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripDataPoint", - "parameters" : [ - { - "label" : "_", - "name" : "data", - "type" : { - "swiftStruct" : { - "_0" : "DataPoint" - } - } - } - ], - "returnType" : { - "swiftStruct" : { - "_0" : "DataPoint" - } - } - }, - { - "abiName" : "bjs_roundTripPublicPoint", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripPublicPoint", - "parameters" : [ - { - "label" : "_", - "name" : "point", - "type" : { - "swiftStruct" : { - "_0" : "PublicPoint" - } - } - } - ], - "returnType" : { - "swiftStruct" : { - "_0" : "PublicPoint" - } - } - }, - { - "abiName" : "bjs_asyncRoundTripPublicPoint", - "effects" : { - "isAsync" : true, - "isStatic" : false, - "isThrows" : false - }, - "name" : "asyncRoundTripPublicPoint", - "parameters" : [ - { - "label" : "_", - "name" : "point", - "type" : { - "swiftStruct" : { - "_0" : "PublicPoint" - } - } - } - ], - "returnType" : { - "swiftStruct" : { - "_0" : "PublicPoint" + "width" : "word" + } + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false } } }, { - "abiName" : "bjs_asyncRoundTripPublicPointThrows", + "abiName" : "bjs_roundTripPointerFields", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, - "isThrows" : true + "isThrows" : false }, - "name" : "asyncRoundTripPublicPointThrows", + "name" : "roundTripPointerFields", "parameters" : [ { "label" : "_", - "name" : "point", + "name" : "value", "type" : { "swiftStruct" : { - "_0" : "PublicPoint" + "_0" : "PointerFields" } } } ], "returnType" : { "swiftStruct" : { - "_0" : "PublicPoint" + "_0" : "PointerFields" } } }, { - "abiName" : "bjs_asyncStructOrThrow", + "abiName" : "bjs_testStructDefault", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, - "isThrows" : true + "isThrows" : false }, - "name" : "asyncStructOrThrow", + "name" : "testStructDefault", "parameters" : [ { - "label" : "_", - "name" : "shouldThrow", - "type" : { - "bool" : { + "defaultValue" : { + "structLiteral" : { + "_0" : "DataPoint", + "_1" : [ + { + "name" : "x", + "value" : { + "float" : { + "_0" : 1 + } + } + }, + { + "name" : "y", + "value" : { + "float" : { + "_0" : 2 + } + } + }, + { + "name" : "label", + "value" : { + "string" : { + "_0" : "default" + } + } + }, + { + "name" : "optCount", + "value" : { + "null" : { + + } + } + }, + { + "name" : "optFlag", + "value" : { + "null" : { + } + } + } + ] + } + }, + "label" : "point", + "name" : "point", + "type" : { + "swiftStruct" : { + "_0" : "DataPoint" } } } ], "returnType" : { - "swiftStruct" : { - "_0" : "PublicPoint" + "string" : { + } } }, { - "abiName" : "bjs_asyncCombinePublicPoints", + "abiName" : "bjs_cartToJSObject", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncCombinePublicPoints", + "name" : "cartToJSObject", "parameters" : [ { "label" : "_", - "name" : "a", - "type" : { - "swiftStruct" : { - "_0" : "PublicPoint" - } - } - }, - { - "label" : "_", - "name" : "b", + "name" : "cart", "type" : { "swiftStruct" : { - "_0" : "PublicPoint" + "_0" : "CopyableCart" } } } ], "returnType" : { - "swiftStruct" : { - "_0" : "PublicPoint" + "jsObject" : { + } } }, { - "abiName" : "bjs_asyncRoundTripContact", + "abiName" : "bjs_nestedCartToJSObject", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripContact", + "name" : "nestedCartToJSObject", "parameters" : [ { "label" : "_", - "name" : "contact", + "name" : "cart", "type" : { "swiftStruct" : { - "_0" : "Contact" + "_0" : "CopyableNestedCart" } } } ], "returnType" : { - "swiftStruct" : { - "_0" : "Contact" + "jsObject" : { + } } }, { - "abiName" : "bjs_asyncRoundTripPublicPointArray", + "abiName" : "bjs_roundTripDataPoint", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripPublicPointArray", + "name" : "roundTripDataPoint", "parameters" : [ { "label" : "_", - "name" : "points", + "name" : "data", "type" : { - "array" : { - "_0" : { - "swiftStruct" : { - "_0" : "PublicPoint" - } - } + "swiftStruct" : { + "_0" : "DataPoint" } } } ], "returnType" : { - "array" : { - "_0" : { - "swiftStruct" : { - "_0" : "PublicPoint" - } - } + "swiftStruct" : { + "_0" : "DataPoint" } } }, { - "abiName" : "bjs_asyncRoundTripOptionalPublicPoint", + "abiName" : "bjs_roundTripPublicPoint", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripOptionalPublicPoint", + "name" : "roundTripPublicPoint", "parameters" : [ { "label" : "_", "name" : "point", "type" : { - "nullable" : { - "_0" : { - "swiftStruct" : { - "_0" : "PublicPoint" - } - }, - "_1" : "null" - } - } - } - ], - "returnType" : { - "nullable" : { - "_0" : { "swiftStruct" : { "_0" : "PublicPoint" } - }, - "_1" : "null" - } - } - }, - { - "abiName" : "bjs_asyncRoundTripPublicPointDict", - "effects" : { - "isAsync" : true, - "isStatic" : false, - "isThrows" : false - }, - "name" : "asyncRoundTripPublicPointDict", - "parameters" : [ - { - "label" : "_", - "name" : "points", - "type" : { - "dictionary" : { - "_0" : { - "swiftStruct" : { - "_0" : "PublicPoint" - } - } - } } } ], "returnType" : { - "dictionary" : { - "_0" : { - "swiftStruct" : { - "_0" : "PublicPoint" - } - } + "swiftStruct" : { + "_0" : "PublicPoint" } } }, @@ -16363,25 +16620,120 @@ "_0" : "Greeter" } } - }, + }, + { + "isReadonly" : false, + "name" : "optionalHelper", + "type" : { + "nullable" : { + "_0" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + }, + "_1" : "null" + } + } + } + ] + } + ], + "structs" : [ + { + "constructor" : { + "abiName" : "bjs_JSCoordinate_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "latitude", + "name" : "latitude", + "type" : { + "double" : { + + } + } + }, + { + "label" : "longitude", + "name" : "longitude", + "type" : { + "double" : { + + } + } + } + ] + }, + "methods" : [ + + ], + "name" : "JSCoordinate", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "latitude", + "type" : { + "double" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "longitude", + "type" : { + "double" : { + + } + } + } + ], + "swiftCallName" : "JSCoordinate" + }, + { + "constructor" : { + "abiName" : "bjs_SessionState_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "token", + "name" : "token", + "type" : { + "string" : { + + } + } + } + ] + }, + "methods" : [ + + ], + "name" : "SessionState", + "properties" : [ { - "isReadonly" : false, - "name" : "optionalHelper", + "isReadonly" : true, + "isStatic" : false, + "name" : "token", "type" : { - "nullable" : { - "_0" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - }, - "_1" : "null" + "string" : { + } } } - ] - } - ], - "structs" : [ + ], + "swiftCallName" : "SessionState" + }, { "methods" : [ @@ -17970,104 +18322,400 @@ "_0" : { "integer" : { "_0" : { - "isSigned" : true, - "width" : "word" - } + "isSigned" : true, + "width" : "word" + } + } + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "abiName" : "bjs_ArrayMembers_firstString", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "firstString", + "parameters" : [ + { + "label" : "_", + "name" : "values", + "type" : { + "array" : { + "_0" : { + "string" : { + + } + } + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" + } + } + } + ], + "name" : "ArrayMembers", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "ints", + "type" : { + "array" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "optStrings", + "type" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "string" : { + + } + } + } + }, + "_1" : "null" + } + } + } + ], + "swiftCallName" : "ArrayMembers" + } + ] + }, + "imported" : { + "children" : [ + { + "functions" : [ + + ], + "types" : [ + { + "accessLevel" : "internal", + "constructor" : { + "accessLevel" : "internal", + "parameters" : [ + { + "name" : "label", + "type" : { + "string" : { + + } + } + } + ] + }, + "getters" : [ + { + "accessLevel" : "internal", + "name" : "label", + "type" : { + "string" : { + + } + } + } + ], + "methods" : [ + + ], + "name" : "Surface", + "setters" : [ + + ], + "staticMethods" : [ + + ] + }, + { + "accessLevel" : "internal", + "getters" : [ + + ], + "methods" : [ + + ], + "name" : "AliasImports", + "setters" : [ + + ], + "staticMethods" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsRoundTripTagged", + "parameters" : [ + { + "name" : "value", + "type" : { + "alias" : { + "name" : "Tagged", + "underlying" : { + "string" : { + + } + } + } + } + } + ], + "returnType" : { + "alias" : { + "name" : "Tagged", + "underlying" : { + "string" : { + + } + } + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsRoundTripOptionalTagged", + "parameters" : [ + { + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "alias" : { + "name" : "Tagged", + "underlying" : { + "string" : { + + } + } + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "alias" : { + "name" : "Tagged", + "underlying" : { + "string" : { + + } + } + } + }, + "_1" : "null" + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsProduceOptionalCanvas", + "parameters" : [ + { + "name" : "label", + "type" : { + "nullable" : { + "_0" : { + "string" : { + + } + }, + "_1" : "null" } } } + ], + "returnType" : { + "nullable" : { + "_0" : { + "alias" : { + "name" : "Canvas", + "underlying" : { + "jsObject" : { + "_0" : "Surface" + } + } + } + }, + "_1" : "null" + } } - } - ], - "returnType" : { - "integer" : { - "_0" : { - "isSigned" : true, - "width" : "word" - } - } - } - }, - { - "abiName" : "bjs_ArrayMembers_firstString", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "firstString", - "parameters" : [ + }, { - "label" : "_", - "name" : "values", - "type" : { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsRoundTripAliasedTags", + "parameters" : [ + { + "name" : "values", + "type" : { + "array" : { + "_0" : { + "nullable" : { + "_0" : { + "alias" : { + "name" : "AliasedTag", + "underlying" : { + "associatedValueEnum" : { + "_0" : "InnerTag" + } + } + } + }, + "_1" : "null" + } + } + } + } + } + ], + "returnType" : { "array" : { "_0" : { - "string" : { - + "nullable" : { + "_0" : { + "alias" : { + "name" : "AliasedTag", + "underlying" : { + "associatedValueEnum" : { + "_0" : "InnerTag" + } + } + } + }, + "_1" : "null" } } } } - } - ], - "returnType" : { - "nullable" : { - "_0" : { - "string" : { - - } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true }, - "_1" : "null" - } - } - } - ], - "name" : "ArrayMembers", - "properties" : [ - { - "isReadonly" : true, - "isStatic" : false, - "name" : "ints", - "type" : { - "array" : { - "_0" : { - "integer" : { - "_0" : { - "isSigned" : true, - "width" : "word" + "name" : "jsRoundTripPolygon", + "parameters" : [ + { + "name" : "value", + "type" : { + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" + } + } + } } } - } - } - } - }, - { - "isReadonly" : true, - "isStatic" : false, - "name" : "optStrings", - "type" : { - "nullable" : { - "_0" : { - "array" : { - "_0" : { - "string" : { - + ], + "returnType" : { + "alias" : { + "name" : "Polygon", + "underlying" : { + "swiftHeapObject" : { + "_0" : "PolygonReference" } } } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true }, - "_1" : "null" + "name" : "jsRoundTripCoordinate", + "parameters" : [ + { + "name" : "value", + "type" : { + "alias" : { + "name" : "Coordinate", + "underlying" : { + "swiftStruct" : { + "_0" : "JSCoordinate" + } + } + } + } + } + ], + "returnType" : { + "alias" : { + "name" : "Coordinate", + "underlying" : { + "swiftStruct" : { + "_0" : "JSCoordinate" + } + } + } + } } - } + ] } - ], - "swiftCallName" : "ArrayMembers" - } - ] - }, - "imported" : { - "children" : [ + ] + }, { "functions" : [ @@ -18961,137 +19609,31 @@ "isStatic" : false, "isThrows" : true }, - "name" : "jsAsyncRoundTripStringArray", - "parameters" : [ - { - "name" : "values", - "type" : { - "array" : { - "_0" : { - "string" : { - - } - } - } - } - } - ], - "returnType" : { - "array" : { - "_0" : { - "string" : { - - } - } - } - } - }, - { - "accessLevel" : "internal", - "effects" : { - "isAsync" : true, - "isStatic" : false, - "isThrows" : true - }, - "name" : "jsAsyncRoundTripFeatureFlag", - "parameters" : [ - { - "name" : "v", - "type" : { - "rawValueEnum" : { - "_0" : "FeatureFlag", - "_1" : "String" - } - } - } - ], - "returnType" : { - "rawValueEnum" : { - "_0" : "FeatureFlag", - "_1" : "String" - } - } - }, - { - "accessLevel" : "internal", - "effects" : { - "isAsync" : true, - "isStatic" : false, - "isThrows" : true - }, - "name" : "jsAsyncRoundTripAssociatedValueEnum", - "parameters" : [ - { - "name" : "v", - "type" : { - "associatedValueEnum" : { - "_0" : "AsyncImportedPayloadResult" - } - } - } - ], - "returnType" : { - "associatedValueEnum" : { - "_0" : "AsyncImportedPayloadResult" - } - } - }, - { - "accessLevel" : "internal", - "effects" : { - "isAsync" : true, - "isStatic" : false, - "isThrows" : true - }, - "name" : "jsAsyncRoundTripOptionalAssociatedValueEnum", + "name" : "jsAsyncRoundTripStringArray", "parameters" : [ { - "name" : "v", + "name" : "values", "type" : { - "nullable" : { + "array" : { "_0" : { - "associatedValueEnum" : { - "_0" : "AsyncImportedPayloadResult" + "string" : { + } - }, - "_1" : "null" + } } } } ], "returnType" : { - "nullable" : { + "array" : { "_0" : { - "associatedValueEnum" : { - "_0" : "AsyncImportedPayloadResult" + "string" : { + } - }, - "_1" : "null" + } } } - } - ] - } - ] - }, - { - "functions" : [ - - ], - "types" : [ - { - "accessLevel" : "internal", - "getters" : [ - - ], - "methods" : [ - - ], - "name" : "ClosureAsyncImports", - "setters" : [ - - ], - "staticMethods" : [ + }, { "accessLevel" : "internal", "effects" : { @@ -19099,13 +19641,22 @@ "isStatic" : false, "isThrows" : true }, - "name" : "runJsClosureAsyncTests", + "name" : "jsAsyncRoundTripFeatureFlag", "parameters" : [ - + { + "name" : "v", + "type" : { + "rawValueEnum" : { + "_0" : "FeatureFlag", + "_1" : "String" + } + } + } ], "returnType" : { - "void" : { - + "rawValueEnum" : { + "_0" : "FeatureFlag", + "_1" : "String" } } } @@ -19934,45 +20485,6 @@ { "functions" : [ - ], - "types" : [ - { - "accessLevel" : "internal", - "getters" : [ - - ], - "methods" : [ - - ], - "name" : "ClosureThrowsImports", - "setters" : [ - - ], - "staticMethods" : [ - { - "accessLevel" : "internal", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : true - }, - "name" : "runJsClosureThrowsTests", - "parameters" : [ - - ], - "returnType" : { - "void" : { - - } - } - } - ] - } - ] - }, - { - "functions" : [ - ], "types" : [ { @@ -20535,6 +21047,23 @@ } } }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "runAliasAsyncWorks", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + }, { "accessLevel" : "internal", "effects" : { @@ -21086,95 +21615,6 @@ } ] }, - { - "functions" : [ - { - "accessLevel" : "internal", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : true - }, - "name" : "jsRoundTripLightColor", - "parameters" : [ - { - "name" : "value", - "type" : { - "caseEnum" : { - "_0" : "LightColor" - } - } - } - ], - "returnType" : { - "caseEnum" : { - "_0" : "LightColor" - } - } - }, - { - "accessLevel" : "internal", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : true - }, - "name" : "jsRoundTripImportedPayloadSignal", - "parameters" : [ - { - "name" : "value", - "type" : { - "associatedValueEnum" : { - "_0" : "ImportedPayloadSignal" - } - } - } - ], - "returnType" : { - "associatedValueEnum" : { - "_0" : "ImportedPayloadSignal" - } - } - }, - { - "accessLevel" : "internal", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : true - }, - "name" : "jsRoundTripOptionalImportedPayloadSignal", - "parameters" : [ - { - "name" : "value", - "type" : { - "nullable" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "ImportedPayloadSignal" - } - }, - "_1" : "null" - } - } - } - ], - "returnType" : { - "nullable" : { - "_0" : { - "associatedValueEnum" : { - "_0" : "ImportedPayloadSignal" - } - }, - "_1" : "null" - } - } - } - ], - "types" : [ - - ] - }, { "functions" : [ { @@ -21222,40 +21662,6 @@ "_0" : "Point" } } - }, - { - "accessLevel" : "internal", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : true - }, - "name" : "jsRoundTripOptionalPoint", - "parameters" : [ - { - "name" : "point", - "type" : { - "nullable" : { - "_0" : { - "swiftStruct" : { - "_0" : "Point" - } - }, - "_1" : "null" - } - } - } - ], - "returnType" : { - "nullable" : { - "_0" : { - "swiftStruct" : { - "_0" : "Point" - } - }, - "_1" : "null" - } - } } ], "types" : [ @@ -22523,40 +22929,6 @@ } } }, - { - "accessLevel" : "internal", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : true - }, - "name" : "jsRoundTripOptionalJSObjectNull", - "parameters" : [ - { - "name" : "value", - "type" : { - "nullable" : { - "_0" : { - "jsObject" : { - - } - }, - "_1" : "null" - } - } - } - ], - "returnType" : { - "nullable" : { - "_0" : { - "jsObject" : { - - } - }, - "_1" : "null" - } - } - }, { "accessLevel" : "internal", "effects" : { diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/AliasTests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/AliasTests.mjs new file mode 100644 index 000000000..db6225b21 --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/JavaScript/AliasTests.mjs @@ -0,0 +1,357 @@ +// @ts-check +import assert from "node:assert"; + +export class Surface { + constructor(label) { + this.label = label; + } +}; + +/** + * @returns {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Imports["AliasImports"]} + */ +export function getImports(importsContext) { + return { + jsRoundTripTagged: (value) => { + return value; + }, + jsRoundTripOptionalTagged: (value) => { + return value ?? null; + }, + jsProduceOptionalCanvas: (label) => { + if (label === null || label === undefined) return null; + return new Surface(label); + }, + jsRoundTripAliasedTags: (values) => { + return values.map((tag) => tag ?? null); + }, + jsRoundTripPolygon: (value) => { + return value; + }, + jsRoundTripCoordinate: (value) => { + return { ...value }; + }, + }; +} + +/** + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports + */ +export function runAliasWorks(exports) { + runBasicRoundTrip(exports); + runOptional(exports); + runMethodsOnTarget(exports); + runStaticReturn(exports); + runMultipleAliases(exports); + runArrays(exports); + runThrows(exports); + runNonCopyable(exports); + runClosureWithAliasParameter(exports); + runOptionalInArray(exports); + runClassPropertyAndInitWithAlias(exports); + runAssociatedValueEnumPayload(exports); + runStructToStructAlias(exports); + runStructToEnumAlias(exports); + runClassToStructAlias(exports); + runEnumToClassAlias(exports); +} + +export async function runAliasAsyncWorks(exports) { + await runAsyncReturningAlias(exports); +} + +/** + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports + */ +function runBasicRoundTrip(exports) { + const seed = new exports.PolygonReference([1, 2, 3], "seed"); + assert.equal(seed.vertexCount(), 3); + assert.equal(seed.summary(), "seed(3)"); + + const roundtrip = exports.roundTripPolygon(seed); + assert.equal(roundtrip.vertexCount(), 3); + assert.equal(roundtrip.summary(), "seed(3)"); + + assert.equal(exports.polygonVertexCount(seed), 3); + + const appended = exports.appendVertex(seed, 4); + assert.equal(appended.vertexCount(), 4); + assert.equal(appended.summary(), "seed(4)"); + + seed.release(); + roundtrip.release(); + appended.release(); +} + +/** + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports + */ +function runOptional(exports) { + assert.equal(exports.optionalRoundTripPolygon(null), null); + + const original = new exports.PolygonReference([7, 8, 9], "opt"); + const echoed = exports.optionalRoundTripPolygon(original); + assert.notEqual(echoed, null); + if (echoed) { + assert.equal(echoed.vertexCount(), 3); + echoed.release(); + } + original.release(); +} + +/** + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports + */ +function runMethodsOnTarget(exports) { + const a = new exports.PolygonReference([1, 2], "a"); + + const snap = a.snapshot(); + assert.equal(snap.summary(), "a(2)"); + + const b = new exports.PolygonReference([3, 4, 5], "b"); + const merged = a.merge(b); + assert.equal(merged.vertexCount(), 5); + assert.equal(merged.summary(), "a(5)"); + + a.release(); + b.release(); + snap.release(); + merged.release(); +} + +/** + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports + */ +function runStaticReturn(exports) { + const o = exports.PolygonReference.origin("o"); + assert.equal(o.vertexCount(), 0); + assert.equal(o.summary(), "o(0)"); + o.release(); +} + +/** + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports + */ +function runMultipleAliases(exports) { + const tag = exports.makeTag("hello"); + assert.equal(tag.describe(), "tag:hello"); + tag.release(); +} + +/** + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports + */ +function runArrays(exports) { + const a = new exports.PolygonReference([1], "a"); + const b = new exports.PolygonReference([2, 3], "b"); + const c = new exports.PolygonReference([4, 5, 6], "c"); + + const roundtripped = exports.roundTripPolygonArray([a, b, c]); + assert.equal(roundtripped.length, 3); + assert.equal(roundtripped[0].vertexCount(), 1); + assert.equal(roundtripped[1].vertexCount(), 2); + assert.equal(roundtripped[2].vertexCount(), 3); + assert.equal(roundtripped[0].summary(), "a(1)"); + assert.equal(roundtripped[1].summary(), "b(2)"); + assert.equal(roundtripped[2].summary(), "c(3)"); + + const combined = exports.concatPolygons([a, b, c]); + assert.equal(combined.vertexCount(), 6); + assert.equal(combined.summary(), "concat(6)"); + + const empty = exports.roundTripPolygonArray([]); + assert.equal(empty.length, 0); + + const split = exports.splitPolygon(combined); + assert.equal(split.length, 6); + for (const piece of split) { + assert.equal(piece.vertexCount(), 1); + piece.release(); + } + + a.release(); + b.release(); + c.release(); + combined.release(); + for (const r of roundtripped) r.release(); +} + +/** + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports + */ +function runThrows(exports) { + const valid = new exports.PolygonReference([1, 2], "v"); + const echoed = exports.validatePolygon(valid); + assert.equal(echoed.summary(), "v(2)"); + echoed.release(); + valid.release(); + + const empty = new exports.PolygonReference([], "empty"); + assert.throws(() => exports.validatePolygon(empty), /empty polygon/); + empty.release(); +} + +/** + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports + */ +function runNonCopyable(exports) { + const seed = exports.makeToken(7); + assert.equal(seed.read(), 7); + + const next = exports.incrementToken(seed); + assert.equal(next.read(), 8); + + next.release(); + seed.release(); +} + +/** + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports + */ +function runClosureWithAliasParameter(exports) { + const inspector = exports.makePolygonInspector(); + const poly = new exports.PolygonReference([10, 20, 30, 40], "inspect"); + assert.equal(inspector(poly), 4); + poly.release(); +} + +/** + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports + */ +function runOptionalInArray(exports) { + const a = new exports.PolygonReference([1], "a"); + const b = new exports.PolygonReference([2, 3], "b"); + + const echoed = exports.roundTripOptionalPolygonArray([a, null, b, null]); + assert.equal(echoed.length, 4); + assert.notEqual(echoed[0], null); + assert.equal(echoed[1], null); + assert.notEqual(echoed[2], null); + assert.equal(echoed[3], null); + if (echoed[0]) { + assert.equal(echoed[0].vertexCount(), 1); + } + if (echoed[2]) { + assert.equal(echoed[2].vertexCount(), 2); + } + + a.release(); + b.release(); + for (const e of echoed) { + if (e) { + e.release(); + } + } +} + +/** + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports + */ +function runClassPropertyAndInitWithAlias(exports) { + const made = exports.makeTagHolder("origin", 1); + assert.equal(made.describe(), "holder(origin, v1)"); + const initial = made.tag; + assert.equal(initial.describe(), "tag:origin"); + + const replacement = exports.makeTag("renamed"); + made.tag = replacement; + assert.equal(made.describe(), "holder(renamed, v1)"); + made.version = 7; + assert.equal(made.describe(), "holder(renamed, v7)"); + + const fresh = exports.makeTag("constructed"); + const ctor = new exports.TagHolderReference(fresh, 99); + assert.equal(ctor.describe(), "holder(constructed, v99)"); + + initial.release(); + replacement.release(); + fresh.release(); + made.release(); + ctor.release(); +} + +/** + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports + */ +function runAssociatedValueEnumPayload(exports) { + const poly = new exports.PolygonReference([1, 2, 3], "shape"); + const wrapped = exports.makeShapePolygon(poly); + assert.equal(wrapped.tag, exports.Shape.Tag.Polygon); + if (wrapped.tag === exports.Shape.Tag.Polygon) { + assert.equal(wrapped.param0.vertexCount(), 3); + } + + const echoed = exports.roundTripShape(wrapped); + assert.equal(echoed.tag, exports.Shape.Tag.Polygon); + if (echoed.tag === exports.Shape.Tag.Polygon) { + assert.equal(echoed.param0.vertexCount(), 3); + echoed.param0.release(); + } + + const empty = exports.makeShapeEmpty(); + assert.equal(empty.tag, exports.Shape.Tag.Empty); + const emptyEcho = exports.roundTripShape(empty); + assert.equal(emptyEcho.tag, exports.Shape.Tag.Empty); + + if (wrapped.tag === exports.Shape.Tag.Polygon) { + wrapped.param0.release(); + } + poly.release(); +} + +/** + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports + */ +function runStructToStructAlias(exports) { + const seed = { latitude: 45.5, longitude: -73.5 }; + const echoed = exports.roundTripCoordinate(seed); + assert.deepStrictEqual(echoed, seed); +} + +/** + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports + */ +function runStructToEnumAlias(exports) { + const made = exports.makeAlert(exports.Severity.Warning); + assert.equal(made, exports.Severity.Warning); + + const echoed = exports.roundTripAlert(exports.Severity.Error); + assert.equal(echoed, exports.Severity.Error); +} + +/** + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports + */ +function runClassToStructAlias(exports) { + const made = exports.makeSession("hello"); + assert.deepStrictEqual(made, { token: "hello" }); + + const echoed = exports.roundTripSession({ token: "world" }); + assert.deepStrictEqual(echoed, { token: "world" }); +} + +/** + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports + */ +function runEnumToClassAlias(exports) { + const seed = exports.PriorityReference.medium(); + assert.equal(seed.describe(), "medium"); + assert.equal(seed.weight(), 5); + + const echoed = exports.roundTripPriority(seed); + assert.equal(echoed.describe(), "medium"); + assert.equal(echoed.weight(), 5); + + seed.release(); + echoed.release(); +} + +/** + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports + */ +async function runAsyncReturningAlias(exports) { + const result = await exports.asyncMakePolygon("async"); + assert.equal(result.vertexCount(), 2); + assert.equal(result.summary(), "async(2)"); + result.release(); +} diff --git a/Tests/BridgeJSRuntimeTests/bridge-js.d.ts b/Tests/BridgeJSRuntimeTests/bridge-js.d.ts index 9fef391c1..582113df1 100644 --- a/Tests/BridgeJSRuntimeTests/bridge-js.d.ts +++ b/Tests/BridgeJSRuntimeTests/bridge-js.d.ts @@ -26,6 +26,8 @@ export class JsGreeter { export function runAsyncWorks(): Promise; +export function runAliasAsyncWorks(): Promise; + export interface WeatherData { temperature: number; description: string; diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index 658bceed9..5b6f8b39f 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -5,6 +5,7 @@ import { } from '../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.js'; import { ImportedFoo } from './BridgeJSRuntimeTests/JavaScript/Types.mjs'; import { runJsOptionalSupportTests } from './BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs'; +import { runAliasWorks, runAliasAsyncWorks, getImports as getAliasImports, Surface } from './BridgeJSRuntimeTests/JavaScript/AliasTests.mjs'; import { getImports as getClosureSupportImports } from './BridgeJSRuntimeTests/JavaScript/ClosureSupportTests.mjs'; import { getImports as getClosureThrowsImports } from './BridgeJSRuntimeTests/JavaScript/ClosureThrowsTests.mjs'; import { getImports as getClosureAsyncImports } from './BridgeJSRuntimeTests/JavaScript/ClosureAsyncTests.mjs'; @@ -107,6 +108,7 @@ export async function setupOptions(options, context) { }, ArrayElementObject, JSClassWithArrayMembers, + Surface, JsGreeter: class { /** * @param {string} name @@ -141,6 +143,14 @@ export async function setupOptions(options, context) { await runAsyncWorksTests(exports); return; }, + runAliasAsyncWorks: async () => { + const exports = importsContext.getExports(); + if (!exports) { + throw new Error("No exports!?"); + } + await runAliasAsyncWorks(exports); + return; + }, AsyncImportImports: getAsyncImportImports(importsContext), fetchWeatherData: (city) => { return Promise.resolve({ @@ -173,6 +183,7 @@ export async function setupOptions(options, context) { IntegerTypesSupportImports: getIntegerTypesSupportImports(importsContext), JSTypedArrayImports: getJSTypedArrayImports(importsContext), IdentityModeTestImports: getIdentityModeTestImports(importsContext), + AliasImports: getAliasImports(importsContext), }; }, addToCoreImports(importObject, importsContext) { @@ -196,6 +207,13 @@ export async function setupOptions(options, context) { } return BridgeJSRuntimeTests_runJsStructWorks(exports); } + bridgeJSRuntimeTests["runAliasWorks"] = () => { + const exports = getExports(); + if (!exports) { + throw new Error("No exports!?"); + } + runAliasWorks(exports); + } const bridgeJSGlobalTests = importObject["BridgeJSGlobalTests"] || {}; bridgeJSGlobalTests["runJsWorksGlobal"] = () => { return BridgeJSGlobalTests_runJsWorksGlobal(); From fce419345ba1ec28505f9ba52f233ffc98c5e872 Mon Sep 17 00:00:00 2001 From: William Taylor Date: Fri, 12 Jun 2026 12:09:56 +1000 Subject: [PATCH 22/50] BridgeJS: Remove insertion of bridging calls for aliases --- .../Sources/BridgeJSCore/ClosureCodegen.swift | 8 +- .../Sources/BridgeJSCore/ExportSwift.swift | 126 +- .../Sources/BridgeJSCore/ImportTS.swift | 29 +- .../BridgeJSCore/SwiftToSkeleton.swift | 24 +- .../Sources/BridgeJSLink/JSGlueGen.swift | 62 +- .../BridgeJSSkeleton/BridgeJSSkeleton.swift | 16 +- .../CrossModuleResolutionTests.swift | 30 + .../BridgeJSCodegenTests/Alias.swift | 64 +- .../BridgeJSCodegenTests/AliasInClosure.swift | 12 +- .../AsyncAssociatedValueEnum.json | 3 + .../BridgeJSCodegenTests/EnumAlias.swift | 8 +- .../EnumAssociatedValueImport.json | 3 + .../BridgeJSCodegenTests/EnumCaseImport.json | 3 + .../SwiftClosureImports.json | 3 + .../__Snapshots__/BridgeJSLinkTests/Alias.js | 7 + .../BridgeJSLinkTests/AliasInClosure.js | 7 + .../BridgeJSLinkTests/EnumAlias.js | 7 + .../JavaScriptKit/BridgeJSIntrinsics.swift | 288 + Tests/BridgeJSRuntimeTests/AliasAPIs.swift | 114 +- Tests/BridgeJSRuntimeTests/AliasTests.swift | 15 +- .../Generated/BridgeJS.Macros.swift | 2 - .../Generated/BridgeJS.swift | 12189 +++++++++------- .../Generated/JavaScript/BridgeJS.json | 3216 ++-- .../JavaScript/AliasTests.mjs | 62 +- Tests/BridgeJSRuntimeTests/bridge-js.d.ts | 2 - Tests/prelude.mjs | 10 +- 26 files changed, 10085 insertions(+), 6225 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift index 317bd0b4f..969b3c01e 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ClosureCodegen.swift @@ -153,8 +153,9 @@ public struct ClosureCodegen { let argNames = liftInfo.parameters.map { (argName, _) in liftInfo.parameters.count > 1 ? "\(paramName)\(argName.capitalizedFirstLetter)" : paramName } - let liftCall = "\(paramType.unaliased.swiftType).bridgeJSLiftParameter(\(argNames.joined(separator: ", ")))" - liftedParams.append(paramType.liftAliases(expression: liftCall)) + liftedParams.append( + "\(paramType.swiftType).bridgeJSLiftParameter(\(argNames.joined(separator: ", ")))" + ) } let tryPrefix = signature.isThrows ? "try " : "" @@ -198,8 +199,7 @@ public struct ClosureCodegen { } printer.write("}") default: - let lowered = signature.returnType.lowerAliases(expression: "result") - printer.write("return \(lowered).bridgeJSLowerReturn()") + printer.write("return result.bridgeJSLowerReturn()") } } } diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift index cdbd3970f..663c2362e 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift @@ -100,6 +100,15 @@ public class ExportSwift { } } } + + withSpan("Render Aliases") { [self] in + let aliasCodegen = AliasCodegen() + for alias in skeleton.aliases { + if let aliasExtension = aliasCodegen.renderAliasConformance(alias) { + decls.append(aliasExtension) + } + } + } return withSpan("Format Export Glue") { return decls.map { $0.description }.joined(separator: "\n\n") } @@ -227,15 +236,15 @@ public class ExportSwift { } else { optionalSwiftType = "JSUndefinedOr" } - typeNameForIntrinsic = "\(optionalSwiftType)<\(wrappedType.unaliased.swiftType)>" - let liftCall = - "\(typeNameForIntrinsic).bridgeJSLiftParameter(\(argumentsToLift.joined(separator: ", ")))" - liftingExpr = "\(raw: param.type.liftAliases(expression: liftCall))" + typeNameForIntrinsic = "\(optionalSwiftType)<\(wrappedType.swiftType)>" + liftingExpr = ExprSyntax( + "\(raw: typeNameForIntrinsic).bridgeJSLiftParameter(\(raw: argumentsToLift.joined(separator: ", ")))" + ) default: - typeNameForIntrinsic = param.type.unaliased.swiftType - let liftCall = - "\(typeNameForIntrinsic).bridgeJSLiftParameter(\(argumentsToLift.joined(separator: ", ")))" - liftingExpr = "\(raw: param.type.liftAliases(expression: liftCall))" + typeNameForIntrinsic = param.type.swiftType + liftingExpr = ExprSyntax( + "\(raw: typeNameForIntrinsic).bridgeJSLiftParameter(\(raw: argumentsToLift.joined(separator: ", ")))" + ) } liftedParameterExprs.append(liftingExpr) @@ -280,8 +289,7 @@ public class ExportSwift { } if effects.isAsync, returnType != .void { - let lowered = returnType.lowerAliases(expression: callExpr.description) - return CodeBlockItemSyntax(item: .init(StmtSyntax("return \(raw: lowered)"))) + return CodeBlockItemSyntax(item: .init(StmtSyntax("return \(raw: callExpr)"))) } if returnType == .void { @@ -394,18 +402,17 @@ public class ExportSwift { return } - let returnAccessor = returnType.lowerAliases(expression: "ret") switch returnType { case .closure(_, useJSTypedClosure: false): append("return JSTypedClosure(ret).bridgeJSLowerReturn()") case .array, .nullable(.array, _): let stackCodegen = StackCodegen() - for stmt in stackCodegen.lowerStatements(for: returnType, accessor: returnAccessor, varPrefix: "ret") { + for stmt in stackCodegen.lowerStatements(for: returnType, accessor: "ret", varPrefix: "ret") { append(stmt) } case .dictionary(.swiftProtocol): let stackCodegen = StackCodegen() - for stmt in stackCodegen.lowerStatements(for: returnType, accessor: returnAccessor, varPrefix: "ret") { + for stmt in stackCodegen.lowerStatements(for: returnType, accessor: "ret", varPrefix: "ret") { append(stmt) } case .swiftProtocol: @@ -421,7 +428,7 @@ public class ExportSwift { """ ) default: - append("return \(raw: returnAccessor).bridgeJSLowerReturn()") + append("return ret.bridgeJSLowerReturn()") } } @@ -880,7 +887,7 @@ struct StackCodegen { case .string, .integer, .bool, .float, .double, .jsObject(nil), .jsValue, .swiftStruct, .swiftHeapObject, .unsafePointer, .swiftProtocol, .caseEnum, .associatedValueEnum, .rawValueEnum, .array, .dictionary, .alias: - return "\(raw: type.liftAliases(expression: "\(type.unaliased.swiftType).bridgeJSStackPop()"))" + return "\(raw: type.swiftType).bridgeJSStackPop()" case .jsObject(let className?): return "\(raw: className)(unsafelyWrapping: JSObject.bridgeJSStackPop())" case .nullable(let wrappedType, let kind): @@ -898,9 +905,7 @@ struct StackCodegen { case .string, .integer, .bool, .float, .double, .jsObject(nil), .jsValue, .swiftStruct, .swiftHeapObject, .caseEnum, .associatedValueEnum, .rawValueEnum, .array, .dictionary, .alias: - let popCall = "\(typeName)<\(wrappedType.unaliased.swiftType)>.bridgeJSStackPop()" - let nullableType = BridgeType.nullable(wrappedType, kind) - return "\(raw: nullableType.liftAliases(expression: popCall))" + return "\(raw: typeName)<\(raw: wrappedType.swiftType)>.bridgeJSStackPop()" case .jsObject(let className?): return "\(raw: typeName).bridgeJSStackPop().map { \(raw: className)(unsafelyWrapping: $0) }" case .nullable, .void, .namespaceEnum, .closure, .unsafePointer, .swiftProtocol: @@ -1208,10 +1213,9 @@ struct EnumCodegen { ) { for (index, associatedValue) in associatedValues.enumerated() { let paramName = associatedValue.label ?? "param\(index)" - let accessor = associatedValue.type.lowerAliases(expression: paramName) let statements = stackCodegen.lowerStatements( for: associatedValue.type, - accessor: accessor, + accessor: paramName, varPrefix: paramName ) for statement in statements { @@ -1344,10 +1348,9 @@ struct StructCodegen { let instanceProps = structDef.properties.filter { !$0.isStatic } for property in instanceProps { - let accessor = property.type.lowerAliases(expression: "self.\(property.name)") let statements = stackCodegen.lowerStatements( for: property.type, - accessor: accessor, + accessor: "self.\(property.name)", varPrefix: property.name ) for statement in statements { @@ -1359,6 +1362,18 @@ struct StructCodegen { } } +// MARK: - AliasCodegen + +struct AliasCodegen { + func renderAliasConformance(_ alias: ExportedAlias) -> DeclSyntax? { + guard let protocols = alias.underlying.aliasConformanceProtocols else { + return nil + } + let conformances = (["_BridgedSwiftAlias"] + protocols).joined(separator: ", ") + return "extension \(raw: alias.swiftCallName): \(raw: conformances) {}" + } +} + // MARK: - ProtocolCodegen struct ProtocolCodegen { @@ -1570,61 +1585,20 @@ extension UnsafePointerType { } extension BridgeType { - var unaliased: BridgeType { - switch self { - case .alias(_, let underlying): return underlying.unaliased - case .nullable(let wrapped, let kind): return .nullable(wrapped.unaliased, kind) - case .array(let element): return .array(element.unaliased) - case .dictionary(let value): return .dictionary(value.unaliased) - case .bool, .integer, .float, .double, .string, .jsValue, .jsObject, - .swiftHeapObject, .unsafePointer, .swiftProtocol, .void, - .caseEnum, .rawValueEnum, .associatedValueEnum, .swiftStruct, - .namespaceEnum, .closure: - return self - } - } - - /// If this type contains an alias, convert the expression with a type of the alias to the underlying type. - func liftAliases(expression: String) -> String { - switch self { - case .alias(let name, _): - return "\(name).bridgeFromJS(\(expression))" - case .nullable(let wrapped, _): - let lifted = wrapped.liftAliases(expression: "$0") - return lifted == "$0" ? expression : "\(expression).map { \(lifted) }" - case .array(let element): - let lifted = element.liftAliases(expression: "$0") - return lifted == "$0" ? expression : "\(expression).map { \(lifted) }" - case .dictionary(let value): - let lifted = value.liftAliases(expression: "$0") - return lifted == "$0" ? expression : "\(expression).mapValues { \(lifted) }" - case .bool, .integer, .float, .double, .string, .jsValue, .jsObject, - .swiftHeapObject, .unsafePointer, .swiftProtocol, .void, - .caseEnum, .rawValueEnum, .associatedValueEnum, .swiftStruct, - .namespaceEnum, .closure: - return expression - } - } - - /// Opposite of `liftAliases`: if this type contains an alias, convert the expression with a type of the underlying to the alias type. - func lowerAliases(expression: String) -> String { + var aliasConformanceProtocols: [String]? { switch self { - case .alias: - return "\(expression).bridgeToJS()" - case .nullable(let wrapped, _): - let lowered = wrapped.lowerAliases(expression: "$0") - return lowered == "$0" ? expression : "\(expression).map { \(lowered) }" - case .array(let element): - let lowered = element.lowerAliases(expression: "$0") - return lowered == "$0" ? expression : "\(expression).map { \(lowered) }" - case .dictionary(let value): - let lowered = value.lowerAliases(expression: "$0") - return lowered == "$0" ? expression : "\(expression).mapValues { \(lowered) }" - case .bool, .integer, .float, .double, .string, .jsValue, .jsObject, - .swiftHeapObject, .unsafePointer, .swiftProtocol, .void, - .caseEnum, .rawValueEnum, .associatedValueEnum, .swiftStruct, - .namespaceEnum, .closure: - return expression + case .swiftHeapObject, .jsObject, .integer, .float, .double, .bool, .string, .jsValue: + return ["_BridgedSwiftStackType"] + case .swiftStruct: + return ["_BridgedSwiftStruct"] + case .caseEnum: + return ["_BridgedSwiftCaseEnum"] + case .associatedValueEnum: + return ["_BridgedSwiftAssociatedValueEnum"] + case .rawValueEnum, .void, .unsafePointer, .namespaceEnum, + .swiftProtocol, .closure, .nullable, .array, .dictionary, .alias: + // Not supported yet. + return nil } } diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift index 9fd2af08e..c15d974f8 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift @@ -172,8 +172,7 @@ public struct ImportTS { if loweringInfo.useBorrowing { let returnVariableName = "ret\(borrowedArguments.count)" let assign = needsReturnVariable ? "let \(returnVariableName) = " : "" - let loweredAlias = param.type.lowerAliases(expression: param.name) - body.write("\(assign)\(loweredAlias).bridgeJSWithLoweredParameter { \(pattern) in") + body.write("\(assign)\(param.name).bridgeJSWithLoweredParameter { \(pattern) in") body.indent() borrowedArguments.append( BorrowedArgument( @@ -204,8 +203,7 @@ public struct ImportTS { "(\(raw: param.name) as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()" ) } else { - let loweredAlias = param.type.lowerAliases(expression: param.name) - initializerExpr = ExprSyntax("\(raw: loweredAlias).bridgeJSLowerParameter()") + initializerExpr = ExprSyntax("\(raw: param.name).bridgeJSLowerParameter()") } if loweringInfo.loweredParameters.isEmpty { @@ -296,21 +294,18 @@ public struct ImportTS { if returnType.usesSideChannelForOptionalReturn() { // Side channel returns: extern function returns Void, value is retrieved via side channel - let liftCall = "\(returnType.unaliased.swiftType).bridgeJSLiftReturnFromSideChannel()" - body.write("return \(returnType.liftAliases(expression: liftCall))") + body.write("return \(returnType.swiftType).bridgeJSLiftReturnFromSideChannel()") } else { let liftExpr: String switch returnType { case .closure(let signature, _): liftExpr = "_BJS_Closure_\(signature.mangleName).bridgeJSLift(ret)" default: - let liftCall: String if liftingInfo.valueToLift != nil { - liftCall = "\(returnType.unaliased.swiftType).bridgeJSLiftReturn(ret)" + liftExpr = "\(returnType.swiftType).bridgeJSLiftReturn(ret)" } else { - liftCall = "\(returnType.unaliased.swiftType).bridgeJSLiftReturn()" + liftExpr = "\(returnType.swiftType).bridgeJSLiftReturn()" } - liftExpr = returnType.liftAliases(expression: liftCall) } body.write("return \(liftExpr)") } @@ -908,7 +903,7 @@ extension BridgeType { } func loweringParameterInfo(context: BridgeContext = .importTS) throws -> LoweringParameterInfo { - switch self { + switch self.unaliased { case .bool: return .bool case .integer(let t): return LoweringParameterInfo(loweredParameters: [("value", t.wasmCoreType)]) case .float: return .float @@ -962,8 +957,8 @@ extension BridgeType { return LoweringParameterInfo(loweredParameters: params, useBorrowing: wrappedInfo.useBorrowing) case .array, .dictionary: return LoweringParameterInfo(loweredParameters: []) - case .alias(_, let underlying): - return try underlying.loweringParameterInfo(context: context) + case .alias: + preconditionFailure() } } @@ -983,7 +978,7 @@ extension BridgeType { func liftingReturnInfo( context: BridgeContext = .importTS ) throws -> LiftingReturnInfo { - switch self { + switch self.unaliased { case .bool: return .bool case .integer(let t): return LiftingReturnInfo(valueToLift: t.wasmCoreType) case .float: return .float @@ -1026,7 +1021,7 @@ extension BridgeType { case .nullable(let wrappedType, _): // jsObject and `@JS struct` use the stack ABI for optionals — the thunk returns // void and the value (plus isSome discriminator) flows through the stacks. - if case .jsObject = wrappedType.unaliased { + if case .jsObject = wrappedType { return LiftingReturnInfo(valueToLift: nil) } if case .swiftStruct = wrappedType, context == .importTS { @@ -1036,8 +1031,8 @@ extension BridgeType { return LiftingReturnInfo(valueToLift: wrappedInfo.valueToLift) case .array, .dictionary: return LiftingReturnInfo(valueToLift: nil) - case .alias(_, let underlying): - return try underlying.liftingReturnInfo(context: context) + case .alias: + preconditionFailure() } } } diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index 8b4e79d64..36ff44cbc 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -552,10 +552,7 @@ public final class SwiftToSkeleton { swiftCallName: String, errors: inout [DiagnosticError] ) -> BridgeType? { - if let targetDecl = typeDeclResolver.resolve(aliasTarget), - let targetJSAttribute = targetDecl.attributes.firstJSAttribute, - extractAliasTarget(from: targetJSAttribute) != nil - { + func diagnoseChainedAlias() -> BridgeType? { errors.append( DiagnosticError( node: aliasTarget, @@ -565,7 +562,17 @@ public final class SwiftToSkeleton { ) return nil } + if let targetDecl = typeDeclResolver.resolve(aliasTarget), + let targetJSAttribute = targetDecl.attributes.firstJSAttribute, + extractAliasTarget(from: targetJSAttribute) != nil + { + return diagnoseChainedAlias() + } guard let targetType = lookupType(for: aliasTarget, errors: &errors) else { return nil } + if case .alias = targetType { + // Alias declared in another module. + return diagnoseChainedAlias() + } if case .swiftProtocol = targetType { errors.append( DiagnosticError( @@ -1747,6 +1754,15 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { errors.append(contentsOf: lookupErrors) return } + guard underlying.aliasConformanceProtocols != nil else { + errors.append( + DiagnosticError( + node: aliasTarget, + message: "Representation \(underlying.swiftType) is not supported" + ) + ) + return + } exportedAliases.append( ExportedAlias(swiftCallName: swiftCallName, underlying: underlying) ) diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift index c6ac936cd..a94c780ed 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift @@ -651,9 +651,6 @@ struct IntrinsicJSFragment: Sendable { kind: JSOptionalKind, context bridgeContext: BridgeContext = .importTS ) throws -> IntrinsicJSFragment { - if case .alias(_, let underlying) = wrappedType { - return try optionalLiftParameter(wrappedType: underlying, kind: kind, context: bridgeContext) - } if wrappedType.isSingleParamScalar { let coerce = wrappedType.liftCoerce return IntrinsicJSFragment( @@ -742,9 +739,6 @@ struct IntrinsicJSFragment: Sendable { wrappedType: BridgeType, kind: JSOptionalKind ) throws -> IntrinsicJSFragment { - if case .alias(_, let underlying) = wrappedType { - return try optionalLowerParameter(wrappedType: underlying, kind: kind) - } if wrappedType.isSingleParamScalar { let wasmType = wrappedType.wasmParams[0].type let coerce = wrappedType.lowerCoerce @@ -973,9 +967,6 @@ struct IntrinsicJSFragment: Sendable { wrappedType: BridgeType, kind: JSOptionalKind ) -> IntrinsicJSFragment { - if case .alias(_, let underlying) = wrappedType { - return optionalLiftReturn(wrappedType: underlying, kind: kind) - } if let scalarKind = wrappedType.optionalScalarKind { return optionalLiftReturnFromStorage(storage: scalarKind.storageName) } @@ -1073,9 +1064,6 @@ struct IntrinsicJSFragment: Sendable { } static func optionalLowerReturn(wrappedType: BridgeType, kind: JSOptionalKind) throws -> IntrinsicJSFragment { - if case .alias(_, let underlying) = wrappedType { - return try optionalLowerReturn(wrappedType: underlying, kind: kind) - } switch wrappedType { case .void, .nullable, .namespaceEnum, .closure: throw BridgeJSLinkError(message: "Unsupported optional wrapped type for protocol export: \(wrappedType)") @@ -1200,9 +1188,7 @@ struct IntrinsicJSFragment: Sendable { // MARK: - Protocol Support static func protocolPropertyOptionalToSideChannel(wrappedType: BridgeType) throws -> IntrinsicJSFragment { - if case .alias(_, let underlying) = wrappedType { - return try protocolPropertyOptionalToSideChannel(wrappedType: underlying) - } + let wrappedType = wrappedType.unaliased if let scalarKind = wrappedType.optionalScalarKind { let storage = scalarKind.storageName return IntrinsicJSFragment( @@ -1299,7 +1285,7 @@ struct IntrinsicJSFragment: Sendable { /// Returns a fragment that lowers a JS value to Wasm core values for parameters static func lowerParameter(type: BridgeType) throws -> IntrinsicJSFragment { - switch type { + switch type.unaliased { case .bool, .integer, .float, .double, .unsafePointer, .caseEnum: return .identity case .rawValueEnum(_, let rawType) where rawType != .string: @@ -1338,8 +1324,6 @@ struct IntrinsicJSFragment: Sendable { return try arrayLower(elementType: elementType) case .dictionary(let valueType): return try dictionaryLower(valueType: valueType) - case .alias(_, let underlying): - return try lowerParameter(type: underlying) default: throw BridgeJSLinkError(message: "Unhandled type in lowerParameter: \(type)") } @@ -1347,7 +1331,7 @@ struct IntrinsicJSFragment: Sendable { /// Returns a fragment that lifts a Wasm core value to a JS value for return values static func liftReturn(type: BridgeType) throws -> IntrinsicJSFragment { - switch type { + switch type.unaliased { case .bool, .rawValueEnum(_, .bool): return .boolLiftReturn case .integer(let t) where !t.is64Bit && !t.isSigned: @@ -1397,8 +1381,6 @@ struct IntrinsicJSFragment: Sendable { return try arrayLift(elementType: elementType) case .dictionary(let valueType): return try dictionaryLift(valueType: valueType) - case .alias(_, let underlying): - return try liftReturn(type: underlying) default: throw BridgeJSLinkError(message: "Unhandled type in liftReturn: \(type)") } @@ -1408,7 +1390,7 @@ struct IntrinsicJSFragment: Sendable { /// Returns a fragment that lifts Wasm core values to JS values for parameters static func liftParameter(type: BridgeType, context: BridgeContext = .importTS) throws -> IntrinsicJSFragment { - switch type { + switch type.unaliased { case .bool, .rawValueEnum(_, .bool): return .boolLiftParameter case .integer(let t) where !t.is64Bit && !t.isSigned: @@ -1489,8 +1471,6 @@ struct IntrinsicJSFragment: Sendable { return try arrayLift(elementType: elementType) case .dictionary(let valueType): return try dictionaryLift(valueType: valueType) - case .alias(_, let underlying): - return try liftParameter(type: underlying, context: context) default: throw BridgeJSLinkError(message: "Unhandled type in liftParameter: \(type)") } @@ -1498,7 +1478,7 @@ struct IntrinsicJSFragment: Sendable { /// Returns a fragment that lowers a JS value to Wasm core values for return values static func lowerReturn(type: BridgeType, context: BridgeContext = .importTS) throws -> IntrinsicJSFragment { - switch type { + switch type.unaliased { case .bool, .rawValueEnum(_, .bool): return .boolLowerReturn case .integer, .float, .double, .unsafePointer, .caseEnum: @@ -1545,8 +1525,6 @@ struct IntrinsicJSFragment: Sendable { return try arrayLower(elementType: elementType) case .dictionary(let valueType): return try dictionaryLower(valueType: valueType) - case .alias(_, let underlying): - return try lowerReturn(type: underlying, context: context) default: throw BridgeJSLinkError(message: "Unhandled type in lowerReturn: \(type)") } @@ -1782,6 +1760,7 @@ struct IntrinsicJSFragment: Sendable { } private static func associatedValuePushPayload(type: BridgeType) throws -> IntrinsicJSFragment { + let type = type.unaliased switch type { case .nullable(let wrappedType, let kind): return try optionalElementLowerFragment(wrappedType: wrappedType, kind: kind) @@ -1791,6 +1770,7 @@ struct IntrinsicJSFragment: Sendable { } private static func associatedValuePopPayload(type: BridgeType) throws -> IntrinsicJSFragment { + let type = type.unaliased switch type { case .nullable(let wrappedType, let kind): return try optionalElementRaiseFragment(wrappedType: wrappedType, kind: kind) @@ -1964,9 +1944,6 @@ struct IntrinsicJSFragment: Sendable { } private static func stackLiftFragment(elementType: BridgeType) throws -> IntrinsicJSFragment { - if case .alias(_, let underlying) = elementType { - return try stackLiftFragment(elementType: underlying) - } if case .nullable(let wrappedType, let kind) = elementType { return try optionalElementRaiseFragment(wrappedType: wrappedType, kind: kind) } @@ -2094,9 +2071,6 @@ struct IntrinsicJSFragment: Sendable { } private static func stackLowerFragment(elementType: BridgeType) throws -> IntrinsicJSFragment { - if case .alias(_, let underlying) = elementType { - return try stackLowerFragment(elementType: underlying) - } if case .nullable(let wrappedType, let kind) = elementType { return try optionalElementLowerFragment(wrappedType: wrappedType, kind: kind) } @@ -2221,9 +2195,6 @@ struct IntrinsicJSFragment: Sendable { wrappedType: BridgeType, kind: JSOptionalKind ) throws -> IntrinsicJSFragment { - if case .alias(_, let underlying) = wrappedType { - return try optionalElementRaiseFragment(wrappedType: underlying, kind: kind) - } if case .associatedValueEnum(let fullName) = wrappedType { let base = fullName.components(separatedBy: ".").last ?? fullName let absenceLiteral = kind.absenceLiteral @@ -2290,9 +2261,6 @@ struct IntrinsicJSFragment: Sendable { wrappedType: BridgeType, kind: JSOptionalKind ) throws -> IntrinsicJSFragment { - if case .alias(_, let underlying) = wrappedType { - return try optionalElementLowerFragment(wrappedType: underlying, kind: kind) - } if case .associatedValueEnum(let fullName) = wrappedType { let base = fullName.components(separatedBy: ".").last ?? fullName return IntrinsicJSFragment( @@ -2499,6 +2467,7 @@ struct IntrinsicJSFragment: Sendable { fieldName: String, allStructs: [ExportedStruct] ) throws -> IntrinsicJSFragment { + let type = type.unaliased switch type { case .jsValue: preconditionFailure("Struct field of JSValue is not supported yet") @@ -2560,7 +2529,8 @@ struct IntrinsicJSFragment: Sendable { field: ExportedProperty, allStructs: [ExportedStruct] ) throws -> IntrinsicJSFragment { - switch field.type { + let fieldType = field.type.unaliased + switch fieldType { case .jsValue: preconditionFailure("Struct field of JSValue is not supported yet") case .nullable(let wrappedType, let kind): @@ -2611,7 +2581,7 @@ struct IntrinsicJSFragment: Sendable { } ) default: - return try stackLiftFragment(elementType: field.type) + return try stackLiftFragment(elementType: fieldType) } } } @@ -2715,8 +2685,8 @@ private extension BridgeType { return .stackABI case .nullable(let wrapped, _): return wrapped.optionalConvention - case .alias(_, let underlying): - return underlying.optionalConvention + case .alias: + preconditionFailure() } } @@ -2748,8 +2718,6 @@ private extension BridgeType { return .i32(-1) case .nullable(let wrapped, _): return wrapped.nilSentinel - case .alias(_, let underlying): - return underlying.nilSentinel default: return .none } @@ -2815,8 +2783,8 @@ private extension BridgeType { return [] case .nullable(let wrapped, _): return wrapped.wasmParams - case .alias(_, let underlying): - return underlying.wasmParams + case .alias: + preconditionFailure() } } diff --git a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift index 4d1ebbbc1..d2c506e6a 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift @@ -1008,7 +1008,7 @@ public struct ExportedProperty: Codable, Equatable, Sendable { } } -public struct ExportedAlias: Codable { +public struct ExportedAlias: Codable, Equatable, Sendable { public let swiftCallName: String public let underlying: BridgeType @@ -1626,6 +1626,20 @@ extension BridgeType { } } + public var unaliased: BridgeType { + switch self { + case .alias(_, let underlying): return underlying.unaliased + case .nullable(let wrapped, let kind): return .nullable(wrapped.unaliased, kind) + case .array(let element): return .array(element.unaliased) + case .dictionary(let value): return .dictionary(value.unaliased) + case .bool, .integer, .float, .double, .string, .jsValue, .jsObject, + .swiftHeapObject, .unsafePointer, .swiftProtocol, .void, + .caseEnum, .rawValueEnum, .associatedValueEnum, .swiftStruct, + .namespaceEnum, .closure: + return self + } + } + public var abiReturnType: WasmCoreType? { switch self { case .void: return nil diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/CrossModuleResolutionTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/CrossModuleResolutionTests.swift index 4f12a88fa..3f0ee88db 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/CrossModuleResolutionTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/CrossModuleResolutionTests.swift @@ -457,6 +457,36 @@ import Testing } } + @Test + func crossModuleChainedJSAsDiagnostic() throws { + let core = try buildDependencySkeleton( + moduleName: "Core", + source: """ + @JS(as: Box.self) public struct Wrapped { + public consuming func bridgeToJS() -> Box { fatalError() } + public static func bridgeFromJS(_ value: consuming Box) -> Wrapped { fatalError() } + } + @JS public final class Box { @JS public init() {} } + """ + ) + do { + _ = try resolveApp( + source: """ + import Core + @JS(as: Wrapped.self) public struct Doubly { + public consuming func bridgeToJS() -> Wrapped { fatalError() } + public static func bridgeFromJS(_ value: consuming Wrapped) -> Doubly { fatalError() } + } + """, + dependencies: [(moduleName: "Core", skeleton: core)] + ) + Issue.record("Expected chained-alias diagnostic for cross-module `@JS(as:)` target") + } catch let error as BridgeJSCoreDiagnosticError { + let combinedMessages = error.diagnostics.map(\.diagnostic.message).joined(separator: "\n") + #expect(combinedMessages.contains("not another `@JS(as:)` type")) + } + } + // MARK: - Utillites private func resolveApp( diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.swift index 1a31905f3..a9252e57f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.swift @@ -5,7 +5,7 @@ struct AnyHasOptionalUserId: HasOptionalUserId, _BridgedSwiftProtocolWrapper { get { let jsObjectValue = jsObject.bridgeJSLowerParameter() bjs_HasOptionalUserId_userId_get(jsObjectValue) - return Optional.bridgeJSLiftReturnFromSideChannel().map { UserId.bridgeFromJS($0) } + return Optional.bridgeJSLiftReturnFromSideChannel() } } @@ -53,8 +53,8 @@ extension InnerTag: _BridgedSwiftAssociatedValueEnum { @_cdecl("bjs_roundtripPolygon") public func _bjs_roundtripPolygon(_ polygon: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = roundtripPolygon(_: Polygon.bridgeFromJS(PolygonReference.bridgeJSLiftParameter(polygon))) - return ret.bridgeToJS().bridgeJSLowerReturn() + let ret = roundtripPolygon(_: Polygon.bridgeJSLiftParameter(polygon)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -64,8 +64,8 @@ public func _bjs_roundtripPolygon(_ polygon: UnsafeMutableRawPointer) -> UnsafeM @_cdecl("bjs_optionalPolygon") public func _bjs_optionalPolygon(_ polygonIsSome: Int32, _ polygonValue: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = optionalPolygon(_: Optional.bridgeJSLiftParameter(polygonIsSome, polygonValue).map { Polygon.bridgeFromJS($0) }) - return ret.map { $0.bridgeToJS() }.bridgeJSLowerReturn() + let ret = optionalPolygon(_: Optional.bridgeJSLiftParameter(polygonIsSome, polygonValue)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -75,8 +75,8 @@ public func _bjs_optionalPolygon(_ polygonIsSome: Int32, _ polygonValue: UnsafeM @_cdecl("bjs_polygonArray") public func _bjs_polygonArray() -> Void { #if arch(wasm32) - let ret = polygonArray(_: [PolygonReference].bridgeJSStackPop().map { Polygon.bridgeFromJS($0) }) - ret.map { $0.bridgeToJS() }.bridgeJSStackPush() + let ret = polygonArray(_: [Polygon].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -87,15 +87,15 @@ public func _bjs_polygonArray() -> Void { public func _bjs_validatePolygon(_ polygon: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) do { - let ret = try validatePolygon(_: Polygon.bridgeFromJS(PolygonReference.bridgeJSLiftParameter(polygon))) - return ret.bridgeToJS().bridgeJSLowerReturn() + let ret = try validatePolygon(_: Polygon.bridgeJSLiftParameter(polygon)) + return ret.bridgeJSLowerReturn() } catch let error { if let error = error.thrownValue.object { withExtendedLifetime(error) { _swift_js_throw(Int32(bitPattern: $0.id)) } } else { - let jsError = JSError(message: String(describing: error)) + let jsError = JSError(message: error.description) withExtendedLifetime(jsError.jsObject) { _swift_js_throw(Int32(bitPattern: $0.id)) } @@ -112,7 +112,7 @@ public func _bjs_validatePolygon(_ polygon: UnsafeMutableRawPointer) -> UnsafeMu public func _bjs_makeTag(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) let ret = makeTag(_: String.bridgeJSLiftParameter(nameBytes, nameLength)) - return ret.bridgeToJS().bridgeJSLowerReturn() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -122,8 +122,8 @@ public func _bjs_makeTag(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutab @_cdecl("bjs_roundtripTags") public func _bjs_roundtripTags() -> Void { #if arch(wasm32) - let ret = roundtripTags(_: [Optional].bridgeJSStackPop().map { $0.map { AliasedTag.bridgeFromJS($0) } }) - ret.map { $0.map { $0.bridgeToJS() } }.bridgeJSStackPush() + let ret = roundtripTags(_: [Optional].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif @@ -144,7 +144,7 @@ public func _bjs_describeUser(_ owner: Int32) -> Int32 { @_cdecl("bjs_PolygonReference_init") public func _bjs_PolygonReference_init(_ underlying: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = PolygonReference(underlying: Polygon.bridgeFromJS(PolygonReference.bridgeJSLiftParameter(underlying))) + let ret = PolygonReference(underlying: Polygon.bridgeJSLiftParameter(underlying)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -156,7 +156,7 @@ public func _bjs_PolygonReference_init(_ underlying: UnsafeMutableRawPointer) -> public func _bjs_PolygonReference_snapshot(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) let ret = PolygonReference.bridgeJSLiftParameter(_self).snapshot() - return ret.bridgeToJS().bridgeJSLowerReturn() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -166,8 +166,8 @@ public func _bjs_PolygonReference_snapshot(_ _self: UnsafeMutableRawPointer) -> @_cdecl("bjs_PolygonReference_merge") public func _bjs_PolygonReference_merge(_ _self: UnsafeMutableRawPointer, _ other: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = PolygonReference.bridgeJSLiftParameter(_self).merge(_: Polygon.bridgeFromJS(PolygonReference.bridgeJSLiftParameter(other))) - return ret.bridgeToJS().bridgeJSLowerReturn() + let ret = PolygonReference.bridgeJSLiftParameter(_self).merge(_: Polygon.bridgeJSLiftParameter(other)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -178,7 +178,7 @@ public func _bjs_PolygonReference_merge(_ _self: UnsafeMutableRawPointer, _ othe public func _bjs_PolygonReference_static_origin() -> UnsafeMutableRawPointer { #if arch(wasm32) let ret = PolygonReference.origin() - return ret.bridgeToJS().bridgeJSLowerReturn() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -219,7 +219,7 @@ fileprivate func _bjs_PolygonReference_wrap_extern(_ pointer: UnsafeMutableRawPo @_cdecl("bjs_TagReference_init") public func _bjs_TagReference_init(_ underlying: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = TagReference(underlying: Tag.bridgeFromJS(TagReference.bridgeJSLiftParameter(underlying))) + let ret = TagReference(underlying: Tag.bridgeJSLiftParameter(underlying)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -257,6 +257,18 @@ fileprivate func _bjs_TagReference_wrap_extern(_ pointer: UnsafeMutableRawPointe return _bjs_TagReference_wrap_extern(pointer) } +extension Polygon: _BridgedSwiftAlias, _BridgedSwiftStackType {} + +extension Tag: _BridgedSwiftAlias, _BridgedSwiftStackType {} + +extension Tagged: _BridgedSwiftAlias, _BridgedSwiftStackType {} + +extension Canvas: _BridgedSwiftAlias, _BridgedSwiftStackType {} + +extension AliasedTag: _BridgedSwiftAlias, _BridgedSwiftAssociatedValueEnum {} + +extension UserId: _BridgedSwiftAlias, _BridgedSwiftStackType {} + #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_acceptTagged") fileprivate func bjs_acceptTagged_extern(_ taggedBytes: Int32, _ taggedLength: Int32) -> Void @@ -270,7 +282,7 @@ fileprivate func bjs_acceptTagged_extern(_ taggedBytes: Int32, _ taggedLength: I } func _$acceptTagged(_ tagged: Tagged) throws(JSException) -> Void { - tagged.bridgeToJS().bridgeJSWithLoweredParameter { (taggedBytes, taggedLength) in + tagged.bridgeJSWithLoweredParameter { (taggedBytes, taggedLength) in bjs_acceptTagged(taggedBytes, taggedLength) } if let error = _swift_js_take_exception() { @@ -291,9 +303,7 @@ fileprivate func bjs_acceptOptionalTagged_extern(_ taggedIsSome: Int32, _ tagged } func _$acceptOptionalTagged(_ tagged: Optional) throws(JSException) -> Void { - tagged.map { - $0.bridgeToJS() - } .bridgeJSWithLoweredParameter { (taggedIsSome, taggedBytes, taggedLength) in + tagged.bridgeJSWithLoweredParameter { (taggedIsSome, taggedBytes, taggedLength) in bjs_acceptOptionalTagged(taggedIsSome, taggedBytes, taggedLength) } if let error = _swift_js_take_exception() { @@ -314,7 +324,7 @@ fileprivate func bjs_roundtripTagged_extern(_ taggedBytes: Int32, _ taggedLength } func _$roundtripTagged(_ tagged: Tagged) throws(JSException) -> Tagged { - let ret0 = tagged.bridgeToJS().bridgeJSWithLoweredParameter { (taggedBytes, taggedLength) in + let ret0 = tagged.bridgeJSWithLoweredParameter { (taggedBytes, taggedLength) in let ret = bjs_roundtripTagged(taggedBytes, taggedLength) return ret } @@ -322,7 +332,7 @@ func _$roundtripTagged(_ tagged: Tagged) throws(JSException) -> Tagged { if let error = _swift_js_take_exception() { throw error } - return Tagged.bridgeFromJS(String.bridgeJSLiftReturn(ret)) + return Tagged.bridgeJSLiftReturn(ret) } #if arch(wasm32) @@ -342,9 +352,7 @@ func _$produceOptionalCanvas() throws(JSException) -> Optional { if let error = _swift_js_take_exception() { throw error } - return Optional.bridgeJSLiftReturn().map { - Canvas.bridgeFromJS($0) - } + return Optional.bridgeJSLiftReturn() } #if arch(wasm32) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.swift index 3613ead7e..38cc900ae 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.swift @@ -28,7 +28,7 @@ private enum _BJS_Closure_10TestModuleAl7Polygon_Si { return { [callback] param0 in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() - let param0Pointer = param0.bridgeToJS().bridgeJSLowerParameter() + let param0Pointer = param0.bridgeJSLowerParameter() let ret = invoke_js_callback_TestModule_10TestModuleAl7Polygon_Si(callbackValue, param0Pointer) return Int.bridgeJSLiftReturn(ret) #else @@ -54,7 +54,7 @@ extension JSTypedClosure where Signature == (Polygon) -> Int { public func _invoke_swift_closure_TestModule_10TestModuleAl7Polygon_Si(_ boxPtr: UnsafeMutableRawPointer, _ param0: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Polygon) -> Int>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Polygon.bridgeFromJS(PolygonReference.bridgeJSLiftParameter(param0))) + let result = closure(Polygon.bridgeJSLiftParameter(param0)) return result.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") @@ -92,7 +92,7 @@ private enum _BJS_Closure_10TestModuley_Al7Polygon { #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_TestModule_10TestModuley_Al7Polygon(callbackValue) - return Polygon.bridgeFromJS(PolygonReference.bridgeJSLiftReturn(ret)) + return Polygon.bridgeJSLiftReturn(ret) #else fatalError("Only available on WebAssembly") #endif @@ -117,7 +117,7 @@ public func _invoke_swift_closure_TestModule_10TestModuley_Al7Polygon(_ boxPtr: #if arch(wasm32) let closure = Unmanaged<_BridgeJSTypedClosureBox<() -> Polygon>>.fromOpaque(boxPtr).takeUnretainedValue().closure let result = closure() - return result.bridgeToJS().bridgeJSLowerReturn() + return result.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -185,4 +185,6 @@ fileprivate func _bjs_PolygonReference_wrap_extern(_ pointer: UnsafeMutableRawPo #endif @inline(never) fileprivate func _bjs_PolygonReference_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { return _bjs_PolygonReference_wrap_extern(pointer) -} \ No newline at end of file +} + +extension Polygon: _BridgedSwiftAlias, _BridgedSwiftStackType {} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncAssociatedValueEnum.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncAssociatedValueEnum.json index 6b0d70453..b69bf4012 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncAssociatedValueEnum.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncAssociatedValueEnum.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ ], diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAlias.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAlias.swift index 615110c90..1e74a127b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAlias.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAlias.swift @@ -2,8 +2,8 @@ @_cdecl("bjs_roundtripColor") public func _bjs_roundtripColor(_ color: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = roundtripColor(_: Color.bridgeFromJS(ColorBox.bridgeJSLiftParameter(color))) - return ret.bridgeToJS().bridgeJSLowerReturn() + let ret = roundtripColor(_: Color.bridgeJSLiftParameter(color)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif @@ -49,4 +49,6 @@ fileprivate func _bjs_ColorBox_wrap_extern(_ pointer: UnsafeMutableRawPointer) - #endif @inline(never) fileprivate func _bjs_ColorBox_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { return _bjs_ColorBox_wrap_extern(pointer) -} \ No newline at end of file +} + +extension Color: _BridgedSwiftAlias, _BridgedSwiftStackType {} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValueImport.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValueImport.json index 23cb1b0f0..6ba934220 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValueImport.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValueImport.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ ], diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCaseImport.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCaseImport.json index 71bf8679e..f0d534425 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCaseImport.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCaseImport.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ ], diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.json index d1cda5c7d..0d93a993f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ ], diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js index c55e429d5..a24c0754b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js @@ -139,6 +139,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js index 21c96aed6..dc6e6ccd3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js @@ -131,6 +131,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js index 01f0472ab..2a2e89f8c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js @@ -106,6 +106,13 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } bjs["swift_js_return_optional_bool"] = function(isSome, value) { if (isSome === 0) { tmpRetOptionalBool = null; diff --git a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift index bbf8c8f2e..1fbdff0b8 100644 --- a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift +++ b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift @@ -217,6 +217,294 @@ extension Optional: _BridgedAsOptional { public init(optional: Wrapped?) { self = optional } } +// MARK: - _BridgedSwiftAlias + +/// Types that are bridged using a separate JavaScript representation (`@JS(as:)`). +public protocol _BridgedSwiftAlias { + associatedtype JSRepresentation + consuming func bridgeToJS() -> JSRepresentation + static func bridgeFromJS(_ value: consuming JSRepresentation) -> Self +} + +extension _BridgedSwiftAlias where JSRepresentation: _BridgedSwiftHeapObject { + // MARK: ImportTS + @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> UnsafeMutableRawPointer { + bridgeToJS().bridgeJSLowerParameter() + } + @_spi(BridgeJS) public static func bridgeJSLiftReturn(_ pointer: UnsafeMutableRawPointer) -> Self { + bridgeFromJS(JSRepresentation.bridgeJSLiftReturn(pointer)) + } + // MARK: ExportSwift + @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ pointer: UnsafeMutableRawPointer) -> Self { + bridgeFromJS(JSRepresentation.bridgeJSLiftParameter(pointer)) + } + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> UnsafeMutableRawPointer { + bridgeToJS().bridgeJSLowerReturn() + } + // MARK: Stack ABI + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { + bridgeFromJS(JSRepresentation.bridgeJSStackPop()) + } + @_spi(BridgeJS) public consuming func bridgeJSStackPush() { + bridgeToJS().bridgeJSStackPush() + } +} + +extension _BridgedAsOptional where Wrapped: _BridgedSwiftAlias, Wrapped.JSRepresentation: _BridgedSwiftHeapObject { + @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> ( + isSome: Int32, pointer: UnsafeMutableRawPointer + ) { + asOptional.map { $0.bridgeToJS() }.bridgeJSLowerParameter() + } + + @_spi(BridgeJS) public static func bridgeJSLiftReturn(_ pointer: UnsafeMutableRawPointer) -> Self { + Self(optional: Optional.bridgeJSLiftReturn(pointer).map { Wrapped.bridgeFromJS($0) }) + } + + @_spi(BridgeJS) public static func bridgeJSLiftParameter( + _ isSome: Int32, + _ pointer: UnsafeMutableRawPointer + ) -> Self { + Self( + optional: Optional.bridgeJSLiftParameter(isSome, pointer) + .map { Wrapped.bridgeFromJS($0) } + ) + } + + @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Self { + Self( + optional: Optional.bridgeJSLiftReturnFromSideChannel() + .map { Wrapped.bridgeFromJS($0) } + ) + } + + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { + asOptional.map { $0.bridgeToJS() }.bridgeJSLowerReturn() + } +} + +extension _BridgedSwiftAlias where JSRepresentation: _JSBridgedClass { + // MARK: ImportTS + @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> Int32 { + bridgeToJS().bridgeJSLowerParameter() + } + @_spi(BridgeJS) public static func bridgeJSLiftReturn(_ id: Int32) -> Self { + bridgeFromJS(JSRepresentation.bridgeJSLiftReturn(id)) + } + // MARK: ExportSwift + @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ id: Int32) -> Self { + bridgeFromJS(JSRepresentation.bridgeJSLiftParameter(id)) + } + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Int32 { + bridgeToJS().bridgeJSLowerReturn() + } + // MARK: Stack ABI + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { + bridgeFromJS(JSRepresentation.bridgeJSStackPop()) + } + @_spi(BridgeJS) public consuming func bridgeJSStackPush() { + bridgeToJS().bridgeJSStackPush() + } +} + +extension _BridgedSwiftAlias where JSRepresentation: _BridgedSwiftTypeLoweredIntoSingleWasmCoreType { + // MARK: ImportTS + @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> JSRepresentation.WasmCoreType { + bridgeToJS().bridgeJSLowerParameter() + } + @_spi(BridgeJS) public static func bridgeJSLiftReturn(_ value: JSRepresentation.WasmCoreType) -> Self { + bridgeFromJS(JSRepresentation.bridgeJSLiftReturn(value)) + } + // MARK: ExportSwift + @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ value: JSRepresentation.WasmCoreType) -> Self { + bridgeFromJS(JSRepresentation.bridgeJSLiftParameter(value)) + } + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> JSRepresentation.WasmCoreType { + bridgeToJS().bridgeJSLowerReturn() + } +} + +extension _BridgedSwiftAlias +where + JSRepresentation: _BridgedSwiftTypeLoweredIntoSingleWasmCoreType, JSRepresentation: _BridgedSwiftStackType, + JSRepresentation.StackLiftResult == JSRepresentation +{ + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { + bridgeFromJS(JSRepresentation.bridgeJSStackPop()) + } + @_spi(BridgeJS) public consuming func bridgeJSStackPush() { + bridgeToJS().bridgeJSStackPush() + } +} + +extension _BridgedAsOptional +where Wrapped: _BridgedSwiftAlias, Wrapped.JSRepresentation: _BridgedSwiftOptionalScalarBridge { + @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> ( + isSome: Int32, value: Wrapped.JSRepresentation.WasmCoreType + ) { + asOptional.map { $0.bridgeToJS() }.bridgeJSLowerParameter() + } + @_spi(BridgeJS) public static func bridgeJSLiftParameter( + _ isSome: Int32, + _ value: Wrapped.JSRepresentation.WasmCoreType + ) -> Self { + Self( + optional: Optional.bridgeJSLiftParameter(isSome, value) + .map { Wrapped.bridgeFromJS($0) } + ) + } + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { + asOptional.map { $0.bridgeToJS() }.bridgeJSLowerReturn() + } +} + +extension _BridgedAsOptional +where Wrapped: _BridgedSwiftAlias, Wrapped.JSRepresentation: _BridgedSwiftOptionalScalarSideChannelBridge { + @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Self { + Self( + optional: Optional.bridgeJSLiftReturnFromSideChannel() + .map { Wrapped.bridgeFromJS($0) } + ) + } +} + +extension _BridgedSwiftAlias where JSRepresentation: _BridgedSwiftStruct { + // MARK: ExportSwift + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { + bridgeFromJS(JSRepresentation.bridgeJSStackPop()) + } + @_spi(BridgeJS) public consuming func bridgeJSStackPush() { + bridgeToJS().bridgeJSStackPush() + } + + public init(unsafelyCopying jsObject: JSObject) { + self = Self.bridgeFromJS(JSRepresentation(unsafelyCopying: jsObject)) + } + public func toJSObject() -> JSObject { + return self.bridgeToJS().toJSObject() + } +} + +extension _BridgedSwiftAlias where JSRepresentation: _BridgedSwiftCaseEnum { + // MARK: ImportTS + @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> Int32 { + bridgeToJS().bridgeJSLowerParameter() + } + @_spi(BridgeJS) public static func bridgeJSLiftReturn(_ value: Int32) -> Self { + bridgeFromJS(JSRepresentation.bridgeJSLiftReturn(value)) + } + // MARK: ExportSwift + @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ value: Int32) -> Self { + bridgeFromJS(JSRepresentation.bridgeJSLiftParameter(value)) + } + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Int32 { + bridgeToJS().bridgeJSLowerReturn() + } +} + +extension _BridgedSwiftAlias where JSRepresentation: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) public static func bridgeJSStackPopPayload(_ caseId: Int32) -> Self { + bridgeFromJS(JSRepresentation.bridgeJSStackPopPayload(caseId)) + } + @_spi(BridgeJS) public consuming func bridgeJSStackPushPayload() -> Int32 { + bridgeToJS().bridgeJSStackPushPayload() + } +} + +extension _BridgedSwiftAlias where JSRepresentation == String { + // MARK: ImportTS + @_spi(BridgeJS) public consuming func bridgeJSWithLoweredParameter(_ body: (Int32, Int32) -> T) -> T { + bridgeToJS().bridgeJSWithLoweredParameter(body) + } + @_spi(BridgeJS) public static func bridgeJSLiftReturn(_ bytesCount: Int32) -> Self { + bridgeFromJS(String.bridgeJSLiftReturn(bytesCount)) + } + // MARK: ExportSwift + @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ bytes: Int32, _ count: Int32) -> Self { + bridgeFromJS(String.bridgeJSLiftParameter(bytes, count)) + } + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { + bridgeToJS().bridgeJSLowerReturn() + } + // MARK: Stack ABI + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { + bridgeFromJS(String.bridgeJSStackPop()) + } + @_spi(BridgeJS) public consuming func bridgeJSStackPush() { + bridgeToJS().bridgeJSStackPush() + } +} + +extension _BridgedAsOptional where Wrapped: _BridgedSwiftAlias, Wrapped.JSRepresentation == String { + @_spi(BridgeJS) public consuming func bridgeJSWithLoweredParameter( + _ body: (Int32, Int32, Int32) -> T + ) -> T { + asOptional.map { $0.bridgeToJS() }.bridgeJSWithLoweredParameter(body) + } + @_spi(BridgeJS) public static func bridgeJSLiftParameter( + _ isSome: Int32, + _ bytes: Int32, + _ count: Int32 + ) -> Self { + Self(optional: Optional.bridgeJSLiftParameter(isSome, bytes, count).map { Wrapped.bridgeFromJS($0) }) + } + @_spi(BridgeJS) public static func bridgeJSLiftReturnFromSideChannel() -> Self { + Self(optional: Optional.bridgeJSLiftReturnFromSideChannel().map { Wrapped.bridgeFromJS($0) }) + } + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { + asOptional.map { $0.bridgeToJS() }.bridgeJSLowerReturn() + } +} + +extension _BridgedSwiftAlias where JSRepresentation == JSValue { + // MARK: ImportTS + @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> (kind: Int32, payload1: Int32, payload2: Double) { + bridgeToJS().bridgeJSLowerParameter() + } + @_spi(BridgeJS) public static func bridgeJSLiftReturn() -> Self { + bridgeFromJS(JSValue.bridgeJSLiftReturn()) + } + // MARK: ExportSwift + @_spi(BridgeJS) public static func bridgeJSLiftParameter( + _ kind: Int32, + _ payload1: Int32, + _ payload2: Double + ) -> Self { + bridgeFromJS(JSValue.bridgeJSLiftParameter(kind, payload1, payload2)) + } + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { + bridgeToJS().bridgeJSLowerReturn() + } + @_spi(BridgeJS) public static func bridgeJSStackPop() -> Self { + bridgeFromJS(JSValue.bridgeJSStackPop()) + } + @_spi(BridgeJS) public consuming func bridgeJSStackPush() { + bridgeToJS().bridgeJSStackPush() + } +} + +extension _BridgedAsOptional where Wrapped: _BridgedSwiftAlias, Wrapped.JSRepresentation == JSValue { + @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> ( + isSome: Int32, kind: Int32, payload1: Int32, payload2: Double + ) { + asOptional.map { $0.bridgeToJS() }.bridgeJSLowerParameter() + } + @_spi(BridgeJS) public static func bridgeJSLiftParameter( + _ isSome: Int32, + _ kind: Int32, + _ payload1: Int32, + _ payload2: Double + ) -> Self { + Self( + optional: Optional.bridgeJSLiftParameter(isSome, kind, payload1, payload2) + .map { Wrapped.bridgeFromJS($0) } + ) + } + @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { + asOptional.map { $0.bridgeToJS() }.bridgeJSLowerReturn() + } +} + extension Bool: _BridgedSwiftTypeLoweredIntoSingleWasmCoreType, _BridgedSwiftStackType { // MARK: ImportTS @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { diff --git a/Tests/BridgeJSRuntimeTests/AliasAPIs.swift b/Tests/BridgeJSRuntimeTests/AliasAPIs.swift index bd6737b77..b6d637966 100644 --- a/Tests/BridgeJSRuntimeTests/AliasAPIs.swift +++ b/Tests/BridgeJSRuntimeTests/AliasAPIs.swift @@ -116,46 +116,10 @@ import JavaScriptKit return polygon.vertices.map { Polygon(vertices: [$0], label: polygon.label) } } -@JS(as: TokenReference.self) struct Token: ~Copyable { - let value: Int - - consuming func bridgeToJS() -> TokenReference { - return TokenReference(value: value) - } - - static func bridgeFromJS(_ value: consuming TokenReference) -> Token { - return Token(value: value.value) - } -} - -@JS final class TokenReference { - let value: Int - - @JS init(value: Int) { - self.value = value - } - - @JS func read() -> Int { - return value - } -} - -@JS func incrementToken(_ token: borrowing Token) -> Token { - return Token(value: token.value + 1) -} - -@JS func makeToken(_ value: Int) -> Token { - return Token(value: value) -} - @JS func makePolygonInspector() -> (Polygon) -> Int { return { polygon in polygon.vertices.count } } -@JS func asyncMakePolygon(_ label: String) async -> Polygon { - return Polygon(vertices: [9, 9], label: label) -} - @JS func roundTripOptionalPolygonArray(_ polygons: [Polygon?]) -> [Polygon?] { return polygons } @@ -294,38 +258,6 @@ import JavaScriptKit return Alert(level: level) } -@JS(as: SessionState.self) class Session { - var token: String - - init(token: String) { - self.token = token - } - - consuming func bridgeToJS() -> SessionState { - return SessionState(token: token) - } - - static func bridgeFromJS(_ value: consuming SessionState) -> Session { - return Session(token: value.token) - } -} - -@JS struct SessionState { - var token: String - - @JS init(token: String) { - self.token = token - } -} - -@JS func roundTripSession(_ session: Session) -> Session { - return session -} - -@JS func makeSession(_ token: String) -> Session { - return Session(token: token) -} - @JS enum Shape { case polygon(Polygon) case empty @@ -343,6 +275,30 @@ import JavaScriptKit return .empty } +@JS(as: Int.self) struct UserId { + var rawValue: Int + + consuming func bridgeToJS() -> Int { + return rawValue + } + + static func bridgeFromJS(_ value: consuming Int) -> UserId { + return UserId(rawValue: value) + } +} + +@JS func roundTripUserId(_ id: UserId) -> UserId { + return id +} + +@JS func roundTripOptionalUserId(_ id: UserId?) -> UserId? { + return id +} + +@JS func roundTripUserIdArray(_ ids: [UserId]) -> [UserId] { + return ids +} + // MARK: - Imports @JS(as: String.self) struct Tagged { @@ -391,6 +347,26 @@ import JavaScriptKit } } +@JS(as: JSValue.self) struct Boxed { + var value: JSValue + + consuming func bridgeToJS() -> JSValue { + return value + } + + static func bridgeFromJS(_ value: consuming JSValue) -> Boxed { + return Boxed(value: value) + } +} + +@JS func roundTripBoxed(_ boxed: Boxed) -> Boxed { + return boxed +} + +@JS func roundTripOptionalBoxed(_ boxed: Boxed?) -> Boxed? { + return boxed +} + @JSClass struct AliasImports { @JSFunction static func jsRoundTripTagged(_ value: Tagged) throws(JSException) -> Tagged @JSFunction static func jsRoundTripOptionalTagged(_ value: Tagged?) throws(JSException) -> Tagged? @@ -398,4 +374,6 @@ import JavaScriptKit @JSFunction static func jsRoundTripAliasedTags(_ values: [AliasedTag?]) throws(JSException) -> [AliasedTag?] @JSFunction static func jsRoundTripPolygon(_ value: Polygon) throws(JSException) -> Polygon @JSFunction static func jsRoundTripCoordinate(_ value: Coordinate) throws(JSException) -> Coordinate + @JSFunction static func jsRoundTripUserId(_ value: UserId) throws(JSException) -> UserId + @JSFunction static func jsRoundTripOptionalUserId(_ value: UserId?) throws(JSException) -> UserId? } diff --git a/Tests/BridgeJSRuntimeTests/AliasTests.swift b/Tests/BridgeJSRuntimeTests/AliasTests.swift index 2e4548ec9..d1f0b40a8 100644 --- a/Tests/BridgeJSRuntimeTests/AliasTests.swift +++ b/Tests/BridgeJSRuntimeTests/AliasTests.swift @@ -10,10 +10,6 @@ final class AliasTests: XCTestCase { runAliasWorks() } - func testAliasAsyncEndToEnd() async throws { - try await runAliasAsyncWorks() - } - // MARK: - Imports func testRoundTripTagged() throws { @@ -69,4 +65,15 @@ final class AliasTests: XCTestCase { XCTAssertEqual(echoed.latitude, 12.5) XCTAssertEqual(echoed.longitude, -34.25) } + + func testRoundTripUserIdImport() throws { + let echoed = try AliasImports.jsRoundTripUserId(UserId(rawValue: 42)) + XCTAssertEqual(echoed.rawValue, 42) + } + + func testRoundTripOptionalUserIdImport() throws { + XCTAssertNil(try AliasImports.jsRoundTripOptionalUserId(nil)) + XCTAssertEqual(try AliasImports.jsRoundTripOptionalUserId(UserId(rawValue: 0))?.rawValue, 0) + XCTAssertEqual(try AliasImports.jsRoundTripOptionalUserId(UserId(rawValue: 7))?.rawValue, 7) + } } diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.Macros.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.Macros.swift index b2f7795cc..08d0db2a7 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.Macros.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.Macros.swift @@ -44,8 +44,6 @@ extension FeatureFlag: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum {} @JSFunction func runAsyncWorks() async throws(JSException) -> Void -@JSFunction func runAliasAsyncWorks() async throws(JSException) -> Void - @JSFunction func fetchWeatherData(_ city: String) async throws(JSException) -> WeatherData @JSClass struct WeatherData { diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 1192d4b33..8968773a4 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -674,7 +674,7 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsAl7Polygon_Si { return { [callback] param0 in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() - let param0Pointer = param0.bridgeToJS().bridgeJSLowerParameter() + let param0Pointer = param0.bridgeJSLowerParameter() let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsAl7Polygon_Si(callbackValue, param0Pointer) return Int.bridgeJSLiftReturn(ret) #else @@ -700,13 +700,179 @@ extension JSTypedClosure where Signature == (Polygon) -> Int { public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsAl7Polygon_Si(_ boxPtr: UnsafeMutableRawPointer, _ param0: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Polygon) -> Int>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure(Polygon.bridgeFromJS(PolygonReference.bridgeJSLiftParameter(param0))) + let result = closure(Polygon.bridgeJSLiftParameter(param0)) return result.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb_extern(callback, param0Bytes, param0Length) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestsKSS_Sb { + static func bridgeJSLift(_ callbackId: Int32) -> (String) throws(JSException) -> Bool { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] (param0: String) throws(JSException) -> Bool in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb(callbackValue, param0Bytes, param0Length) + return ret + } + let ret = ret0 + if let error = _swift_js_take_exception() { + throw error + } + return Bool.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (String) throws(JSException) -> Bool { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (String) throws(JSException) -> Bool) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(String) throws(JSException) -> Bool>>.fromOpaque(boxPtr).takeUnretainedValue().closure + do { + let result = try closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) + return result.bridgeJSLowerReturn() + } catch let error { + if let error = error.thrownValue.object { + withExtendedLifetime(error) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } else { + let jsError = JSError(message: error.description) + withExtendedLifetime(jsError.jsObject) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } + return 0 + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si_extern(callback, param0Bytes, param0Length) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestsKSS_Si { + static func bridgeJSLift(_ callbackId: Int32) -> (String) throws(JSException) -> Int { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] (param0: String) throws(JSException) -> Int in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si(callbackValue, param0Bytes, param0Length) + return ret + } + let ret = ret0 + if let error = _swift_js_take_exception() { + throw error + } + return Int.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (String) throws(JSException) -> Int { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (String) throws(JSException) -> Int) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(String) throws(JSException) -> Int>>.fromOpaque(boxPtr).takeUnretainedValue().closure + do { + let result = try closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) + return result.bridgeJSLowerReturn() + } catch let error { + if let error = error.thrownValue.object { + withExtendedLifetime(error) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } else { + let jsError = JSError(message: error.description) + withExtendedLifetime(jsError.jsObject) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } + return 0 + } + #else + fatalError("Only available on WebAssembly") + #endif +} + #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC") fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> UnsafeMutableRawPointer @@ -1865,38 +2031,45 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqS } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y_extern(callback, param0Bytes, param0Length) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS_extern(resolveRef, rejectRef, callback, param0Bytes, param0Length) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y_extern(boxPtr, file, line) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestss11FeatureFlagO_y { - static func bridgeJSLift(_ callbackId: Int32) -> (sending FeatureFlag) -> Void { +private enum _BJS_Closure_20BridgeJSRuntimeTestsYaKSS_SS { + static func bridgeJSLift(_ callbackId: Int32) -> (String) async throws(JSException) -> String { let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] param0 in + return { [callback] (param0: String) async throws(JSException) -> String in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() - param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y(callbackValue, param0Bytes, param0Length) + let resolved = try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending String) -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + let callbackValue = callback.bridgeJSLowerParameter() + param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS(resolveRef, rejectRef, callbackValue, param0Bytes, param0Length) + } } + return resolved #else fatalError("Only available on WebAssembly") #endif @@ -1904,10 +2077,10 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestss11FeatureFlagO_y { } } -extension JSTypedClosure where Signature == (sending FeatureFlag) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending FeatureFlag) -> Void) { +extension JSTypedClosure where Signature == (String) async throws(JSException) -> String { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (String) async throws(JSException) -> String) { self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y, + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS, body: body, fileID: fileID, line: line @@ -1915,49 +2088,58 @@ extension JSTypedClosure where Signature == (sending FeatureFlag) -> Void { } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending FeatureFlag) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(FeatureFlag.bridgeJSLiftParameter(param0Bytes, param0Length)) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(String) async throws(JSException) -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure + return _bjs_makePromise(resolve: Promise_resolve_SS, reject: Promise_reject) { () async throws(JSException) -> String in + return try await closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) + } #else fatalError("Only available on WebAssembly") #endif } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y_extern(_ callback: Int32, _ param0: Int32) -> Void +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y_extern(_ callback: Int32, _ param0: Int32) -> Void { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y(_ callback: Int32, _ param0: Int32) -> Void { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y_extern(callback, param0) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y_extern(resolveRef, rejectRef, callback, param0Bytes, param0Length) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y_extern(boxPtr, file, line) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestss11WeatherDataC_y { - static func bridgeJSLift(_ callbackId: Int32) -> (sending WeatherData) -> Void { +private enum _BJS_Closure_20BridgeJSRuntimeTestsYaKSS_y { + static func bridgeJSLift(_ callbackId: Int32) -> (String) async throws(JSException) -> Void { let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] param0 in + return { [callback] (param0: String) async throws(JSException) -> Void in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() - let param0Value = param0.bridgeJSLowerParameter() - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y(callbackValue, param0Value) + try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<() -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + let callbackValue = callback.bridgeJSLowerParameter() + param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y(resolveRef, rejectRef, callbackValue, param0Bytes, param0Length) + } + } #else fatalError("Only available on WebAssembly") #endif @@ -1965,10 +2147,10 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestss11WeatherDataC_y { } } -extension JSTypedClosure where Signature == (sending WeatherData) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending WeatherData) -> Void) { +extension JSTypedClosure where Signature == (String) async throws(JSException) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (String) async throws(JSException) -> Void) { self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y, + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y, body: body, fileID: fileID, line: line @@ -1976,49 +2158,58 @@ extension JSTypedClosure where Signature == (sending WeatherData) -> Void { } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending WeatherData) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(WeatherData.bridgeJSLiftParameter(param0)) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(String) async throws(JSException) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + return _bjs_makePromise(resolve: Promise_resolve_y, reject: Promise_reject) { () async throws(JSException) in + try await closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) + } #else fatalError("Only available on WebAssembly") #endif } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y_extern(_ callback: Int32, _ param0Kind: Int32, _ param0Payload1: Int32, _ param0Payload2: Float64) -> Void +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0: Int32) -> Void #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y_extern(_ callback: Int32, _ param0Kind: Int32, _ param0Payload1: Int32, _ param0Payload2: Float64) -> Void { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y(_ callback: Int32, _ param0Kind: Int32, _ param0Payload1: Int32, _ param0Payload2: Float64) -> Void { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y_extern(callback, param0Kind, param0Payload1, param0Payload2) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO_extern(resolveRef, rejectRef, callback, param0) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y_extern(boxPtr, file, line) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestss7JSValueV_y { - static func bridgeJSLift(_ callbackId: Int32) -> (sending JSValue) -> Void { +private enum _BJS_Closure_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO { + static func bridgeJSLift(_ callbackId: Int32) -> (Bool) async throws(JSException) -> AsyncPayloadResult { let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] param0 in + return { [callback] (param0: Bool) async throws(JSException) -> AsyncPayloadResult in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() - let (param0Kind, param0Payload1, param0Payload2) = param0.bridgeJSLowerParameter() - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y(callbackValue, param0Kind, param0Payload1, param0Payload2) + let resolved = try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending AsyncPayloadResult) -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + let callbackValue = callback.bridgeJSLowerParameter() + let param0Value = param0.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO(resolveRef, rejectRef, callbackValue, param0Value) + } + return resolved #else fatalError("Only available on WebAssembly") #endif @@ -2026,10 +2217,10 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestss7JSValueV_y { } } -extension JSTypedClosure where Signature == (sending JSValue) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending JSValue) -> Void) { +extension JSTypedClosure where Signature == (Bool) async throws(JSException) -> AsyncPayloadResult { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Bool) async throws(JSException) -> AsyncPayloadResult) { self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y, + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO, body: body, fileID: fileID, line: line @@ -2037,50 +2228,59 @@ extension JSTypedClosure where Signature == (sending JSValue) -> Void { } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y(_ boxPtr: UnsafeMutableRawPointer, _ param0Kind: Int32, _ param0Payload1: Int32, _ param0Payload2: Float64) -> Void { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Int32 { #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending JSValue) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(JSValue.bridgeJSLiftParameter(param0Kind, param0Payload1, param0Payload2)) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Bool) async throws(JSException) -> AsyncPayloadResult>>.fromOpaque(boxPtr).takeUnretainedValue().closure + return _bjs_makePromise(resolve: Promise_resolve_18AsyncPayloadResultO, reject: Promise_reject) { () async throws(JSException) -> AsyncPayloadResult in + return try await closure(Bool.bridgeJSLiftParameter(param0)) + } #else fatalError("Only available on WebAssembly") #endif } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y_extern(callback, param0Bytes, param0Length) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS_extern(resolveRef, rejectRef, callback, param0Bytes, param0Length) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y_extern(boxPtr, file, line) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestssSS_y { - static func bridgeJSLift(_ callbackId: Int32) -> (sending String) -> Void { +private enum _BJS_Closure_20BridgeJSRuntimeTestsYaSS_SS { + static func bridgeJSLift(_ callbackId: Int32) -> (String) async -> String { let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] param0 in + return { [callback] (param0: String) async -> String in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() - param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y(callbackValue, param0Bytes, param0Length) + let resolved = try! await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending String) -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + let callbackValue = callback.bridgeJSLowerParameter() + param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS(resolveRef, rejectRef, callbackValue, param0Bytes, param0Length) + } } + return resolved #else fatalError("Only available on WebAssembly") #endif @@ -2088,10 +2288,10 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestssSS_y { } } -extension JSTypedClosure where Signature == (sending String) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending String) -> Void) { +extension JSTypedClosure where Signature == (String) async -> String { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (String) async -> String) { self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y, + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS, body: body, fileID: fileID, line: line @@ -2099,49 +2299,58 @@ extension JSTypedClosure where Signature == (sending String) -> Void { } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Int32 { #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending String) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(String) async -> String>>.fromOpaque(boxPtr).takeUnretainedValue().closure + return _bjs_makePromise(resolve: Promise_resolve_SS, reject: Promise_reject) { + return await closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) + } #else fatalError("Only available on WebAssembly") #endif } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y_extern(_ callback: Int32) -> Void +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0: Float64) -> Void #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y_extern(_ callback: Int32) -> Void { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0: Float64) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y(_ callback: Int32) -> Void { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y_extern(callback) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV(_ resolveRef: Int32, _ rejectRef: Int32, _ callback: Int32, _ param0: Float64) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV_extern(resolveRef, rejectRef, callback, param0) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y_extern(boxPtr, file, line) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestssSaSS_y { - static func bridgeJSLift(_ callbackId: Int32) -> (sending [String]) -> Void { +private enum _BJS_Closure_20BridgeJSRuntimeTestsYaSd_9DataPointV { + static func bridgeJSLift(_ callbackId: Int32) -> (Double) async -> DataPoint { let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] param0 in + return { [callback] (param0: Double) async -> DataPoint in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() - let _ = param0.bridgeJSLowerParameter() - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y(callbackValue) + let resolved = try! await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending DataPoint) -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + let callbackValue = callback.bridgeJSLowerParameter() + let param0Value = param0.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV(resolveRef, rejectRef, callbackValue, param0Value) + } + return resolved #else fatalError("Only available on WebAssembly") #endif @@ -2149,10 +2358,10 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestssSaSS_y { } } -extension JSTypedClosure where Signature == (sending [String]) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending [String]) -> Void) { +extension JSTypedClosure where Signature == (Double) async -> DataPoint { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Double) async -> DataPoint) { self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y, + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV, body: body, fileID: fileID, line: line @@ -2160,49 +2369,52 @@ extension JSTypedClosure where Signature == (sending [String]) -> Void { } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y(_ boxPtr: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV(_ boxPtr: UnsafeMutableRawPointer, _ param0: Float64) -> Int32 { #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending [String]) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure([String].bridgeJSLiftParameter()) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Double) async -> DataPoint>>.fromOpaque(boxPtr).takeUnretainedValue().closure + return _bjs_makePromise(resolve: Promise_resolve_9DataPointV, reject: Promise_reject) { + return await closure(Double.bridgeJSLiftParameter(param0)) + } #else fatalError("Only available on WebAssembly") #endif } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y_extern(_ callback: Int32) -> Void +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y_extern(_ callback: Int32) -> Void { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y(_ callback: Int32) -> Void { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y_extern(callback) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y_extern(callback, param0Bytes, param0Length) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 -#else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y_extern(boxPtr, file, line) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestssSaSb_y { - static func bridgeJSLift(_ callbackId: Int32) -> (sending [Bool]) -> Void { +private enum _BJS_Closure_20BridgeJSRuntimeTestss11FeatureFlagO_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending FeatureFlag) -> Void { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() - let _ = param0.bridgeJSLowerParameter() - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y(callbackValue) + param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y(callbackValue, param0Bytes, param0Length) + } #else fatalError("Only available on WebAssembly") #endif @@ -2210,10 +2422,10 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestssSaSb_y { } } -extension JSTypedClosure where Signature == (sending [Bool]) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending [Bool]) -> Void) { +extension JSTypedClosure where Signature == (sending FeatureFlag) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending FeatureFlag) -> Void) { self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y, + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y, body: body, fileID: fileID, line: line @@ -2221,49 +2433,49 @@ extension JSTypedClosure where Signature == (sending [Bool]) -> Void { } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y(_ boxPtr: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending [Bool]) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure([Bool].bridgeJSLiftParameter()) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending FeatureFlag) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(FeatureFlag.bridgeJSLiftParameter(param0Bytes, param0Length)) #else fatalError("Only available on WebAssembly") #endif } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y_extern(_ callback: Int32) -> Void +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y_extern(_ callback: Int32, _ param0: Int32) -> Void #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y_extern(_ callback: Int32) -> Void { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y_extern(_ callback: Int32, _ param0: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y(_ callback: Int32) -> Void { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y_extern(callback) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y(_ callback: Int32, _ param0: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y_extern(callback, param0) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y_extern(boxPtr, file, line) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestssSaSd_y { - static func bridgeJSLift(_ callbackId: Int32) -> (sending [Double]) -> Void { +private enum _BJS_Closure_20BridgeJSRuntimeTestss11WeatherDataC_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending WeatherData) -> Void { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() - let _ = param0.bridgeJSLowerParameter() - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y(callbackValue) + let param0Value = param0.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y(callbackValue, param0Value) #else fatalError("Only available on WebAssembly") #endif @@ -2271,10 +2483,10 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestssSaSd_y { } } -extension JSTypedClosure where Signature == (sending [Double]) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending [Double]) -> Void) { +extension JSTypedClosure where Signature == (sending WeatherData) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending WeatherData) -> Void) { self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y, + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y, body: body, fileID: fileID, line: line @@ -2282,49 +2494,49 @@ extension JSTypedClosure where Signature == (sending [Double]) -> Void { } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y(_ boxPtr: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending [Double]) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure([Double].bridgeJSLiftParameter()) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending WeatherData) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(WeatherData.bridgeJSLiftParameter(param0)) #else fatalError("Only available on WebAssembly") #endif } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y_extern(_ callback: Int32, _ param0: Int32) -> Void +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y_extern(_ callback: Int32, _ param0: Int32) -> Void #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y_extern(_ callback: Int32, _ param0: Int32) -> Void { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y_extern(_ callback: Int32, _ param0: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y(_ callback: Int32, _ param0: Int32) -> Void { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y_extern(callback, param0) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y(_ callback: Int32, _ param0: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y_extern(callback, param0) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y_extern(boxPtr, file, line) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestssSb_y { - static func bridgeJSLift(_ callbackId: Int32) -> (sending Bool) -> Void { +private enum _BJS_Closure_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending AsyncPayloadResult) -> Void { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() - let param0Value = param0.bridgeJSLowerParameter() - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y(callbackValue, param0Value) + let param0CaseId = param0.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y(callbackValue, param0CaseId) #else fatalError("Only available on WebAssembly") #endif @@ -2332,10 +2544,10 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestssSb_y { } } -extension JSTypedClosure where Signature == (sending Bool) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Bool) -> Void) { +extension JSTypedClosure where Signature == (sending AsyncPayloadResult) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending AsyncPayloadResult) -> Void) { self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y, + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y, body: body, fileID: fileID, line: line @@ -2343,49 +2555,49 @@ extension JSTypedClosure where Signature == (sending Bool) -> Void { } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending Bool) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(Bool.bridgeJSLiftParameter(param0)) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending AsyncPayloadResult) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(AsyncPayloadResult.bridgeJSLiftParameter(param0)) #else fatalError("Only available on WebAssembly") #endif } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y_extern(_ callback: Int32, _ param0: Float64) -> Void +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y_extern(_ callback: Int32, _ param0: Int32) -> Void #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y_extern(_ callback: Int32, _ param0: Float64) -> Void { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y_extern(_ callback: Int32, _ param0: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y(_ callback: Int32, _ param0: Float64) -> Void { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y_extern(callback, param0) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y(_ callback: Int32, _ param0: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y_extern(callback, param0) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y_extern(boxPtr, file, line) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestssSd_y { - static func bridgeJSLift(_ callbackId: Int32) -> (sending Double) -> Void { +private enum _BJS_Closure_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending AsyncImportedPayloadResult) -> Void { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() - let param0Value = param0.bridgeJSLowerParameter() - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y(callbackValue, param0Value) + let param0CaseId = param0.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y(callbackValue, param0CaseId) #else fatalError("Only available on WebAssembly") #endif @@ -2393,10 +2605,10 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestssSd_y { } } -extension JSTypedClosure where Signature == (sending Double) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Double) -> Void) { +extension JSTypedClosure where Signature == (sending AsyncImportedPayloadResult) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending AsyncImportedPayloadResult) -> Void) { self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y, + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y, body: body, fileID: fileID, line: line @@ -2404,50 +2616,49 @@ extension JSTypedClosure where Signature == (sending Double) -> Void { } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Float64) -> Void { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending Double) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(Double.bridgeJSLiftParameter(param0)) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending AsyncImportedPayloadResult) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(AsyncImportedPayloadResult.bridgeJSLiftParameter(param0)) #else fatalError("Only available on WebAssembly") #endif } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y_extern(_ callback: Int32, _ param0Kind: Int32, _ param0Payload1: Int32, _ param0Payload2: Float64) -> Void #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y_extern(_ callback: Int32, _ param0Kind: Int32, _ param0Payload1: Int32, _ param0Payload2: Float64) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y_extern(callback, param0IsSome, param0Bytes, param0Length) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y(_ callback: Int32, _ param0Kind: Int32, _ param0Payload1: Int32, _ param0Payload2: Float64) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y_extern(callback, param0Kind, param0Payload1, param0Payload2) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y_extern(boxPtr, file, line) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestssSqSS_y { - static func bridgeJSLift(_ callbackId: Int32) -> (sending Optional) -> Void { +private enum _BJS_Closure_20BridgeJSRuntimeTestss7JSValueV_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending JSValue) -> Void { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() - param0.bridgeJSWithLoweredParameter { (param0IsSome, param0Bytes, param0Length) in - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y(callbackValue, param0IsSome, param0Bytes, param0Length) - } + let (param0Kind, param0Payload1, param0Payload2) = param0.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y(callbackValue, param0Kind, param0Payload1, param0Payload2) #else fatalError("Only available on WebAssembly") #endif @@ -2455,10 +2666,10 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestssSqSS_y { } } -extension JSTypedClosure where Signature == (sending Optional) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Optional) -> Void) { +extension JSTypedClosure where Signature == (sending JSValue) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending JSValue) -> Void) { self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y, + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y, body: body, fileID: fileID, line: line @@ -2466,49 +2677,49 @@ extension JSTypedClosure where Signature == (sending Optional) -> Void { } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y(_ boxPtr: UnsafeMutableRawPointer, _ param0Kind: Int32, _ param0Payload1: Int32, _ param0Payload2: Float64) -> Void { #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending Optional) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Bytes, param0Length)) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending JSValue) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(JSValue.bridgeJSLiftParameter(param0Kind, param0Payload1, param0Payload2)) #else fatalError("Only available on WebAssembly") #endif } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Float64) -> Void +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y_extern(_ callback: Int32) -> Void #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Float64) -> Void { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y_extern(_ callback: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Float64) -> Void { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y_extern(callback, param0IsSome, param0Value) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y(_ callback: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y_extern(callback) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y_extern(boxPtr, file, line) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestssSqSd_y { - static func bridgeJSLift(_ callbackId: Int32) -> (sending Optional) -> Void { +private enum _BJS_Closure_20BridgeJSRuntimeTestss9DataPointV_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending DataPoint) -> Void { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() - let (param0IsSome, param0Value) = param0.bridgeJSLowerParameter() - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y(callbackValue, param0IsSome, param0Value) + let _ = param0.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y(callbackValue) #else fatalError("Only available on WebAssembly") #endif @@ -2516,10 +2727,10 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestssSqSd_y { } } -extension JSTypedClosure where Signature == (sending Optional) -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Optional) -> Void) { +extension JSTypedClosure where Signature == (sending DataPoint) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending DataPoint) -> Void) { self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y, + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y, body: body, fileID: fileID, line: line @@ -2527,49 +2738,50 @@ extension JSTypedClosure where Signature == (sending Optional) -> Void { } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Value: Float64) -> Void { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y(_ boxPtr: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending Optional) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending DataPoint) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(DataPoint.bridgeJSLiftParameter()) #else fatalError("Only available on WebAssembly") #endif } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP_extern(_ callback: Int32) -> Int32 +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP_extern(_ callback: Int32) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y_extern(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP(_ callback: Int32) -> Int32 { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP_extern(callback) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y(_ callback: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y_extern(callback, param0Bytes, param0Length) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP_extern(boxPtr, file, line) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestsy_13DataProcessorP { - static func bridgeJSLift(_ callbackId: Int32) -> () -> any DataProcessor { +private enum _BJS_Closure_20BridgeJSRuntimeTestssSS_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending String) -> Void { let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] in + return { [callback] param0 in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() - let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP(callbackValue) - return AnyDataProcessor.bridgeJSLiftReturn(ret) + param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y(callbackValue, param0Bytes, param0Length) + } #else fatalError("Only available on WebAssembly") #endif @@ -2577,10 +2789,10 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsy_13DataProcessorP { } } -extension JSTypedClosure where Signature == () -> any DataProcessor { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping () -> any DataProcessor) { +extension JSTypedClosure where Signature == (sending String) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending String) -> Void) { self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP, + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y, body: body, fileID: fileID, line: line @@ -2588,50 +2800,49 @@ extension JSTypedClosure where Signature == () -> any DataProcessor { } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP(_ boxPtr: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y(_ boxPtr: UnsafeMutableRawPointer, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<() -> any DataProcessor>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure() - return (result as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn() + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending String) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(String.bridgeJSLiftParameter(param0Bytes, param0Length)) #else fatalError("Only available on WebAssembly") #endif } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb_extern(_ callback: Int32) -> Int32 +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y_extern(_ callback: Int32) -> Void #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb_extern(_ callback: Int32) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y_extern(_ callback: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb(_ callback: Int32) -> Int32 { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb_extern(callback) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y(_ callback: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y_extern(callback) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb_extern(boxPtr, file, line) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestsy_Sb { - static func bridgeJSLift(_ callbackId: Int32) -> () -> Bool { +private enum _BJS_Closure_20BridgeJSRuntimeTestssSaSS_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending [String]) -> Void { let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] in + return { [callback] param0 in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() - let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb(callbackValue) - return Bool.bridgeJSLiftReturn(ret) + let _ = param0.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y(callbackValue) #else fatalError("Only available on WebAssembly") #endif @@ -2639,10 +2850,10 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsy_Sb { } } -extension JSTypedClosure where Signature == () -> Bool { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping () -> Bool) { +extension JSTypedClosure where Signature == (sending [String]) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending [String]) -> Void) { self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb, + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y, body: body, fileID: fileID, line: line @@ -2650,50 +2861,49 @@ extension JSTypedClosure where Signature == () -> Bool { } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb(_ boxPtr: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y(_ boxPtr: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<() -> Bool>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure() - return result.bridgeJSLowerReturn() + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending [String]) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure([String].bridgeJSLiftParameter()) #else fatalError("Only available on WebAssembly") #endif } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC_extern(_ callback: Int32) -> UnsafeMutableRawPointer +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y_extern(_ callback: Int32) -> Void #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC_extern(_ callback: Int32) -> UnsafeMutableRawPointer { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y_extern(_ callback: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC(_ callback: Int32) -> UnsafeMutableRawPointer { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC_extern(callback) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y(_ callback: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y_extern(callback) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC_extern(boxPtr, file, line) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestsy_Sq7GreeterC { - static func bridgeJSLift(_ callbackId: Int32) -> () -> Optional { +private enum _BJS_Closure_20BridgeJSRuntimeTestssSaSb_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending [Bool]) -> Void { let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] in + return { [callback] param0 in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() - let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC(callbackValue) - return Optional.bridgeJSLiftReturn(ret) + let _ = param0.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y(callbackValue) #else fatalError("Only available on WebAssembly") #endif @@ -2701,10 +2911,10 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsy_Sq7GreeterC { } } -extension JSTypedClosure where Signature == () -> Optional { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping () -> Optional) { +extension JSTypedClosure where Signature == (sending [Bool]) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending [Bool]) -> Void) { self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC, + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y, body: body, fileID: fileID, line: line @@ -2712,49 +2922,49 @@ extension JSTypedClosure where Signature == () -> Optional { } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC(_ boxPtr: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y(_ boxPtr: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<() -> Optional>>.fromOpaque(boxPtr).takeUnretainedValue().closure - let result = closure() - return result.bridgeJSLowerReturn() + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending [Bool]) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure([Bool].bridgeJSLiftParameter()) #else fatalError("Only available on WebAssembly") #endif } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y") -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y_extern(_ callback: Int32) -> Void +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y_extern(_ callback: Int32) -> Void #else -fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y_extern(_ callback: Int32) -> Void { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y_extern(_ callback: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y(_ callback: Int32) -> Void { - return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y_extern(callback) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y(_ callback: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y_extern(callback) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y") -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y_extern(boxPtr, file, line) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y_extern(boxPtr, file, line) } -private enum _BJS_Closure_20BridgeJSRuntimeTestsy_y { - static func bridgeJSLift(_ callbackId: Int32) -> () -> Void { +private enum _BJS_Closure_20BridgeJSRuntimeTestssSaSd_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending [Double]) -> Void { let callback = JSObject.bridgeJSLiftParameter(callbackId) - return { [callback] in + return { [callback] param0 in #if arch(wasm32) let callbackValue = callback.bridgeJSLowerParameter() - invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y(callbackValue) + let _ = param0.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y(callbackValue) #else fatalError("Only available on WebAssembly") #endif @@ -2762,10 +2972,10 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsy_y { } } -extension JSTypedClosure where Signature == () -> Void { - init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping () -> Void) { +extension JSTypedClosure where Signature == (sending [Double]) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending [Double]) -> Void) { self.init( - makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y, + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y, body: body, fileID: fileID, line: line @@ -2773,683 +2983,1235 @@ extension JSTypedClosure where Signature == () -> Void { } } -@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y") -@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y") -public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y(_ boxPtr: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y(_ boxPtr: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let closure = Unmanaged<_BridgeJSTypedClosureBox<() -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure - closure() + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending [Double]) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure([Double].bridgeJSLiftParameter()) #else fatalError("Only available on WebAssembly") #endif } -struct AnyArrayElementProtocol: ArrayElementProtocol, _BridgedSwiftProtocolWrapper { - let jsObject: JSObject +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y_extern(_ callback: Int32, _ param0: Int32) -> Void +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y_extern(_ callback: Int32, _ param0: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y(_ callback: Int32, _ param0: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y_extern(callback, param0) +} - var value: Int { - get { - let jsObjectValue = jsObject.bridgeJSLowerParameter() - let ret = bjs_ArrayElementProtocol_value_get(jsObjectValue) - return Int.bridgeJSLiftReturn(ret) - } - set { - let jsObjectValue = jsObject.bridgeJSLowerParameter() - let newValueValue = newValue.bridgeJSLowerParameter() - bjs_ArrayElementProtocol_value_set(jsObjectValue, newValueValue) +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestssSb_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending Bool) -> Void { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let param0Value = param0.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y(callbackValue, param0Value) + #else + fatalError("Only available on WebAssembly") + #endif } } +} - static func bridgeJSLiftParameter(_ value: Int32) -> Self { - return AnyArrayElementProtocol(jsObject: JSObject(id: UInt32(bitPattern: value))) +extension JSTypedClosure where Signature == (sending Bool) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Bool) -> Void) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y, + body: body, + fileID: fileID, + line: line + ) } } +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Int32) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending Bool) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(Bool.bridgeJSLiftParameter(param0)) + #else + fatalError("Only available on WebAssembly") + #endif +} + #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ArrayElementProtocol_value_get") -fileprivate func bjs_ArrayElementProtocol_value_get_extern(_ jsObject: Int32) -> Int32 +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y_extern(_ callback: Int32, _ param0: Float64) -> Void #else -fileprivate func bjs_ArrayElementProtocol_value_get_extern(_ jsObject: Int32) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y_extern(_ callback: Int32, _ param0: Float64) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_ArrayElementProtocol_value_get(_ jsObject: Int32) -> Int32 { - return bjs_ArrayElementProtocol_value_get_extern(jsObject) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y(_ callback: Int32, _ param0: Float64) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y_extern(callback, param0) } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ArrayElementProtocol_value_set") -fileprivate func bjs_ArrayElementProtocol_value_set_extern(_ jsObject: Int32, _ newValue: Int32) -> Void +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func bjs_ArrayElementProtocol_value_set_extern(_ jsObject: Int32, _ newValue: Int32) -> Void { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_ArrayElementProtocol_value_set(_ jsObject: Int32, _ newValue: Int32) -> Void { - return bjs_ArrayElementProtocol_value_set_extern(jsObject, newValue) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y_extern(boxPtr, file, line) } -struct AnyDataProcessor: DataProcessor, _BridgedSwiftProtocolWrapper { - let jsObject: JSObject - - func increment(by amount: Int) -> Void { - let jsObjectValue = jsObject.bridgeJSLowerParameter() - let amountValue = amount.bridgeJSLowerParameter() - _extern_increment(jsObjectValue, amountValue) - } - - func getValue() -> Int { - let jsObjectValue = jsObject.bridgeJSLowerParameter() - let ret = _extern_getValue(jsObjectValue) - return Int.bridgeJSLiftReturn(ret) - } - - func setLabelElements(_ labelPrefix: String, _ labelSuffix: String) -> Void { - let jsObjectValue = jsObject.bridgeJSLowerParameter() - labelPrefix.bridgeJSWithLoweredParameter { (labelPrefixBytes, labelPrefixLength) in - labelSuffix.bridgeJSWithLoweredParameter { (labelSuffixBytes, labelSuffixLength) in - _extern_setLabelElements(jsObjectValue, labelPrefixBytes, labelPrefixLength, labelSuffixBytes, labelSuffixLength) - } +private enum _BJS_Closure_20BridgeJSRuntimeTestssSd_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending Double) -> Void { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let param0Value = param0.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y(callbackValue, param0Value) + #else + fatalError("Only available on WebAssembly") + #endif } } +} - func getLabel() -> String { - let jsObjectValue = jsObject.bridgeJSLowerParameter() - let ret = _extern_getLabel(jsObjectValue) - return String.bridgeJSLiftReturn(ret) - } - - func isEven() -> Bool { - let jsObjectValue = jsObject.bridgeJSLowerParameter() - let ret = _extern_isEven(jsObjectValue) - return Bool.bridgeJSLiftReturn(ret) - } - - func processGreeter(_ greeter: Greeter) -> String { - let jsObjectValue = jsObject.bridgeJSLowerParameter() - let greeterPointer = greeter.bridgeJSLowerParameter() - let ret = _extern_processGreeter(jsObjectValue, greeterPointer) - return String.bridgeJSLiftReturn(ret) - } - - func createGreeter() -> Greeter { - let jsObjectValue = jsObject.bridgeJSLowerParameter() - let ret = _extern_createGreeter(jsObjectValue) - return Greeter.bridgeJSLiftReturn(ret) - } - - func processOptionalGreeter(_ greeter: Optional) -> String { - let jsObjectValue = jsObject.bridgeJSLowerParameter() - let (greeterIsSome, greeterPointer) = greeter.bridgeJSLowerParameter() - let ret = _extern_processOptionalGreeter(jsObjectValue, greeterIsSome, greeterPointer) - return String.bridgeJSLiftReturn(ret) - } - - func createOptionalGreeter() -> Optional { - let jsObjectValue = jsObject.bridgeJSLowerParameter() - let ret = _extern_createOptionalGreeter(jsObjectValue) - return Optional.bridgeJSLiftReturn(ret) - } - - func handleAPIResult(_ result: Optional) -> Void { - let jsObjectValue = jsObject.bridgeJSLowerParameter() - let (resultIsSome, resultCaseId) = result.bridgeJSLowerParameter() - _extern_handleAPIResult(jsObjectValue, resultIsSome, resultCaseId) - } - - func getAPIResult() -> Optional { - let jsObjectValue = jsObject.bridgeJSLowerParameter() - let ret = _extern_getAPIResult(jsObjectValue) - return Optional.bridgeJSLiftReturn(ret) - } - - var count: Int { - get { - let jsObjectValue = jsObject.bridgeJSLowerParameter() - let ret = bjs_DataProcessor_count_get(jsObjectValue) - return Int.bridgeJSLiftReturn(ret) - } - set { - let jsObjectValue = jsObject.bridgeJSLowerParameter() - let newValueValue = newValue.bridgeJSLowerParameter() - bjs_DataProcessor_count_set(jsObjectValue, newValueValue) - } - } - - var name: String { - get { - let jsObjectValue = jsObject.bridgeJSLowerParameter() - let ret = bjs_DataProcessor_name_get(jsObjectValue) - return String.bridgeJSLiftReturn(ret) - } - } - - var optionalTag: Optional { - get { - let jsObjectValue = jsObject.bridgeJSLowerParameter() - bjs_DataProcessor_optionalTag_get(jsObjectValue) - return Optional.bridgeJSLiftReturnFromSideChannel() - } - set { - let jsObjectValue = jsObject.bridgeJSLowerParameter() - newValue.bridgeJSWithLoweredParameter { (newValueIsSome, newValueBytes, newValueLength) in - bjs_DataProcessor_optionalTag_set(jsObjectValue, newValueIsSome, newValueBytes, newValueLength) - } - } - } - - var optionalCount: Optional { - get { - let jsObjectValue = jsObject.bridgeJSLowerParameter() - bjs_DataProcessor_optionalCount_get(jsObjectValue) - return Optional.bridgeJSLiftReturnFromSideChannel() - } - set { - let jsObjectValue = jsObject.bridgeJSLowerParameter() - let (newValueIsSome, newValueValue) = newValue.bridgeJSLowerParameter() - bjs_DataProcessor_optionalCount_set(jsObjectValue, newValueIsSome, newValueValue) - } - } - - var direction: Optional { - get { - let jsObjectValue = jsObject.bridgeJSLowerParameter() - let ret = bjs_DataProcessor_direction_get(jsObjectValue) - return Optional.bridgeJSLiftReturn(ret) - } - set { - let jsObjectValue = jsObject.bridgeJSLowerParameter() - let (newValueIsSome, newValueValue) = newValue.bridgeJSLowerParameter() - bjs_DataProcessor_direction_set(jsObjectValue, newValueIsSome, newValueValue) - } - } - - var optionalTheme: Optional { - get { - let jsObjectValue = jsObject.bridgeJSLowerParameter() - bjs_DataProcessor_optionalTheme_get(jsObjectValue) - return Optional.bridgeJSLiftReturnFromSideChannel() - } - set { - let jsObjectValue = jsObject.bridgeJSLowerParameter() - newValue.bridgeJSWithLoweredParameter { (newValueIsSome, newValueBytes, newValueLength) in - bjs_DataProcessor_optionalTheme_set(jsObjectValue, newValueIsSome, newValueBytes, newValueLength) - } - } - } - - var httpStatus: Optional { - get { - let jsObjectValue = jsObject.bridgeJSLowerParameter() - bjs_DataProcessor_httpStatus_get(jsObjectValue) - return Optional.bridgeJSLiftReturnFromSideChannel() - } - set { - let jsObjectValue = jsObject.bridgeJSLowerParameter() - let (newValueIsSome, newValueValue) = newValue.bridgeJSLowerParameter() - bjs_DataProcessor_httpStatus_set(jsObjectValue, newValueIsSome, newValueValue) - } - } - - var apiResult: Optional { - get { - let jsObjectValue = jsObject.bridgeJSLowerParameter() - let ret = bjs_DataProcessor_apiResult_get(jsObjectValue) - return Optional.bridgeJSLiftReturn(ret) - } - set { - let jsObjectValue = jsObject.bridgeJSLowerParameter() - let (newValueIsSome, newValueCaseId) = newValue.bridgeJSLowerParameter() - bjs_DataProcessor_apiResult_set(jsObjectValue, newValueIsSome, newValueCaseId) - } - } - - var helper: Greeter { - get { - let jsObjectValue = jsObject.bridgeJSLowerParameter() - let ret = bjs_DataProcessor_helper_get(jsObjectValue) - return Greeter.bridgeJSLiftReturn(ret) - } - set { - let jsObjectValue = jsObject.bridgeJSLowerParameter() - let newValuePointer = newValue.bridgeJSLowerParameter() - bjs_DataProcessor_helper_set(jsObjectValue, newValuePointer) - } - } - - var optionalHelper: Optional { - get { - let jsObjectValue = jsObject.bridgeJSLowerParameter() - let ret = bjs_DataProcessor_optionalHelper_get(jsObjectValue) - return Optional.bridgeJSLiftReturn(ret) - } - set { - let jsObjectValue = jsObject.bridgeJSLowerParameter() - let (newValueIsSome, newValuePointer) = newValue.bridgeJSLowerParameter() - bjs_DataProcessor_optionalHelper_set(jsObjectValue, newValueIsSome, newValuePointer) - } - } - - static func bridgeJSLiftParameter(_ value: Int32) -> Self { - return AnyDataProcessor(jsObject: JSObject(id: UInt32(bitPattern: value))) +extension JSTypedClosure where Signature == (sending Double) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Double) -> Void) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y, + body: body, + fileID: fileID, + line: line + ) } } -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_increment") -fileprivate func _extern_increment_extern(_ jsObject: Int32, _ amount: Int32) -> Void -#else -fileprivate func _extern_increment_extern(_ jsObject: Int32, _ amount: Int32) -> Void { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y(_ boxPtr: UnsafeMutableRawPointer, _ param0: Float64) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending Double) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(Double.bridgeJSLiftParameter(param0)) + #else fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func _extern_increment(_ jsObject: Int32, _ amount: Int32) -> Void { - return _extern_increment_extern(jsObject, amount) + #endif } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_getValue") -fileprivate func _extern_getValue_extern(_ jsObject: Int32) -> Int32 +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0CaseId: Int32) -> Void #else -fileprivate func _extern_getValue_extern(_ jsObject: Int32) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0CaseId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _extern_getValue(_ jsObject: Int32) -> Int32 { - return _extern_getValue_extern(jsObject) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y(_ callback: Int32, _ param0IsSome: Int32, _ param0CaseId: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y_extern(callback, param0IsSome, param0CaseId) } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_setLabelElements") -fileprivate func _extern_setLabelElements_extern(_ jsObject: Int32, _ labelPrefixBytes: Int32, _ labelPrefixLength: Int32, _ labelSuffixBytes: Int32, _ labelSuffixLength: Int32) -> Void +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func _extern_setLabelElements_extern(_ jsObject: Int32, _ labelPrefixBytes: Int32, _ labelPrefixLength: Int32, _ labelSuffixBytes: Int32, _ labelSuffixLength: Int32) -> Void { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _extern_setLabelElements(_ jsObject: Int32, _ labelPrefixBytes: Int32, _ labelPrefixLength: Int32, _ labelSuffixBytes: Int32, _ labelSuffixLength: Int32) -> Void { - return _extern_setLabelElements_extern(jsObject, labelPrefixBytes, labelPrefixLength, labelSuffixBytes, labelSuffixLength) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y_extern(boxPtr, file, line) } -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_getLabel") -fileprivate func _extern_getLabel_extern(_ jsObject: Int32) -> Int32 -#else -fileprivate func _extern_getLabel_extern(_ jsObject: Int32) -> Int32 { - fatalError("Only available on WebAssembly") +private enum _BJS_Closure_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending Optional) -> Void { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let (param0IsSome, param0CaseId) = param0.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y(callbackValue, param0IsSome, param0CaseId) + #else + fatalError("Only available on WebAssembly") + #endif + } + } } -#endif -@inline(never) fileprivate func _extern_getLabel(_ jsObject: Int32) -> Int32 { - return _extern_getLabel_extern(jsObject) + +extension JSTypedClosure where Signature == (sending Optional) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Optional) -> Void) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y, + body: body, + fileID: fileID, + line: line + ) + } } -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_isEven") -fileprivate func _extern_isEven_extern(_ jsObject: Int32) -> Int32 -#else -fileprivate func _extern_isEven_extern(_ jsObject: Int32) -> Int32 { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0CaseId: Int32) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending Optional) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(Optional.bridgeJSLiftParameter(param0IsSome, param0CaseId)) + #else fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func _extern_isEven(_ jsObject: Int32) -> Int32 { - return _extern_isEven_extern(jsObject) + #endif } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_processGreeter") -fileprivate func _extern_processGreeter_extern(_ jsObject: Int32, _ greeter: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void #else -fileprivate func _extern_processGreeter_extern(_ jsObject: Int32, _ greeter: UnsafeMutableRawPointer) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _extern_processGreeter(_ jsObject: Int32, _ greeter: UnsafeMutableRawPointer) -> Int32 { - return _extern_processGreeter_extern(jsObject, greeter) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y(_ callback: Int32, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y_extern(callback, param0IsSome, param0Bytes, param0Length) } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_createGreeter") -fileprivate func _extern_createGreeter_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func _extern_createGreeter_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _extern_createGreeter(_ jsObject: Int32) -> UnsafeMutableRawPointer { - return _extern_createGreeter_extern(jsObject) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y_extern(boxPtr, file, line) } -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_processOptionalGreeter") -fileprivate func _extern_processOptionalGreeter_extern(_ jsObject: Int32, _ greeterIsSome: Int32, _ greeterPointer: UnsafeMutableRawPointer) -> Int32 -#else -fileprivate func _extern_processOptionalGreeter_extern(_ jsObject: Int32, _ greeterIsSome: Int32, _ greeterPointer: UnsafeMutableRawPointer) -> Int32 { - fatalError("Only available on WebAssembly") +private enum _BJS_Closure_20BridgeJSRuntimeTestssSqSS_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending Optional) -> Void { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + param0.bridgeJSWithLoweredParameter { (param0IsSome, param0Bytes, param0Length) in + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y(callbackValue, param0IsSome, param0Bytes, param0Length) + } + #else + fatalError("Only available on WebAssembly") + #endif + } + } } -#endif -@inline(never) fileprivate func _extern_processOptionalGreeter(_ jsObject: Int32, _ greeterIsSome: Int32, _ greeterPointer: UnsafeMutableRawPointer) -> Int32 { - return _extern_processOptionalGreeter_extern(jsObject, greeterIsSome, greeterPointer) + +extension JSTypedClosure where Signature == (sending Optional) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Optional) -> Void) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y, + body: body, + fileID: fileID, + line: line + ) + } } -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_createOptionalGreeter") -fileprivate func _extern_createOptionalGreeter_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer -#else -fileprivate func _extern_createOptionalGreeter_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Bytes: Int32, _ param0Length: Int32) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending Optional) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Bytes, param0Length)) + #else fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func _extern_createOptionalGreeter(_ jsObject: Int32) -> UnsafeMutableRawPointer { - return _extern_createOptionalGreeter_extern(jsObject) + #endif } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_handleAPIResult") -fileprivate func _extern_handleAPIResult_extern(_ jsObject: Int32, _ resultIsSome: Int32, _ resultCaseId: Int32) -> Void +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Float64) -> Void #else -fileprivate func _extern_handleAPIResult_extern(_ jsObject: Int32, _ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y_extern(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Float64) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _extern_handleAPIResult(_ jsObject: Int32, _ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { - return _extern_handleAPIResult_extern(jsObject, resultIsSome, resultCaseId) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y(_ callback: Int32, _ param0IsSome: Int32, _ param0Value: Float64) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y_extern(callback, param0IsSome, param0Value) } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_getAPIResult") -fileprivate func _extern_getAPIResult_extern(_ jsObject: Int32) -> Int32 +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func _extern_getAPIResult_extern(_ jsObject: Int32) -> Int32 { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _extern_getAPIResult(_ jsObject: Int32) -> Int32 { - return _extern_getAPIResult_extern(jsObject) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y_extern(boxPtr, file, line) } -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_count_get") -fileprivate func bjs_DataProcessor_count_get_extern(_ jsObject: Int32) -> Int32 -#else -fileprivate func bjs_DataProcessor_count_get_extern(_ jsObject: Int32) -> Int32 { - fatalError("Only available on WebAssembly") +private enum _BJS_Closure_20BridgeJSRuntimeTestssSqSd_y { + static func bridgeJSLift(_ callbackId: Int32) -> (sending Optional) -> Void { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let (param0IsSome, param0Value) = param0.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y(callbackValue, param0IsSome, param0Value) + #else + fatalError("Only available on WebAssembly") + #endif + } + } } -#endif -@inline(never) fileprivate func bjs_DataProcessor_count_get(_ jsObject: Int32) -> Int32 { - return bjs_DataProcessor_count_get_extern(jsObject) + +extension JSTypedClosure where Signature == (sending Optional) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (sending Optional) -> Void) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y, + body: body, + fileID: fileID, + line: line + ) + } } -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_count_set") -fileprivate func bjs_DataProcessor_count_set_extern(_ jsObject: Int32, _ newValue: Int32) -> Void -#else -fileprivate func bjs_DataProcessor_count_set_extern(_ jsObject: Int32, _ newValue: Int32) -> Void { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y(_ boxPtr: UnsafeMutableRawPointer, _ param0IsSome: Int32, _ param0Value: Float64) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(sending Optional) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(Optional.bridgeJSLiftParameter(param0IsSome, param0Value)) + #else fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func bjs_DataProcessor_count_set(_ jsObject: Int32, _ newValue: Int32) -> Void { - return bjs_DataProcessor_count_set_extern(jsObject, newValue) + #endif } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_name_get") -fileprivate func bjs_DataProcessor_name_get_extern(_ jsObject: Int32) -> Int32 +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP_extern(_ callback: Int32) -> Int32 #else -fileprivate func bjs_DataProcessor_name_get_extern(_ jsObject: Int32) -> Int32 { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP_extern(_ callback: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_DataProcessor_name_get(_ jsObject: Int32) -> Int32 { - return bjs_DataProcessor_name_get_extern(jsObject) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP(_ callback: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP_extern(callback) } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_optionalTag_get") -fileprivate func bjs_DataProcessor_optionalTag_get_extern(_ jsObject: Int32) -> Void +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func bjs_DataProcessor_optionalTag_get_extern(_ jsObject: Int32) -> Void { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_DataProcessor_optionalTag_get(_ jsObject: Int32) -> Void { - return bjs_DataProcessor_optionalTag_get_extern(jsObject) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestsy_13DataProcessorP { + static func bridgeJSLift(_ callbackId: Int32) -> () -> any DataProcessor { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP(callbackValue) + return AnyDataProcessor.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == () -> any DataProcessor { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping () -> any DataProcessor) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_13DataProcessorP(_ boxPtr: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<() -> any DataProcessor>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure() + return (result as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn() + #else + fatalError("Only available on WebAssembly") + #endif } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_optionalTag_set") -fileprivate func bjs_DataProcessor_optionalTag_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb_extern(_ callback: Int32) -> Int32 #else -fileprivate func bjs_DataProcessor_optionalTag_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb_extern(_ callback: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_DataProcessor_optionalTag_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { - return bjs_DataProcessor_optionalTag_set_extern(jsObject, newValueIsSome, newValueBytes, newValueLength) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb(_ callback: Int32) -> Int32 { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb_extern(callback) } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_optionalCount_get") -fileprivate func bjs_DataProcessor_optionalCount_get_extern(_ jsObject: Int32) -> Void +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func bjs_DataProcessor_optionalCount_get_extern(_ jsObject: Int32) -> Void { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_DataProcessor_optionalCount_get(_ jsObject: Int32) -> Void { - return bjs_DataProcessor_optionalCount_get_extern(jsObject) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTestsy_Sb { + static func bridgeJSLift(_ callbackId: Int32) -> () -> Bool { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb(callbackValue) + return Bool.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == () -> Bool { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping () -> Bool) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sb(_ boxPtr: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<() -> Bool>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure() + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_optionalCount_set") -fileprivate func bjs_DataProcessor_optionalCount_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC_extern(_ callback: Int32) -> UnsafeMutableRawPointer #else -fileprivate func bjs_DataProcessor_optionalCount_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC_extern(_ callback: Int32) -> UnsafeMutableRawPointer { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_DataProcessor_optionalCount_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { - return bjs_DataProcessor_optionalCount_set_extern(jsObject, newValueIsSome, newValueValue) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC(_ callback: Int32) -> UnsafeMutableRawPointer { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC_extern(callback) } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_direction_get") -fileprivate func bjs_DataProcessor_direction_get_extern(_ jsObject: Int32) -> Int32 +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func bjs_DataProcessor_direction_get_extern(_ jsObject: Int32) -> Int32 { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_DataProcessor_direction_get(_ jsObject: Int32) -> Int32 { - return bjs_DataProcessor_direction_get_extern(jsObject) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC_extern(boxPtr, file, line) } -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_direction_set") -fileprivate func bjs_DataProcessor_direction_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void -#else -fileprivate func bjs_DataProcessor_direction_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func bjs_DataProcessor_direction_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { - return bjs_DataProcessor_direction_set_extern(jsObject, newValueIsSome, newValueValue) +private enum _BJS_Closure_20BridgeJSRuntimeTestsy_Sq7GreeterC { + static func bridgeJSLift(_ callbackId: Int32) -> () -> Optional { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC(callbackValue) + return Optional.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } } -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_optionalTheme_get") -fileprivate func bjs_DataProcessor_optionalTheme_get_extern(_ jsObject: Int32) -> Void -#else -fileprivate func bjs_DataProcessor_optionalTheme_get_extern(_ jsObject: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func bjs_DataProcessor_optionalTheme_get(_ jsObject: Int32) -> Void { - return bjs_DataProcessor_optionalTheme_get_extern(jsObject) +extension JSTypedClosure where Signature == () -> Optional { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping () -> Optional) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC, + body: body, + fileID: fileID, + line: line + ) + } } -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_optionalTheme_set") -fileprivate func bjs_DataProcessor_optionalTheme_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void -#else -fileprivate func bjs_DataProcessor_optionalTheme_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_Sq7GreeterC(_ boxPtr: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<() -> Optional>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure() + return result.bridgeJSLowerReturn() + #else fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func bjs_DataProcessor_optionalTheme_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { - return bjs_DataProcessor_optionalTheme_set_extern(jsObject, newValueIsSome, newValueBytes, newValueLength) + #endif } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_httpStatus_get") -fileprivate func bjs_DataProcessor_httpStatus_get_extern(_ jsObject: Int32) -> Void +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y_extern(_ callback: Int32) -> Void #else -fileprivate func bjs_DataProcessor_httpStatus_get_extern(_ jsObject: Int32) -> Void { +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y_extern(_ callback: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_DataProcessor_httpStatus_get(_ jsObject: Int32) -> Void { - return bjs_DataProcessor_httpStatus_get_extern(jsObject) +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y(_ callback: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y_extern(callback) } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_httpStatus_set") -fileprivate func bjs_DataProcessor_httpStatus_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func bjs_DataProcessor_httpStatus_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_DataProcessor_httpStatus_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { - return bjs_DataProcessor_httpStatus_set_extern(jsObject, newValueIsSome, newValueValue) +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y_extern(boxPtr, file, line) } -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_apiResult_get") -fileprivate func bjs_DataProcessor_apiResult_get_extern(_ jsObject: Int32) -> Int32 -#else -fileprivate func bjs_DataProcessor_apiResult_get_extern(_ jsObject: Int32) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func bjs_DataProcessor_apiResult_get(_ jsObject: Int32) -> Int32 { - return bjs_DataProcessor_apiResult_get_extern(jsObject) +private enum _BJS_Closure_20BridgeJSRuntimeTestsy_y { + static func bridgeJSLift(_ callbackId: Int32) -> () -> Void { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] in + #if arch(wasm32) + let callbackValue = callback.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y(callbackValue) + #else + fatalError("Only available on WebAssembly") + #endif + } + } } -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_apiResult_set") -fileprivate func bjs_DataProcessor_apiResult_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueCaseId: Int32) -> Void -#else -fileprivate func bjs_DataProcessor_apiResult_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueCaseId: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func bjs_DataProcessor_apiResult_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueCaseId: Int32) -> Void { - return bjs_DataProcessor_apiResult_set_extern(jsObject, newValueIsSome, newValueCaseId) +extension JSTypedClosure where Signature == () -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping () -> Void) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y, + body: body, + fileID: fileID, + line: line + ) + } } -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_helper_get") -fileprivate func bjs_DataProcessor_helper_get_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer -#else -fileprivate func bjs_DataProcessor_helper_get_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer { +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsy_y(_ boxPtr: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<() -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure() + #else fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func bjs_DataProcessor_helper_get(_ jsObject: Int32) -> UnsafeMutableRawPointer { - return bjs_DataProcessor_helper_get_extern(jsObject) + #endif } -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_helper_set") -fileprivate func bjs_DataProcessor_helper_set_extern(_ jsObject: Int32, _ newValue: UnsafeMutableRawPointer) -> Void -#else -fileprivate func bjs_DataProcessor_helper_set_extern(_ jsObject: Int32, _ newValue: UnsafeMutableRawPointer) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func bjs_DataProcessor_helper_set(_ jsObject: Int32, _ newValue: UnsafeMutableRawPointer) -> Void { - return bjs_DataProcessor_helper_set_extern(jsObject, newValue) +struct AnyArrayElementProtocol: ArrayElementProtocol, _BridgedSwiftProtocolWrapper { + let jsObject: JSObject + + var value: Int { + get { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let ret = bjs_ArrayElementProtocol_value_get(jsObjectValue) + return Int.bridgeJSLiftReturn(ret) + } + set { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let newValueValue = newValue.bridgeJSLowerParameter() + bjs_ArrayElementProtocol_value_set(jsObjectValue, newValueValue) + } + } + + static func bridgeJSLiftParameter(_ value: Int32) -> Self { + return AnyArrayElementProtocol(jsObject: JSObject(id: UInt32(bitPattern: value))) + } } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_optionalHelper_get") -fileprivate func bjs_DataProcessor_optionalHelper_get_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ArrayElementProtocol_value_get") +fileprivate func bjs_ArrayElementProtocol_value_get_extern(_ jsObject: Int32) -> Int32 #else -fileprivate func bjs_DataProcessor_optionalHelper_get_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer { +fileprivate func bjs_ArrayElementProtocol_value_get_extern(_ jsObject: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_DataProcessor_optionalHelper_get(_ jsObject: Int32) -> UnsafeMutableRawPointer { - return bjs_DataProcessor_optionalHelper_get_extern(jsObject) +@inline(never) fileprivate func bjs_ArrayElementProtocol_value_get(_ jsObject: Int32) -> Int32 { + return bjs_ArrayElementProtocol_value_get_extern(jsObject) } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_optionalHelper_set") -fileprivate func bjs_DataProcessor_optionalHelper_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValuePointer: UnsafeMutableRawPointer) -> Void +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ArrayElementProtocol_value_set") +fileprivate func bjs_ArrayElementProtocol_value_set_extern(_ jsObject: Int32, _ newValue: Int32) -> Void #else -fileprivate func bjs_DataProcessor_optionalHelper_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValuePointer: UnsafeMutableRawPointer) -> Void { +fileprivate func bjs_ArrayElementProtocol_value_set_extern(_ jsObject: Int32, _ newValue: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_DataProcessor_optionalHelper_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValuePointer: UnsafeMutableRawPointer) -> Void { - return bjs_DataProcessor_optionalHelper_set_extern(jsObject, newValueIsSome, newValuePointer) +@inline(never) fileprivate func bjs_ArrayElementProtocol_value_set(_ jsObject: Int32, _ newValue: Int32) -> Void { + return bjs_ArrayElementProtocol_value_set_extern(jsObject, newValue) } -extension Severity: _BridgedSwiftCaseEnum { - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { - return bridgeJSRawValue - } - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> Severity { - return bridgeJSLiftParameter(value) - } - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> Severity { - return Severity(bridgeJSRawValue: value)! +struct AnyDataProcessor: DataProcessor, _BridgedSwiftProtocolWrapper { + let jsObject: JSObject + + func increment(by amount: Int) -> Void { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let amountValue = amount.bridgeJSLowerParameter() + _extern_increment(jsObjectValue, amountValue) } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { - return bridgeJSLowerParameter() + + func getValue() -> Int { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let ret = _extern_getValue(jsObjectValue) + return Int.bridgeJSLiftReturn(ret) } - @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { - switch bridgeJSRawValue { - case 0: - self = .notice - case 1: - self = .warning - case 2: - self = .error - default: - return nil + func setLabelElements(_ labelPrefix: String, _ labelSuffix: String) -> Void { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + labelPrefix.bridgeJSWithLoweredParameter { (labelPrefixBytes, labelPrefixLength) in + labelSuffix.bridgeJSWithLoweredParameter { (labelSuffixBytes, labelSuffixLength) in + _extern_setLabelElements(jsObjectValue, labelPrefixBytes, labelPrefixLength, labelSuffixBytes, labelSuffixLength) + } } } - @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { - switch self { - case .notice: - return 0 - case .warning: - return 1 - case .error: - return 2 - } + func getLabel() -> String { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let ret = _extern_getLabel(jsObjectValue) + return String.bridgeJSLiftReturn(ret) } -} -extension Shape: _BridgedSwiftAssociatedValueEnum { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> Shape { - switch caseId { - case 0: - return .polygon(Polygon.bridgeFromJS(PolygonReference.bridgeJSStackPop())) - case 1: - return .empty - default: - fatalError("Unknown Shape case ID: \(caseId)") - } + func isEven() -> Bool { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let ret = _extern_isEven(jsObjectValue) + return Bool.bridgeJSLiftReturn(ret) + } + + func processGreeter(_ greeter: Greeter) -> String { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let greeterPointer = greeter.bridgeJSLowerParameter() + let ret = _extern_processGreeter(jsObjectValue, greeterPointer) + return String.bridgeJSLiftReturn(ret) + } + + func createGreeter() -> Greeter { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let ret = _extern_createGreeter(jsObjectValue) + return Greeter.bridgeJSLiftReturn(ret) + } + + func processOptionalGreeter(_ greeter: Optional) -> String { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let (greeterIsSome, greeterPointer) = greeter.bridgeJSLowerParameter() + let ret = _extern_processOptionalGreeter(jsObjectValue, greeterIsSome, greeterPointer) + return String.bridgeJSLiftReturn(ret) + } + + func createOptionalGreeter() -> Optional { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let ret = _extern_createOptionalGreeter(jsObjectValue) + return Optional.bridgeJSLiftReturn(ret) + } + + func handleAPIResult(_ result: Optional) -> Void { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let (resultIsSome, resultCaseId) = result.bridgeJSLowerParameter() + _extern_handleAPIResult(jsObjectValue, resultIsSome, resultCaseId) + } + + func getAPIResult() -> Optional { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let ret = _extern_getAPIResult(jsObjectValue) + return Optional.bridgeJSLiftReturn(ret) + } + + var count: Int { + get { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let ret = bjs_DataProcessor_count_get(jsObjectValue) + return Int.bridgeJSLiftReturn(ret) + } + set { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let newValueValue = newValue.bridgeJSLowerParameter() + bjs_DataProcessor_count_set(jsObjectValue, newValueValue) + } + } + + var name: String { + get { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let ret = bjs_DataProcessor_name_get(jsObjectValue) + return String.bridgeJSLiftReturn(ret) + } + } + + var optionalTag: Optional { + get { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + bjs_DataProcessor_optionalTag_get(jsObjectValue) + return Optional.bridgeJSLiftReturnFromSideChannel() + } + set { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + newValue.bridgeJSWithLoweredParameter { (newValueIsSome, newValueBytes, newValueLength) in + bjs_DataProcessor_optionalTag_set(jsObjectValue, newValueIsSome, newValueBytes, newValueLength) + } + } + } + + var optionalCount: Optional { + get { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + bjs_DataProcessor_optionalCount_get(jsObjectValue) + return Optional.bridgeJSLiftReturnFromSideChannel() + } + set { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let (newValueIsSome, newValueValue) = newValue.bridgeJSLowerParameter() + bjs_DataProcessor_optionalCount_set(jsObjectValue, newValueIsSome, newValueValue) + } + } + + var direction: Optional { + get { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let ret = bjs_DataProcessor_direction_get(jsObjectValue) + return Optional.bridgeJSLiftReturn(ret) + } + set { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let (newValueIsSome, newValueValue) = newValue.bridgeJSLowerParameter() + bjs_DataProcessor_direction_set(jsObjectValue, newValueIsSome, newValueValue) + } + } + + var optionalTheme: Optional { + get { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + bjs_DataProcessor_optionalTheme_get(jsObjectValue) + return Optional.bridgeJSLiftReturnFromSideChannel() + } + set { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + newValue.bridgeJSWithLoweredParameter { (newValueIsSome, newValueBytes, newValueLength) in + bjs_DataProcessor_optionalTheme_set(jsObjectValue, newValueIsSome, newValueBytes, newValueLength) + } + } + } + + var httpStatus: Optional { + get { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + bjs_DataProcessor_httpStatus_get(jsObjectValue) + return Optional.bridgeJSLiftReturnFromSideChannel() + } + set { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let (newValueIsSome, newValueValue) = newValue.bridgeJSLowerParameter() + bjs_DataProcessor_httpStatus_set(jsObjectValue, newValueIsSome, newValueValue) + } + } + + var apiResult: Optional { + get { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let ret = bjs_DataProcessor_apiResult_get(jsObjectValue) + return Optional.bridgeJSLiftReturn(ret) + } + set { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let (newValueIsSome, newValueCaseId) = newValue.bridgeJSLowerParameter() + bjs_DataProcessor_apiResult_set(jsObjectValue, newValueIsSome, newValueCaseId) + } + } + + var helper: Greeter { + get { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let ret = bjs_DataProcessor_helper_get(jsObjectValue) + return Greeter.bridgeJSLiftReturn(ret) + } + set { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let newValuePointer = newValue.bridgeJSLowerParameter() + bjs_DataProcessor_helper_set(jsObjectValue, newValuePointer) + } + } + + var optionalHelper: Optional { + get { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let ret = bjs_DataProcessor_optionalHelper_get(jsObjectValue) + return Optional.bridgeJSLiftReturn(ret) + } + set { + let jsObjectValue = jsObject.bridgeJSLowerParameter() + let (newValueIsSome, newValuePointer) = newValue.bridgeJSLowerParameter() + bjs_DataProcessor_optionalHelper_set(jsObjectValue, newValueIsSome, newValuePointer) + } + } + + static func bridgeJSLiftParameter(_ value: Int32) -> Self { + return AnyDataProcessor(jsObject: JSObject(id: UInt32(bitPattern: value))) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_increment") +fileprivate func _extern_increment_extern(_ jsObject: Int32, _ amount: Int32) -> Void +#else +fileprivate func _extern_increment_extern(_ jsObject: Int32, _ amount: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_increment(_ jsObject: Int32, _ amount: Int32) -> Void { + return _extern_increment_extern(jsObject, amount) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_getValue") +fileprivate func _extern_getValue_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func _extern_getValue_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_getValue(_ jsObject: Int32) -> Int32 { + return _extern_getValue_extern(jsObject) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_setLabelElements") +fileprivate func _extern_setLabelElements_extern(_ jsObject: Int32, _ labelPrefixBytes: Int32, _ labelPrefixLength: Int32, _ labelSuffixBytes: Int32, _ labelSuffixLength: Int32) -> Void +#else +fileprivate func _extern_setLabelElements_extern(_ jsObject: Int32, _ labelPrefixBytes: Int32, _ labelPrefixLength: Int32, _ labelSuffixBytes: Int32, _ labelSuffixLength: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_setLabelElements(_ jsObject: Int32, _ labelPrefixBytes: Int32, _ labelPrefixLength: Int32, _ labelSuffixBytes: Int32, _ labelSuffixLength: Int32) -> Void { + return _extern_setLabelElements_extern(jsObject, labelPrefixBytes, labelPrefixLength, labelSuffixBytes, labelSuffixLength) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_getLabel") +fileprivate func _extern_getLabel_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func _extern_getLabel_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_getLabel(_ jsObject: Int32) -> Int32 { + return _extern_getLabel_extern(jsObject) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_isEven") +fileprivate func _extern_isEven_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func _extern_isEven_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_isEven(_ jsObject: Int32) -> Int32 { + return _extern_isEven_extern(jsObject) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_processGreeter") +fileprivate func _extern_processGreeter_extern(_ jsObject: Int32, _ greeter: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _extern_processGreeter_extern(_ jsObject: Int32, _ greeter: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_processGreeter(_ jsObject: Int32, _ greeter: UnsafeMutableRawPointer) -> Int32 { + return _extern_processGreeter_extern(jsObject, greeter) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_createGreeter") +fileprivate func _extern_createGreeter_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer +#else +fileprivate func _extern_createGreeter_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_createGreeter(_ jsObject: Int32) -> UnsafeMutableRawPointer { + return _extern_createGreeter_extern(jsObject) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_processOptionalGreeter") +fileprivate func _extern_processOptionalGreeter_extern(_ jsObject: Int32, _ greeterIsSome: Int32, _ greeterPointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _extern_processOptionalGreeter_extern(_ jsObject: Int32, _ greeterIsSome: Int32, _ greeterPointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_processOptionalGreeter(_ jsObject: Int32, _ greeterIsSome: Int32, _ greeterPointer: UnsafeMutableRawPointer) -> Int32 { + return _extern_processOptionalGreeter_extern(jsObject, greeterIsSome, greeterPointer) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_createOptionalGreeter") +fileprivate func _extern_createOptionalGreeter_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer +#else +fileprivate func _extern_createOptionalGreeter_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_createOptionalGreeter(_ jsObject: Int32) -> UnsafeMutableRawPointer { + return _extern_createOptionalGreeter_extern(jsObject) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_handleAPIResult") +fileprivate func _extern_handleAPIResult_extern(_ jsObject: Int32, _ resultIsSome: Int32, _ resultCaseId: Int32) -> Void +#else +fileprivate func _extern_handleAPIResult_extern(_ jsObject: Int32, _ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_handleAPIResult(_ jsObject: Int32, _ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { + return _extern_handleAPIResult_extern(jsObject, resultIsSome, resultCaseId) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_getAPIResult") +fileprivate func _extern_getAPIResult_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func _extern_getAPIResult_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _extern_getAPIResult(_ jsObject: Int32) -> Int32 { + return _extern_getAPIResult_extern(jsObject) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_count_get") +fileprivate func bjs_DataProcessor_count_get_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func bjs_DataProcessor_count_get_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_count_get(_ jsObject: Int32) -> Int32 { + return bjs_DataProcessor_count_get_extern(jsObject) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_count_set") +fileprivate func bjs_DataProcessor_count_set_extern(_ jsObject: Int32, _ newValue: Int32) -> Void +#else +fileprivate func bjs_DataProcessor_count_set_extern(_ jsObject: Int32, _ newValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_count_set(_ jsObject: Int32, _ newValue: Int32) -> Void { + return bjs_DataProcessor_count_set_extern(jsObject, newValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_name_get") +fileprivate func bjs_DataProcessor_name_get_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func bjs_DataProcessor_name_get_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_name_get(_ jsObject: Int32) -> Int32 { + return bjs_DataProcessor_name_get_extern(jsObject) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_optionalTag_get") +fileprivate func bjs_DataProcessor_optionalTag_get_extern(_ jsObject: Int32) -> Void +#else +fileprivate func bjs_DataProcessor_optionalTag_get_extern(_ jsObject: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_optionalTag_get(_ jsObject: Int32) -> Void { + return bjs_DataProcessor_optionalTag_get_extern(jsObject) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_optionalTag_set") +fileprivate func bjs_DataProcessor_optionalTag_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void +#else +fileprivate func bjs_DataProcessor_optionalTag_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_optionalTag_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { + return bjs_DataProcessor_optionalTag_set_extern(jsObject, newValueIsSome, newValueBytes, newValueLength) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_optionalCount_get") +fileprivate func bjs_DataProcessor_optionalCount_get_extern(_ jsObject: Int32) -> Void +#else +fileprivate func bjs_DataProcessor_optionalCount_get_extern(_ jsObject: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_optionalCount_get(_ jsObject: Int32) -> Void { + return bjs_DataProcessor_optionalCount_get_extern(jsObject) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_optionalCount_set") +fileprivate func bjs_DataProcessor_optionalCount_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +#else +fileprivate func bjs_DataProcessor_optionalCount_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_optionalCount_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + return bjs_DataProcessor_optionalCount_set_extern(jsObject, newValueIsSome, newValueValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_direction_get") +fileprivate func bjs_DataProcessor_direction_get_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func bjs_DataProcessor_direction_get_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_direction_get(_ jsObject: Int32) -> Int32 { + return bjs_DataProcessor_direction_get_extern(jsObject) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_direction_set") +fileprivate func bjs_DataProcessor_direction_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +#else +fileprivate func bjs_DataProcessor_direction_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_direction_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + return bjs_DataProcessor_direction_set_extern(jsObject, newValueIsSome, newValueValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_optionalTheme_get") +fileprivate func bjs_DataProcessor_optionalTheme_get_extern(_ jsObject: Int32) -> Void +#else +fileprivate func bjs_DataProcessor_optionalTheme_get_extern(_ jsObject: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_optionalTheme_get(_ jsObject: Int32) -> Void { + return bjs_DataProcessor_optionalTheme_get_extern(jsObject) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_optionalTheme_set") +fileprivate func bjs_DataProcessor_optionalTheme_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void +#else +fileprivate func bjs_DataProcessor_optionalTheme_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_optionalTheme_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueBytes: Int32, _ newValueLength: Int32) -> Void { + return bjs_DataProcessor_optionalTheme_set_extern(jsObject, newValueIsSome, newValueBytes, newValueLength) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_httpStatus_get") +fileprivate func bjs_DataProcessor_httpStatus_get_extern(_ jsObject: Int32) -> Void +#else +fileprivate func bjs_DataProcessor_httpStatus_get_extern(_ jsObject: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_httpStatus_get(_ jsObject: Int32) -> Void { + return bjs_DataProcessor_httpStatus_get_extern(jsObject) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_httpStatus_set") +fileprivate func bjs_DataProcessor_httpStatus_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void +#else +fileprivate func bjs_DataProcessor_httpStatus_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_httpStatus_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueValue: Int32) -> Void { + return bjs_DataProcessor_httpStatus_set_extern(jsObject, newValueIsSome, newValueValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_apiResult_get") +fileprivate func bjs_DataProcessor_apiResult_get_extern(_ jsObject: Int32) -> Int32 +#else +fileprivate func bjs_DataProcessor_apiResult_get_extern(_ jsObject: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_apiResult_get(_ jsObject: Int32) -> Int32 { + return bjs_DataProcessor_apiResult_get_extern(jsObject) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_apiResult_set") +fileprivate func bjs_DataProcessor_apiResult_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueCaseId: Int32) -> Void +#else +fileprivate func bjs_DataProcessor_apiResult_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueCaseId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_apiResult_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValueCaseId: Int32) -> Void { + return bjs_DataProcessor_apiResult_set_extern(jsObject, newValueIsSome, newValueCaseId) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_helper_get") +fileprivate func bjs_DataProcessor_helper_get_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer +#else +fileprivate func bjs_DataProcessor_helper_get_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_helper_get(_ jsObject: Int32) -> UnsafeMutableRawPointer { + return bjs_DataProcessor_helper_get_extern(jsObject) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_helper_set") +fileprivate func bjs_DataProcessor_helper_set_extern(_ jsObject: Int32, _ newValue: UnsafeMutableRawPointer) -> Void +#else +fileprivate func bjs_DataProcessor_helper_set_extern(_ jsObject: Int32, _ newValue: UnsafeMutableRawPointer) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_helper_set(_ jsObject: Int32, _ newValue: UnsafeMutableRawPointer) -> Void { + return bjs_DataProcessor_helper_set_extern(jsObject, newValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_optionalHelper_get") +fileprivate func bjs_DataProcessor_optionalHelper_get_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer +#else +fileprivate func bjs_DataProcessor_optionalHelper_get_extern(_ jsObject: Int32) -> UnsafeMutableRawPointer { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_optionalHelper_get(_ jsObject: Int32) -> UnsafeMutableRawPointer { + return bjs_DataProcessor_optionalHelper_get_extern(jsObject) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessor_optionalHelper_set") +fileprivate func bjs_DataProcessor_optionalHelper_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValuePointer: UnsafeMutableRawPointer) -> Void +#else +fileprivate func bjs_DataProcessor_optionalHelper_set_extern(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValuePointer: UnsafeMutableRawPointer) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_DataProcessor_optionalHelper_set(_ jsObject: Int32, _ newValueIsSome: Int32, _ newValuePointer: UnsafeMutableRawPointer) -> Void { + return bjs_DataProcessor_optionalHelper_set_extern(jsObject, newValueIsSome, newValuePointer) +} + +extension Severity: _BridgedSwiftCaseEnum { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + return bridgeJSRawValue + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> Severity { + return bridgeJSLiftParameter(value) + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> Severity { + return Severity(bridgeJSRawValue: value)! + } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { + return bridgeJSLowerParameter() + } + + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { + switch bridgeJSRawValue { + case 0: + self = .notice + case 1: + self = .warning + case 2: + self = .error + default: + return nil + } + } + + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { + switch self { + case .notice: + return 0 + case .warning: + return 1 + case .error: + return 2 + } + } +} + +extension Shape: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> Shape { + switch caseId { + case 0: + return .polygon(Polygon.bridgeJSStackPop()) + case 1: + return .empty + default: + fatalError("Unknown Shape case ID: \(caseId)") + } } @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { switch self { case .polygon(let param0): - param0.bridgeToJS().bridgeJSStackPush() + param0.bridgeJSStackPush() return Int32(0) case .empty: return Int32(1) @@ -3964,6 +4726,34 @@ public func _bjs_ArraySupportExports_static_multiOptionalArraySecond() -> Void { #endif } +extension AsyncImportedPayloadResult: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> AsyncImportedPayloadResult { + switch caseId { + case 0: + return .success(String.bridgeJSStackPop()) + case 1: + return .failure(Int.bridgeJSStackPop()) + case 2: + return .idle + default: + fatalError("Unknown AsyncImportedPayloadResult case ID: \(caseId)") + } + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { + switch self { + case .success(let param0): + param0.bridgeJSStackPush() + return Int32(0) + case .failure(let param0): + param0.bridgeJSStackPush() + return Int32(1) + case .idle: + return Int32(2) + } + } +} + @_expose(wasm, "bjs_DefaultArgumentExports_static_testStringDefault") @_cdecl("bjs_DefaultArgumentExports_static_testStringDefault") public func _bjs_DefaultArgumentExports_static_testStringDefault(_ messageBytes: Int32, _ messageLength: Int32) -> Void { @@ -4052,192 +4842,621 @@ public func _bjs_DefaultArgumentExports_static_testRawStringEnumDefault(_ themeB #endif } -@_expose(wasm, "bjs_DefaultArgumentExports_static_testComplexInit") -@_cdecl("bjs_DefaultArgumentExports_static_testComplexInit") -public func _bjs_DefaultArgumentExports_static_testComplexInit(_ greeter: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let ret = DefaultArgumentExports.testComplexInit(greeter: Greeter.bridgeJSLiftParameter(greeter)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} +@_expose(wasm, "bjs_DefaultArgumentExports_static_testComplexInit") +@_cdecl("bjs_DefaultArgumentExports_static_testComplexInit") +public func _bjs_DefaultArgumentExports_static_testComplexInit(_ greeter: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = DefaultArgumentExports.testComplexInit(greeter: Greeter.bridgeJSLiftParameter(greeter)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_DefaultArgumentExports_static_testEmptyInit") +@_cdecl("bjs_DefaultArgumentExports_static_testEmptyInit") +public func _bjs_DefaultArgumentExports_static_testEmptyInit(_ object: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = DefaultArgumentExports.testEmptyInit(_: StaticPropertyHolder.bridgeJSLiftParameter(object)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_DefaultArgumentExports_static_createConstructorDefaults") +@_cdecl("bjs_DefaultArgumentExports_static_createConstructorDefaults") +public func _bjs_DefaultArgumentExports_static_createConstructorDefaults(_ nameBytes: Int32, _ nameLength: Int32, _ count: Int32, _ enabled: Int32, _ status: Int32, _ tagIsSome: Int32, _ tagBytes: Int32, _ tagLength: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = DefaultArgumentExports.createConstructorDefaults(name: String.bridgeJSLiftParameter(nameBytes, nameLength), count: Int.bridgeJSLiftParameter(count), enabled: Bool.bridgeJSLiftParameter(enabled), status: Status.bridgeJSLiftParameter(status), tag: Optional.bridgeJSLiftParameter(tagIsSome, tagBytes, tagLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_DefaultArgumentExports_static_describeConstructorDefaults") +@_cdecl("bjs_DefaultArgumentExports_static_describeConstructorDefaults") +public func _bjs_DefaultArgumentExports_static_describeConstructorDefaults(_ value: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = DefaultArgumentExports.describeConstructorDefaults(_: DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(value)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_DefaultArgumentExports_static_arrayWithDefault") +@_cdecl("bjs_DefaultArgumentExports_static_arrayWithDefault") +public func _bjs_DefaultArgumentExports_static_arrayWithDefault() -> Int32 { + #if arch(wasm32) + let ret = DefaultArgumentExports.arrayWithDefault(_: [Int].bridgeJSStackPop()) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_DefaultArgumentExports_static_arrayWithOptionalDefault") +@_cdecl("bjs_DefaultArgumentExports_static_arrayWithOptionalDefault") +public func _bjs_DefaultArgumentExports_static_arrayWithOptionalDefault() -> Int32 { + #if arch(wasm32) + let ret = DefaultArgumentExports.arrayWithOptionalDefault(_: Optional<[Int]>.bridgeJSLiftParameter()) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_DefaultArgumentExports_static_arrayMixedDefaults") +@_cdecl("bjs_DefaultArgumentExports_static_arrayMixedDefaults") +public func _bjs_DefaultArgumentExports_static_arrayMixedDefaults(_ prefixBytes: Int32, _ prefixLength: Int32, _ suffixBytes: Int32, _ suffixLength: Int32) -> Void { + #if arch(wasm32) + let ret = DefaultArgumentExports.arrayMixedDefaults(prefix: String.bridgeJSLiftParameter(prefixBytes, prefixLength), values: [Int].bridgeJSStackPop(), suffix: String.bridgeJSLiftParameter(suffixBytes, suffixLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension Direction: _BridgedSwiftCaseEnum { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + return bridgeJSRawValue + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> Direction { + return bridgeJSLiftParameter(value) + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> Direction { + return Direction(bridgeJSRawValue: value)! + } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { + return bridgeJSLowerParameter() + } + + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { + switch bridgeJSRawValue { + case 0: + self = .north + case 1: + self = .south + case 2: + self = .east + case 3: + self = .west + default: + return nil + } + } + + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { + switch self { + case .north: + return 0 + case .south: + return 1 + case .east: + return 2 + case .west: + return 3 + } + } +} + +extension Status: _BridgedSwiftCaseEnum { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + return bridgeJSRawValue + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> Status { + return bridgeJSLiftParameter(value) + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> Status { + return Status(bridgeJSRawValue: value)! + } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { + return bridgeJSLowerParameter() + } + + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { + switch bridgeJSRawValue { + case 0: + self = .loading + case 1: + self = .success + case 2: + self = .error + default: + return nil + } + } + + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { + switch self { + case .loading: + return 0 + case .success: + return 1 + case .error: + return 2 + } + } +} + +extension Theme: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +} + +extension HttpStatus: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +} + +extension FileSize: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +} + +extension SessionId: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +} + +extension Precision: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +} + +extension Ratio: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +} + +extension TSDirection: _BridgedSwiftCaseEnum { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + return bridgeJSRawValue + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> TSDirection { + return bridgeJSLiftParameter(value) + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> TSDirection { + return TSDirection(bridgeJSRawValue: value)! + } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { + return bridgeJSLowerParameter() + } + + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { + switch bridgeJSRawValue { + case 0: + self = .north + case 1: + self = .south + case 2: + self = .east + case 3: + self = .west + default: + return nil + } + } + + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { + switch self { + case .north: + return 0 + case .south: + return 1 + case .east: + return 2 + case .west: + return 3 + } + } +} + +extension TSTheme: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +} + +extension AsyncPayloadResult: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> AsyncPayloadResult { + switch caseId { + case 0: + return .success(String.bridgeJSStackPop()) + case 1: + return .failure(Int.bridgeJSStackPop()) + case 2: + return .idle + default: + fatalError("Unknown AsyncPayloadResult case ID: \(caseId)") + } + } -@_expose(wasm, "bjs_DefaultArgumentExports_static_testEmptyInit") -@_cdecl("bjs_DefaultArgumentExports_static_testEmptyInit") -public func _bjs_DefaultArgumentExports_static_testEmptyInit(_ object: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { - #if arch(wasm32) - let ret = DefaultArgumentExports.testEmptyInit(_: StaticPropertyHolder.bridgeJSLiftParameter(object)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { + switch self { + case .success(let param0): + param0.bridgeJSStackPush() + return Int32(0) + case .failure(let param0): + param0.bridgeJSStackPush() + return Int32(1) + case .idle: + return Int32(2) + } + } } -@_expose(wasm, "bjs_DefaultArgumentExports_static_createConstructorDefaults") -@_cdecl("bjs_DefaultArgumentExports_static_createConstructorDefaults") -public func _bjs_DefaultArgumentExports_static_createConstructorDefaults(_ nameBytes: Int32, _ nameLength: Int32, _ count: Int32, _ enabled: Int32, _ status: Int32, _ tagIsSome: Int32, _ tagBytes: Int32, _ tagLength: Int32) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_Utils_StringUtils_static_uppercase") +@_cdecl("bjs_Utils_StringUtils_static_uppercase") +public func _bjs_Utils_StringUtils_static_uppercase(_ textBytes: Int32, _ textLength: Int32) -> Void { #if arch(wasm32) - let ret = DefaultArgumentExports.createConstructorDefaults(name: String.bridgeJSLiftParameter(nameBytes, nameLength), count: Int.bridgeJSLiftParameter(count), enabled: Bool.bridgeJSLiftParameter(enabled), status: Status.bridgeJSLiftParameter(status), tag: Optional.bridgeJSLiftParameter(tagIsSome, tagBytes, tagLength)) + let ret = Utils.StringUtils.uppercase(_: String.bridgeJSLiftParameter(textBytes, textLength)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DefaultArgumentExports_static_describeConstructorDefaults") -@_cdecl("bjs_DefaultArgumentExports_static_describeConstructorDefaults") -public func _bjs_DefaultArgumentExports_static_describeConstructorDefaults(_ value: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_Utils_StringUtils_static_lowercase") +@_cdecl("bjs_Utils_StringUtils_static_lowercase") +public func _bjs_Utils_StringUtils_static_lowercase(_ textBytes: Int32, _ textLength: Int32) -> Void { #if arch(wasm32) - let ret = DefaultArgumentExports.describeConstructorDefaults(_: DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(value)) + let ret = Utils.StringUtils.lowercase(_: String.bridgeJSLiftParameter(textBytes, textLength)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DefaultArgumentExports_static_arrayWithDefault") -@_cdecl("bjs_DefaultArgumentExports_static_arrayWithDefault") -public func _bjs_DefaultArgumentExports_static_arrayWithDefault() -> Int32 { - #if arch(wasm32) - let ret = DefaultArgumentExports.arrayWithDefault(_: [Int].bridgeJSStackPop()) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif +extension Networking.API.Method: _BridgedSwiftCaseEnum { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + return bridgeJSRawValue + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> Networking.API.Method { + return bridgeJSLiftParameter(value) + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> Networking.API.Method { + return Networking.API.Method(bridgeJSRawValue: value)! + } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { + return bridgeJSLowerParameter() + } + + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { + switch bridgeJSRawValue { + case 0: + self = .get + case 1: + self = .post + case 2: + self = .put + case 3: + self = .delete + default: + return nil + } + } + + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { + switch self { + case .get: + return 0 + case .post: + return 1 + case .put: + return 2 + case .delete: + return 3 + } + } } -@_expose(wasm, "bjs_DefaultArgumentExports_static_arrayWithOptionalDefault") -@_cdecl("bjs_DefaultArgumentExports_static_arrayWithOptionalDefault") -public func _bjs_DefaultArgumentExports_static_arrayWithOptionalDefault() -> Int32 { - #if arch(wasm32) - let ret = DefaultArgumentExports.arrayWithOptionalDefault(_: Optional<[Int]>.bridgeJSLiftParameter()) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif +extension Configuration.LogLevel: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } -@_expose(wasm, "bjs_DefaultArgumentExports_static_arrayMixedDefaults") -@_cdecl("bjs_DefaultArgumentExports_static_arrayMixedDefaults") -public func _bjs_DefaultArgumentExports_static_arrayMixedDefaults(_ prefixBytes: Int32, _ prefixLength: Int32, _ suffixBytes: Int32, _ suffixLength: Int32) -> Void { - #if arch(wasm32) - let ret = DefaultArgumentExports.arrayMixedDefaults(prefix: String.bridgeJSLiftParameter(prefixBytes, prefixLength), values: [Int].bridgeJSStackPop(), suffix: String.bridgeJSLiftParameter(suffixBytes, suffixLength)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif +extension Configuration.Port: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } -extension Direction: _BridgedSwiftCaseEnum { +extension Internal.SupportedMethod: _BridgedSwiftCaseEnum { @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { return bridgeJSRawValue } - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> Direction { + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> Internal.SupportedMethod { return bridgeJSLiftParameter(value) } - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> Direction { - return Direction(bridgeJSRawValue: value)! + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> Internal.SupportedMethod { + return Internal.SupportedMethod(bridgeJSRawValue: value)! } @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { return bridgeJSLowerParameter() } - @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { - switch bridgeJSRawValue { + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { + switch bridgeJSRawValue { + case 0: + self = .get + case 1: + self = .post + default: + return nil + } + } + + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { + switch self { + case .get: + return 0 + case .post: + return 1 + } + } +} + +extension APIResult: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> APIResult { + switch caseId { + case 0: + return .success(String.bridgeJSStackPop()) + case 1: + return .failure(Int.bridgeJSStackPop()) + case 2: + return .flag(Bool.bridgeJSStackPop()) + case 3: + return .rate(Float.bridgeJSStackPop()) + case 4: + return .precise(Double.bridgeJSStackPop()) + case 5: + return .info + default: + fatalError("Unknown APIResult case ID: \(caseId)") + } + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { + switch self { + case .success(let param0): + param0.bridgeJSStackPush() + return Int32(0) + case .failure(let param0): + param0.bridgeJSStackPush() + return Int32(1) + case .flag(let param0): + param0.bridgeJSStackPush() + return Int32(2) + case .rate(let param0): + param0.bridgeJSStackPush() + return Int32(3) + case .precise(let param0): + param0.bridgeJSStackPush() + return Int32(4) + case .info: + return Int32(5) + } + } +} + +extension ComplexResult: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> ComplexResult { + switch caseId { + case 0: + return .success(String.bridgeJSStackPop()) + case 1: + return .error(String.bridgeJSStackPop(), Int.bridgeJSStackPop()) + case 2: + return .location(Double.bridgeJSStackPop(), Double.bridgeJSStackPop(), String.bridgeJSStackPop()) + case 3: + return .status(Bool.bridgeJSStackPop(), Int.bridgeJSStackPop(), String.bridgeJSStackPop()) + case 4: + return .coordinates(Double.bridgeJSStackPop(), Double.bridgeJSStackPop(), Double.bridgeJSStackPop()) + case 5: + return .comprehensive(Bool.bridgeJSStackPop(), Bool.bridgeJSStackPop(), Int.bridgeJSStackPop(), Int.bridgeJSStackPop(), Double.bridgeJSStackPop(), Double.bridgeJSStackPop(), String.bridgeJSStackPop(), String.bridgeJSStackPop(), String.bridgeJSStackPop()) + case 6: + return .info + default: + fatalError("Unknown ComplexResult case ID: \(caseId)") + } + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { + switch self { + case .success(let param0): + param0.bridgeJSStackPush() + return Int32(0) + case .error(let param0, let param1): + param0.bridgeJSStackPush() + param1.bridgeJSStackPush() + return Int32(1) + case .location(let param0, let param1, let param2): + param0.bridgeJSStackPush() + param1.bridgeJSStackPush() + param2.bridgeJSStackPush() + return Int32(2) + case .status(let param0, let param1, let param2): + param0.bridgeJSStackPush() + param1.bridgeJSStackPush() + param2.bridgeJSStackPush() + return Int32(3) + case .coordinates(let param0, let param1, let param2): + param0.bridgeJSStackPush() + param1.bridgeJSStackPush() + param2.bridgeJSStackPush() + return Int32(4) + case .comprehensive(let param0, let param1, let param2, let param3, let param4, let param5, let param6, let param7, let param8): + param0.bridgeJSStackPush() + param1.bridgeJSStackPush() + param2.bridgeJSStackPush() + param3.bridgeJSStackPush() + param4.bridgeJSStackPush() + param5.bridgeJSStackPush() + param6.bridgeJSStackPush() + param7.bridgeJSStackPush() + param8.bridgeJSStackPush() + return Int32(5) + case .info: + return Int32(6) + } + } +} + +extension Utilities.Result: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> Utilities.Result { + switch caseId { case 0: - self = .north + return .success(String.bridgeJSStackPop()) case 1: - self = .south + return .failure(String.bridgeJSStackPop(), Int.bridgeJSStackPop()) case 2: - self = .east - case 3: - self = .west + return .status(Bool.bridgeJSStackPop(), Int.bridgeJSStackPop(), String.bridgeJSStackPop()) default: - return nil + fatalError("Unknown Utilities.Result case ID: \(caseId)") } } - @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { switch self { - case .north: - return 0 - case .south: - return 1 - case .east: - return 2 - case .west: - return 3 + case .success(let param0): + param0.bridgeJSStackPush() + return Int32(0) + case .failure(let param0, let param1): + param0.bridgeJSStackPush() + param1.bridgeJSStackPush() + return Int32(1) + case .status(let param0, let param1, let param2): + param0.bridgeJSStackPush() + param1.bridgeJSStackPush() + param2.bridgeJSStackPush() + return Int32(2) } } } -extension Status: _BridgedSwiftCaseEnum { - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { - return bridgeJSRawValue - } - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> Status { - return bridgeJSLiftParameter(value) - } - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> Status { - return Status(bridgeJSRawValue: value)! +extension API.NetworkingResult: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> API.NetworkingResult { + switch caseId { + case 0: + return .success(String.bridgeJSStackPop()) + case 1: + return .failure(String.bridgeJSStackPop(), Int.bridgeJSStackPop()) + default: + fatalError("Unknown API.NetworkingResult case ID: \(caseId)") + } } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { - return bridgeJSLowerParameter() + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { + switch self { + case .success(let param0): + param0.bridgeJSStackPush() + return Int32(0) + case .failure(let param0, let param1): + param0.bridgeJSStackPush() + param1.bridgeJSStackPush() + return Int32(1) + } } +} - @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { - switch bridgeJSRawValue { +extension AllTypesResult: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> AllTypesResult { + switch caseId { case 0: - self = .loading + return .structPayload(Address.bridgeJSStackPop()) case 1: - self = .success + return .classPayload(Greeter.bridgeJSStackPop()) case 2: - self = .error + return .jsObjectPayload(JSObject.bridgeJSStackPop()) + case 3: + return .nestedEnum(APIResult.bridgeJSStackPop()) + case 4: + return .arrayPayload([Int].bridgeJSStackPop()) + case 5: + return .jsClassPayload(Foo(unsafelyWrapping: JSObject.bridgeJSStackPop())) + case 6: + return .empty default: - return nil + fatalError("Unknown AllTypesResult case ID: \(caseId)") } } - @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { switch self { - case .loading: - return 0 - case .success: - return 1 - case .error: - return 2 + case .structPayload(let param0): + param0.bridgeJSStackPush() + return Int32(0) + case .classPayload(let param0): + param0.bridgeJSStackPush() + return Int32(1) + case .jsObjectPayload(let param0): + param0.bridgeJSStackPush() + return Int32(2) + case .nestedEnum(let param0): + param0.bridgeJSStackPush() + return Int32(3) + case .arrayPayload(let param0): + param0.bridgeJSStackPush() + return Int32(4) + case .jsClassPayload(let param0): + param0.jsObject.bridgeJSStackPush() + return Int32(5) + case .empty: + return Int32(6) } } } -extension Theme: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { -} - -extension HttpStatus: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { -} - -extension FileSize: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { -} - -extension SessionId: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { -} - -extension Precision: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { -} +extension TypedPayloadResult: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> TypedPayloadResult { + switch caseId { + case 0: + return .precision(Precision.bridgeJSStackPop()) + case 1: + return .direction(Direction.bridgeJSStackPop()) + case 2: + return .optPrecision(Optional.bridgeJSStackPop()) + case 3: + return .optDirection(Optional.bridgeJSStackPop()) + case 4: + return .empty + default: + fatalError("Unknown TypedPayloadResult case ID: \(caseId)") + } + } -extension Ratio: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { + switch self { + case .precision(let param0): + param0.bridgeJSStackPush() + return Int32(0) + case .direction(let param0): + param0.bridgeJSStackPush() + return Int32(1) + case .optPrecision(let param0): + param0.bridgeJSStackPush() + return Int32(2) + case .optDirection(let param0): + param0.bridgeJSStackPush() + return Int32(3) + case .empty: + return Int32(4) + } + } } -extension TSDirection: _BridgedSwiftCaseEnum { +extension StaticCalculator: _BridgedSwiftCaseEnum { @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { return bridgeJSRawValue } - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> TSDirection { + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> StaticCalculator { return bridgeJSLiftParameter(value) } - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> TSDirection { - return TSDirection(bridgeJSRawValue: value)! + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> StaticCalculator { + return StaticCalculator(bridgeJSRawValue: value)! } @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { return bridgeJSLowerParameter() @@ -4246,13 +5465,9 @@ extension TSDirection: _BridgedSwiftCaseEnum { @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { switch bridgeJSRawValue { case 0: - self = .north + self = .scientific case 1: - self = .south - case 2: - self = .east - case 3: - self = .west + self = .basic default: return nil } @@ -4260,52 +5475,89 @@ extension TSDirection: _BridgedSwiftCaseEnum { @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { switch self { - case .north: + case .scientific: return 0 - case .south: + case .basic: return 1 - case .east: - return 2 - case .west: - return 3 } } } -extension TSTheme: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +@_expose(wasm, "bjs_StaticCalculator_static_roundtrip") +@_cdecl("bjs_StaticCalculator_static_roundtrip") +public func _bjs_StaticCalculator_static_roundtrip(_ value: Int32) -> Int32 { + #if arch(wasm32) + let ret = StaticCalculator.roundtrip(_: Int.bridgeJSLiftParameter(value)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif } -@_expose(wasm, "bjs_Utils_StringUtils_static_uppercase") -@_cdecl("bjs_Utils_StringUtils_static_uppercase") -public func _bjs_Utils_StringUtils_static_uppercase(_ textBytes: Int32, _ textLength: Int32) -> Void { +@_expose(wasm, "bjs_StaticCalculator_static_doubleValue") +@_cdecl("bjs_StaticCalculator_static_doubleValue") +public func _bjs_StaticCalculator_static_doubleValue(_ value: Int32) -> Int32 { #if arch(wasm32) - let ret = Utils.StringUtils.uppercase(_: String.bridgeJSLiftParameter(textBytes, textLength)) + let ret = StaticCalculator.doubleValue(_: Int.bridgeJSLiftParameter(value)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_Utils_StringUtils_static_lowercase") -@_cdecl("bjs_Utils_StringUtils_static_lowercase") -public func _bjs_Utils_StringUtils_static_lowercase(_ textBytes: Int32, _ textLength: Int32) -> Void { +@_expose(wasm, "bjs_StaticCalculator_static_version_get") +@_cdecl("bjs_StaticCalculator_static_version_get") +public func _bjs_StaticCalculator_static_version_get() -> Void { #if arch(wasm32) - let ret = Utils.StringUtils.lowercase(_: String.bridgeJSLiftParameter(textBytes, textLength)) + let ret = StaticCalculator.version + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_StaticUtils_Nested_static_roundtrip") +@_cdecl("bjs_StaticUtils_Nested_static_roundtrip") +public func _bjs_StaticUtils_Nested_static_roundtrip(_ valueBytes: Int32, _ valueLength: Int32) -> Void { + #if arch(wasm32) + let ret = StaticUtils.Nested.roundtrip(_: String.bridgeJSLiftParameter(valueBytes, valueLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Services_Graph_GraphOperations_static_createGraph") +@_cdecl("bjs_Services_Graph_GraphOperations_static_createGraph") +public func _bjs_Services_Graph_GraphOperations_static_createGraph(_ rootId: Int32) -> Int32 { + #if arch(wasm32) + let ret = GraphOperations.createGraph(rootId: Int.bridgeJSLiftParameter(rootId)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Services_Graph_GraphOperations_static_nodeCount") +@_cdecl("bjs_Services_Graph_GraphOperations_static_nodeCount") +public func _bjs_Services_Graph_GraphOperations_static_nodeCount(_ graphId: Int32) -> Int32 { + #if arch(wasm32) + let ret = GraphOperations.nodeCount(graphId: Int.bridgeJSLiftParameter(graphId)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -extension Networking.API.Method: _BridgedSwiftCaseEnum { +extension StaticPropertyEnum: _BridgedSwiftCaseEnum { @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { return bridgeJSRawValue } - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> Networking.API.Method { + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> StaticPropertyEnum { return bridgeJSLiftParameter(value) } - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> Networking.API.Method { - return Networking.API.Method(bridgeJSRawValue: value)! + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> StaticPropertyEnum { + return StaticPropertyEnum(bridgeJSRawValue: value)! } @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { return bridgeJSLowerParameter() @@ -4314,13 +5566,9 @@ extension Networking.API.Method: _BridgedSwiftCaseEnum { @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { switch bridgeJSRawValue { case 0: - self = .get + self = .option1 case 1: - self = .post - case 2: - self = .put - case 3: - self = .delete + self = .option2 default: return nil } @@ -4328,2762 +5576,3040 @@ extension Networking.API.Method: _BridgedSwiftCaseEnum { @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { switch self { - case .get: + case .option1: return 0 - case .post: + case .option2: return 1 - case .put: - return 2 - case .delete: - return 3 } } } -extension Configuration.LogLevel: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +@_expose(wasm, "bjs_StaticPropertyEnum_static_enumProperty_get") +@_cdecl("bjs_StaticPropertyEnum_static_enumProperty_get") +public func _bjs_StaticPropertyEnum_static_enumProperty_get() -> Void { + #if arch(wasm32) + let ret = StaticPropertyEnum.enumProperty + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif } -extension Configuration.Port: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +@_expose(wasm, "bjs_StaticPropertyEnum_static_enumProperty_set") +@_cdecl("bjs_StaticPropertyEnum_static_enumProperty_set") +public func _bjs_StaticPropertyEnum_static_enumProperty_set(_ valueBytes: Int32, _ valueLength: Int32) -> Void { + #if arch(wasm32) + StaticPropertyEnum.enumProperty = String.bridgeJSLiftParameter(valueBytes, valueLength) + #else + fatalError("Only available on WebAssembly") + #endif } -extension Internal.SupportedMethod: _BridgedSwiftCaseEnum { - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { - return bridgeJSRawValue - } - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> Internal.SupportedMethod { - return bridgeJSLiftParameter(value) - } - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> Internal.SupportedMethod { - return Internal.SupportedMethod(bridgeJSRawValue: value)! - } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { - return bridgeJSLowerParameter() - } +@_expose(wasm, "bjs_StaticPropertyEnum_static_enumConstant_get") +@_cdecl("bjs_StaticPropertyEnum_static_enumConstant_get") +public func _bjs_StaticPropertyEnum_static_enumConstant_get() -> Int32 { + #if arch(wasm32) + let ret = StaticPropertyEnum.enumConstant + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} - @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { - switch bridgeJSRawValue { - case 0: - self = .get - case 1: - self = .post - default: - return nil - } - } +@_expose(wasm, "bjs_StaticPropertyEnum_static_enumBool_get") +@_cdecl("bjs_StaticPropertyEnum_static_enumBool_get") +public func _bjs_StaticPropertyEnum_static_enumBool_get() -> Int32 { + #if arch(wasm32) + let ret = StaticPropertyEnum.enumBool + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} - @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { - switch self { - case .get: - return 0 - case .post: - return 1 - } - } +@_expose(wasm, "bjs_StaticPropertyEnum_static_enumBool_set") +@_cdecl("bjs_StaticPropertyEnum_static_enumBool_set") +public func _bjs_StaticPropertyEnum_static_enumBool_set(_ value: Int32) -> Void { + #if arch(wasm32) + StaticPropertyEnum.enumBool = Bool.bridgeJSLiftParameter(value) + #else + fatalError("Only available on WebAssembly") + #endif } -extension APIResult: _BridgedSwiftAssociatedValueEnum { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> APIResult { - switch caseId { - case 0: - return .success(String.bridgeJSStackPop()) - case 1: - return .failure(Int.bridgeJSStackPop()) - case 2: - return .flag(Bool.bridgeJSStackPop()) - case 3: - return .rate(Float.bridgeJSStackPop()) - case 4: - return .precise(Double.bridgeJSStackPop()) - case 5: - return .info - default: - fatalError("Unknown APIResult case ID: \(caseId)") - } - } +@_expose(wasm, "bjs_StaticPropertyEnum_static_enumVariable_get") +@_cdecl("bjs_StaticPropertyEnum_static_enumVariable_get") +public func _bjs_StaticPropertyEnum_static_enumVariable_get() -> Int32 { + #if arch(wasm32) + let ret = StaticPropertyEnum.enumVariable + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} - @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { - switch self { - case .success(let param0): - param0.bridgeJSStackPush() - return Int32(0) - case .failure(let param0): - param0.bridgeJSStackPush() - return Int32(1) - case .flag(let param0): - param0.bridgeJSStackPush() - return Int32(2) - case .rate(let param0): - param0.bridgeJSStackPush() - return Int32(3) - case .precise(let param0): - param0.bridgeJSStackPush() - return Int32(4) - case .info: - return Int32(5) - } - } +@_expose(wasm, "bjs_StaticPropertyEnum_static_enumVariable_set") +@_cdecl("bjs_StaticPropertyEnum_static_enumVariable_set") +public func _bjs_StaticPropertyEnum_static_enumVariable_set(_ value: Int32) -> Void { + #if arch(wasm32) + StaticPropertyEnum.enumVariable = Int.bridgeJSLiftParameter(value) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_StaticPropertyEnum_static_computedReadonly_get") +@_cdecl("bjs_StaticPropertyEnum_static_computedReadonly_get") +public func _bjs_StaticPropertyEnum_static_computedReadonly_get() -> Int32 { + #if arch(wasm32) + let ret = StaticPropertyEnum.computedReadonly + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_StaticPropertyEnum_static_computedReadWrite_get") +@_cdecl("bjs_StaticPropertyEnum_static_computedReadWrite_get") +public func _bjs_StaticPropertyEnum_static_computedReadWrite_get() -> Void { + #if arch(wasm32) + let ret = StaticPropertyEnum.computedReadWrite + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_StaticPropertyEnum_static_computedReadWrite_set") +@_cdecl("bjs_StaticPropertyEnum_static_computedReadWrite_set") +public func _bjs_StaticPropertyEnum_static_computedReadWrite_set(_ valueBytes: Int32, _ valueLength: Int32) -> Void { + #if arch(wasm32) + StaticPropertyEnum.computedReadWrite = String.bridgeJSLiftParameter(valueBytes, valueLength) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_StaticPropertyNamespace_static_namespaceProperty_get") +@_cdecl("bjs_StaticPropertyNamespace_static_namespaceProperty_get") +public func _bjs_StaticPropertyNamespace_static_namespaceProperty_get() -> Void { + #if arch(wasm32) + let ret = StaticPropertyNamespace.namespaceProperty + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_StaticPropertyNamespace_static_namespaceProperty_set") +@_cdecl("bjs_StaticPropertyNamespace_static_namespaceProperty_set") +public func _bjs_StaticPropertyNamespace_static_namespaceProperty_set(_ valueBytes: Int32, _ valueLength: Int32) -> Void { + #if arch(wasm32) + StaticPropertyNamespace.namespaceProperty = String.bridgeJSLiftParameter(valueBytes, valueLength) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_StaticPropertyNamespace_static_namespaceConstant_get") +@_cdecl("bjs_StaticPropertyNamespace_static_namespaceConstant_get") +public func _bjs_StaticPropertyNamespace_static_namespaceConstant_get() -> Void { + #if arch(wasm32) + let ret = StaticPropertyNamespace.namespaceConstant + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_StaticPropertyNamespace_NestedProperties_static_nestedProperty_get") +@_cdecl("bjs_StaticPropertyNamespace_NestedProperties_static_nestedProperty_get") +public func _bjs_StaticPropertyNamespace_NestedProperties_static_nestedProperty_get() -> Int32 { + #if arch(wasm32) + let ret = StaticPropertyNamespace.NestedProperties.nestedProperty + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_StaticPropertyNamespace_NestedProperties_static_nestedProperty_set") +@_cdecl("bjs_StaticPropertyNamespace_NestedProperties_static_nestedProperty_set") +public func _bjs_StaticPropertyNamespace_NestedProperties_static_nestedProperty_set(_ value: Int32) -> Void { + #if arch(wasm32) + StaticPropertyNamespace.NestedProperties.nestedProperty = Int.bridgeJSLiftParameter(value) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_StaticPropertyNamespace_NestedProperties_static_nestedConstant_get") +@_cdecl("bjs_StaticPropertyNamespace_NestedProperties_static_nestedConstant_get") +public func _bjs_StaticPropertyNamespace_NestedProperties_static_nestedConstant_get() -> Void { + #if arch(wasm32) + let ret = StaticPropertyNamespace.NestedProperties.nestedConstant + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif } -extension ComplexResult: _BridgedSwiftAssociatedValueEnum { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> ComplexResult { - switch caseId { - case 0: - return .success(String.bridgeJSStackPop()) - case 1: - return .error(String.bridgeJSStackPop(), Int.bridgeJSStackPop()) - case 2: - return .location(Double.bridgeJSStackPop(), Double.bridgeJSStackPop(), String.bridgeJSStackPop()) - case 3: - return .status(Bool.bridgeJSStackPop(), Int.bridgeJSStackPop(), String.bridgeJSStackPop()) - case 4: - return .coordinates(Double.bridgeJSStackPop(), Double.bridgeJSStackPop(), Double.bridgeJSStackPop()) - case 5: - return .comprehensive(Bool.bridgeJSStackPop(), Bool.bridgeJSStackPop(), Int.bridgeJSStackPop(), Int.bridgeJSStackPop(), Double.bridgeJSStackPop(), Double.bridgeJSStackPop(), String.bridgeJSStackPop(), String.bridgeJSStackPop(), String.bridgeJSStackPop()) - case 6: - return .info - default: - fatalError("Unknown ComplexResult case ID: \(caseId)") - } - } +@_expose(wasm, "bjs_StaticPropertyNamespace_NestedProperties_static_nestedDouble_get") +@_cdecl("bjs_StaticPropertyNamespace_NestedProperties_static_nestedDouble_get") +public func _bjs_StaticPropertyNamespace_NestedProperties_static_nestedDouble_get() -> Float64 { + #if arch(wasm32) + let ret = StaticPropertyNamespace.NestedProperties.nestedDouble + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} - @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { - switch self { - case .success(let param0): - param0.bridgeJSStackPush() - return Int32(0) - case .error(let param0, let param1): - param0.bridgeJSStackPush() - param1.bridgeJSStackPush() - return Int32(1) - case .location(let param0, let param1, let param2): - param0.bridgeJSStackPush() - param1.bridgeJSStackPush() - param2.bridgeJSStackPush() - return Int32(2) - case .status(let param0, let param1, let param2): - param0.bridgeJSStackPush() - param1.bridgeJSStackPush() - param2.bridgeJSStackPush() - return Int32(3) - case .coordinates(let param0, let param1, let param2): - param0.bridgeJSStackPush() - param1.bridgeJSStackPush() - param2.bridgeJSStackPush() - return Int32(4) - case .comprehensive(let param0, let param1, let param2, let param3, let param4, let param5, let param6, let param7, let param8): - param0.bridgeJSStackPush() - param1.bridgeJSStackPush() - param2.bridgeJSStackPush() - param3.bridgeJSStackPush() - param4.bridgeJSStackPush() - param5.bridgeJSStackPush() - param6.bridgeJSStackPush() - param7.bridgeJSStackPush() - param8.bridgeJSStackPush() - return Int32(5) - case .info: - return Int32(6) - } - } +@_expose(wasm, "bjs_StaticPropertyNamespace_NestedProperties_static_nestedDouble_set") +@_cdecl("bjs_StaticPropertyNamespace_NestedProperties_static_nestedDouble_set") +public func _bjs_StaticPropertyNamespace_NestedProperties_static_nestedDouble_set(_ value: Float64) -> Void { + #if arch(wasm32) + StaticPropertyNamespace.NestedProperties.nestedDouble = Double.bridgeJSLiftParameter(value) + #else + fatalError("Only available on WebAssembly") + #endif } -extension Utilities.Result: _BridgedSwiftAssociatedValueEnum { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> Utilities.Result { - switch caseId { - case 0: - return .success(String.bridgeJSStackPop()) - case 1: - return .failure(String.bridgeJSStackPop(), Int.bridgeJSStackPop()) - case 2: - return .status(Bool.bridgeJSStackPop(), Int.bridgeJSStackPop(), String.bridgeJSStackPop()) - default: - fatalError("Unknown Utilities.Result case ID: \(caseId)") - } - } +@_expose(wasm, "bjs_NestedStructGroupA_static_roundtripMetadata") +@_cdecl("bjs_NestedStructGroupA_static_roundtripMetadata") +public func _bjs_NestedStructGroupA_static_roundtripMetadata() -> Void { + #if arch(wasm32) + let ret = NestedStructGroupA.roundtripMetadata(_: NestedStructGroupA.Metadata.bridgeJSLiftParameter()) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} - @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { - switch self { - case .success(let param0): - param0.bridgeJSStackPush() - return Int32(0) - case .failure(let param0, let param1): - param0.bridgeJSStackPush() - param1.bridgeJSStackPush() - return Int32(1) - case .status(let param0, let param1, let param2): - param0.bridgeJSStackPush() - param1.bridgeJSStackPush() - param2.bridgeJSStackPush() - return Int32(2) - } - } +@_expose(wasm, "bjs_NestedStructGroupB_static_roundtripMetadata") +@_cdecl("bjs_NestedStructGroupB_static_roundtripMetadata") +public func _bjs_NestedStructGroupB_static_roundtripMetadata() -> Void { + #if arch(wasm32) + let ret = NestedStructGroupB.roundtripMetadata(_: NestedStructGroupB.Metadata.bridgeJSLiftParameter()) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif } -extension API.NetworkingResult: _BridgedSwiftAssociatedValueEnum { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> API.NetworkingResult { - switch caseId { - case 0: - return .success(String.bridgeJSStackPop()) - case 1: - return .failure(String.bridgeJSStackPop(), Int.bridgeJSStackPop()) - default: - fatalError("Unknown API.NetworkingResult case ID: \(caseId)") - } +extension LightColor: _BridgedSwiftCaseEnum { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + return bridgeJSRawValue } - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { - switch self { - case .success(let param0): - param0.bridgeJSStackPush() - return Int32(0) - case .failure(let param0, let param1): - param0.bridgeJSStackPush() - param1.bridgeJSStackPush() - return Int32(1) - } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> LightColor { + return bridgeJSLiftParameter(value) + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> LightColor { + return LightColor(bridgeJSRawValue: value)! + } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { + return bridgeJSLowerParameter() } -} -extension AllTypesResult: _BridgedSwiftAssociatedValueEnum { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> AllTypesResult { - switch caseId { + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { + switch bridgeJSRawValue { case 0: - return .structPayload(Address.bridgeJSStackPop()) + self = .red case 1: - return .classPayload(Greeter.bridgeJSStackPop()) + self = .yellow case 2: - return .jsObjectPayload(JSObject.bridgeJSStackPop()) - case 3: - return .nestedEnum(APIResult.bridgeJSStackPop()) - case 4: - return .arrayPayload([Int].bridgeJSStackPop()) - case 5: - return .jsClassPayload(Foo(unsafelyWrapping: JSObject.bridgeJSStackPop())) - case 6: - return .empty + self = .green default: - fatalError("Unknown AllTypesResult case ID: \(caseId)") + return nil } } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { switch self { - case .structPayload(let param0): - param0.bridgeJSStackPush() - return Int32(0) - case .classPayload(let param0): - param0.bridgeJSStackPush() - return Int32(1) - case .jsObjectPayload(let param0): - param0.bridgeJSStackPush() - return Int32(2) - case .nestedEnum(let param0): - param0.bridgeJSStackPush() - return Int32(3) - case .arrayPayload(let param0): - param0.bridgeJSStackPush() - return Int32(4) - case .jsClassPayload(let param0): - param0.jsObject.bridgeJSStackPush() - return Int32(5) - case .empty: - return Int32(6) + case .red: + return 0 + case .yellow: + return 1 + case .green: + return 2 } } } -extension TypedPayloadResult: _BridgedSwiftAssociatedValueEnum { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> TypedPayloadResult { +extension ImportedPayloadSignal: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> ImportedPayloadSignal { switch caseId { case 0: - return .precision(Precision.bridgeJSStackPop()) + return .start(String.bridgeJSStackPop()) case 1: - return .direction(Direction.bridgeJSStackPop()) + return .stop(Int.bridgeJSStackPop()) case 2: - return .optPrecision(Optional.bridgeJSStackPop()) - case 3: - return .optDirection(Optional.bridgeJSStackPop()) - case 4: - return .empty + return .idle default: - fatalError("Unknown TypedPayloadResult case ID: \(caseId)") + fatalError("Unknown ImportedPayloadSignal case ID: \(caseId)") } } @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { switch self { - case .precision(let param0): + case .start(let param0): param0.bridgeJSStackPush() return Int32(0) - case .direction(let param0): + case .stop(let param0): param0.bridgeJSStackPush() return Int32(1) - case .optPrecision(let param0): - param0.bridgeJSStackPush() + case .idle: return Int32(2) - case .optDirection(let param0): - param0.bridgeJSStackPush() - return Int32(3) - case .empty: - return Int32(4) } } } -extension StaticCalculator: _BridgedSwiftCaseEnum { - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { - return bridgeJSRawValue - } - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> StaticCalculator { - return bridgeJSLiftParameter(value) - } - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> StaticCalculator { - return StaticCalculator(bridgeJSRawValue: value)! - } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { - return bridgeJSLowerParameter() - } +@_expose(wasm, "bjs_IntegerTypesSupportExports_static_roundTripInt") +@_cdecl("bjs_IntegerTypesSupportExports_static_roundTripInt") +public func _bjs_IntegerTypesSupportExports_static_roundTripInt(_ v: Int32) -> Int32 { + #if arch(wasm32) + let ret = IntegerTypesSupportExports.roundTripInt(_: Int.bridgeJSLiftParameter(v)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_IntegerTypesSupportExports_static_roundTripUInt") +@_cdecl("bjs_IntegerTypesSupportExports_static_roundTripUInt") +public func _bjs_IntegerTypesSupportExports_static_roundTripUInt(_ v: Int32) -> Int32 { + #if arch(wasm32) + let ret = IntegerTypesSupportExports.roundTripUInt(_: UInt.bridgeJSLiftParameter(v)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_IntegerTypesSupportExports_static_roundTripInt8") +@_cdecl("bjs_IntegerTypesSupportExports_static_roundTripInt8") +public func _bjs_IntegerTypesSupportExports_static_roundTripInt8(_ v: Int32) -> Int32 { + #if arch(wasm32) + let ret = IntegerTypesSupportExports.roundTripInt8(_: Int8.bridgeJSLiftParameter(v)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} - @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { - switch bridgeJSRawValue { - case 0: - self = .scientific - case 1: - self = .basic - default: - return nil - } - } +@_expose(wasm, "bjs_IntegerTypesSupportExports_static_roundTripUInt8") +@_cdecl("bjs_IntegerTypesSupportExports_static_roundTripUInt8") +public func _bjs_IntegerTypesSupportExports_static_roundTripUInt8(_ v: Int32) -> Int32 { + #if arch(wasm32) + let ret = IntegerTypesSupportExports.roundTripUInt8(_: UInt8.bridgeJSLiftParameter(v)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} - @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { - switch self { - case .scientific: - return 0 - case .basic: - return 1 - } - } +@_expose(wasm, "bjs_IntegerTypesSupportExports_static_roundTripInt16") +@_cdecl("bjs_IntegerTypesSupportExports_static_roundTripInt16") +public func _bjs_IntegerTypesSupportExports_static_roundTripInt16(_ v: Int32) -> Int32 { + #if arch(wasm32) + let ret = IntegerTypesSupportExports.roundTripInt16(_: Int16.bridgeJSLiftParameter(v)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif } -@_expose(wasm, "bjs_StaticCalculator_static_roundtrip") -@_cdecl("bjs_StaticCalculator_static_roundtrip") -public func _bjs_StaticCalculator_static_roundtrip(_ value: Int32) -> Int32 { +@_expose(wasm, "bjs_IntegerTypesSupportExports_static_roundTripUInt16") +@_cdecl("bjs_IntegerTypesSupportExports_static_roundTripUInt16") +public func _bjs_IntegerTypesSupportExports_static_roundTripUInt16(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = StaticCalculator.roundtrip(_: Int.bridgeJSLiftParameter(value)) + let ret = IntegerTypesSupportExports.roundTripUInt16(_: UInt16.bridgeJSLiftParameter(v)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticCalculator_static_doubleValue") -@_cdecl("bjs_StaticCalculator_static_doubleValue") -public func _bjs_StaticCalculator_static_doubleValue(_ value: Int32) -> Int32 { +@_expose(wasm, "bjs_IntegerTypesSupportExports_static_roundTripInt32") +@_cdecl("bjs_IntegerTypesSupportExports_static_roundTripInt32") +public func _bjs_IntegerTypesSupportExports_static_roundTripInt32(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = StaticCalculator.doubleValue(_: Int.bridgeJSLiftParameter(value)) + let ret = IntegerTypesSupportExports.roundTripInt32(_: Int32.bridgeJSLiftParameter(v)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticCalculator_static_version_get") -@_cdecl("bjs_StaticCalculator_static_version_get") -public func _bjs_StaticCalculator_static_version_get() -> Void { +@_expose(wasm, "bjs_IntegerTypesSupportExports_static_roundTripUInt32") +@_cdecl("bjs_IntegerTypesSupportExports_static_roundTripUInt32") +public func _bjs_IntegerTypesSupportExports_static_roundTripUInt32(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = StaticCalculator.version + let ret = IntegerTypesSupportExports.roundTripUInt32(_: UInt32.bridgeJSLiftParameter(v)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticUtils_Nested_static_roundtrip") -@_cdecl("bjs_StaticUtils_Nested_static_roundtrip") -public func _bjs_StaticUtils_Nested_static_roundtrip(_ valueBytes: Int32, _ valueLength: Int32) -> Void { +@_expose(wasm, "bjs_IntegerTypesSupportExports_static_roundTripInt64") +@_cdecl("bjs_IntegerTypesSupportExports_static_roundTripInt64") +public func _bjs_IntegerTypesSupportExports_static_roundTripInt64(_ v: Int64) -> Int64 { #if arch(wasm32) - let ret = StaticUtils.Nested.roundtrip(_: String.bridgeJSLiftParameter(valueBytes, valueLength)) + let ret = IntegerTypesSupportExports.roundTripInt64(_: Int64.bridgeJSLiftParameter(v)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_Services_Graph_GraphOperations_static_createGraph") -@_cdecl("bjs_Services_Graph_GraphOperations_static_createGraph") -public func _bjs_Services_Graph_GraphOperations_static_createGraph(_ rootId: Int32) -> Int32 { +@_expose(wasm, "bjs_IntegerTypesSupportExports_static_roundTripUInt64") +@_cdecl("bjs_IntegerTypesSupportExports_static_roundTripUInt64") +public func _bjs_IntegerTypesSupportExports_static_roundTripUInt64(_ v: Int64) -> Int64 { #if arch(wasm32) - let ret = GraphOperations.createGraph(rootId: Int.bridgeJSLiftParameter(rootId)) + let ret = IntegerTypesSupportExports.roundTripUInt64(_: UInt64.bridgeJSLiftParameter(v)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_Services_Graph_GraphOperations_static_nodeCount") -@_cdecl("bjs_Services_Graph_GraphOperations_static_nodeCount") -public func _bjs_Services_Graph_GraphOperations_static_nodeCount(_ graphId: Int32) -> Int32 { +@_expose(wasm, "bjs_JSTypedArrayExports_static_roundTripUint8Array") +@_cdecl("bjs_JSTypedArrayExports_static_roundTripUint8Array") +public func _bjs_JSTypedArrayExports_static_roundTripUint8Array(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = GraphOperations.nodeCount(graphId: Int.bridgeJSLiftParameter(graphId)) + let ret = JSTypedArrayExports.roundTripUint8Array(_: JSUint8Array.bridgeJSLiftParameter(v)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -extension StaticPropertyEnum: _BridgedSwiftCaseEnum { - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { - return bridgeJSRawValue - } - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> StaticPropertyEnum { - return bridgeJSLiftParameter(value) - } - @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> StaticPropertyEnum { - return StaticPropertyEnum(bridgeJSRawValue: value)! - } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { - return bridgeJSLowerParameter() - } +@_expose(wasm, "bjs_JSTypedArrayExports_static_roundTripFloat32Array") +@_cdecl("bjs_JSTypedArrayExports_static_roundTripFloat32Array") +public func _bjs_JSTypedArrayExports_static_roundTripFloat32Array(_ v: Int32) -> Int32 { + #if arch(wasm32) + let ret = JSTypedArrayExports.roundTripFloat32Array(_: JSFloat32Array.bridgeJSLiftParameter(v)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} - @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { - switch bridgeJSRawValue { - case 0: - self = .option1 - case 1: - self = .option2 - default: - return nil - } - } +@_expose(wasm, "bjs_JSTypedArrayExports_static_roundTripFloat64Array") +@_cdecl("bjs_JSTypedArrayExports_static_roundTripFloat64Array") +public func _bjs_JSTypedArrayExports_static_roundTripFloat64Array(_ v: Int32) -> Int32 { + #if arch(wasm32) + let ret = JSTypedArrayExports.roundTripFloat64Array(_: JSFloat64Array.bridgeJSLiftParameter(v)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} - @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { - switch self { - case .option1: - return 0 - case .option2: - return 1 - } - } +@_expose(wasm, "bjs_JSTypedArrayExports_static_roundTripInt32Array") +@_cdecl("bjs_JSTypedArrayExports_static_roundTripInt32Array") +public func _bjs_JSTypedArrayExports_static_roundTripInt32Array(_ v: Int32) -> Int32 { + #if arch(wasm32) + let ret = JSTypedArrayExports.roundTripInt32Array(_: JSInt32Array.bridgeJSLiftParameter(v)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif } -@_expose(wasm, "bjs_StaticPropertyEnum_static_enumProperty_get") -@_cdecl("bjs_StaticPropertyEnum_static_enumProperty_get") -public func _bjs_StaticPropertyEnum_static_enumProperty_get() -> Void { +@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalString") +@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalString") +public func _bjs_OptionalSupportExports_static_roundTripOptionalString(_ vIsSome: Int32, _ vBytes: Int32, _ vLength: Int32) -> Void { #if arch(wasm32) - let ret = StaticPropertyEnum.enumProperty + let ret = OptionalSupportExports.roundTripOptionalString(_: Optional.bridgeJSLiftParameter(vIsSome, vBytes, vLength)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyEnum_static_enumProperty_set") -@_cdecl("bjs_StaticPropertyEnum_static_enumProperty_set") -public func _bjs_StaticPropertyEnum_static_enumProperty_set(_ valueBytes: Int32, _ valueLength: Int32) -> Void { +@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalInt") +@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalInt") +public func _bjs_OptionalSupportExports_static_roundTripOptionalInt(_ vIsSome: Int32, _ vValue: Int32) -> Void { #if arch(wasm32) - StaticPropertyEnum.enumProperty = String.bridgeJSLiftParameter(valueBytes, valueLength) + let ret = OptionalSupportExports.roundTripOptionalInt(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyEnum_static_enumConstant_get") -@_cdecl("bjs_StaticPropertyEnum_static_enumConstant_get") -public func _bjs_StaticPropertyEnum_static_enumConstant_get() -> Int32 { +@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalBool") +@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalBool") +public func _bjs_OptionalSupportExports_static_roundTripOptionalBool(_ vIsSome: Int32, _ vValue: Int32) -> Void { #if arch(wasm32) - let ret = StaticPropertyEnum.enumConstant + let ret = OptionalSupportExports.roundTripOptionalBool(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyEnum_static_enumBool_get") -@_cdecl("bjs_StaticPropertyEnum_static_enumBool_get") -public func _bjs_StaticPropertyEnum_static_enumBool_get() -> Int32 { +@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalFloat") +@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalFloat") +public func _bjs_OptionalSupportExports_static_roundTripOptionalFloat(_ vIsSome: Int32, _ vValue: Float32) -> Void { #if arch(wasm32) - let ret = StaticPropertyEnum.enumBool + let ret = OptionalSupportExports.roundTripOptionalFloat(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyEnum_static_enumBool_set") -@_cdecl("bjs_StaticPropertyEnum_static_enumBool_set") -public func _bjs_StaticPropertyEnum_static_enumBool_set(_ value: Int32) -> Void { +@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalDouble") +@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalDouble") +public func _bjs_OptionalSupportExports_static_roundTripOptionalDouble(_ vIsSome: Int32, _ vValue: Float64) -> Void { #if arch(wasm32) - StaticPropertyEnum.enumBool = Bool.bridgeJSLiftParameter(value) + let ret = OptionalSupportExports.roundTripOptionalDouble(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyEnum_static_enumVariable_get") -@_cdecl("bjs_StaticPropertyEnum_static_enumVariable_get") -public func _bjs_StaticPropertyEnum_static_enumVariable_get() -> Int32 { +@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalSyntax") +@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalSyntax") +public func _bjs_OptionalSupportExports_static_roundTripOptionalSyntax(_ vIsSome: Int32, _ vBytes: Int32, _ vLength: Int32) -> Void { #if arch(wasm32) - let ret = StaticPropertyEnum.enumVariable + let ret = OptionalSupportExports.roundTripOptionalSyntax(_: Optional.bridgeJSLiftParameter(vIsSome, vBytes, vLength)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyEnum_static_enumVariable_set") -@_cdecl("bjs_StaticPropertyEnum_static_enumVariable_set") -public func _bjs_StaticPropertyEnum_static_enumVariable_set(_ value: Int32) -> Void { +@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalCaseEnum") +@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalCaseEnum") +public func _bjs_OptionalSupportExports_static_roundTripOptionalCaseEnum(_ vIsSome: Int32, _ vValue: Int32) -> Void { #if arch(wasm32) - StaticPropertyEnum.enumVariable = Int.bridgeJSLiftParameter(value) + let ret = OptionalSupportExports.roundTripOptionalCaseEnum(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyEnum_static_computedReadonly_get") -@_cdecl("bjs_StaticPropertyEnum_static_computedReadonly_get") -public func _bjs_StaticPropertyEnum_static_computedReadonly_get() -> Int32 { +@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalStringRawValueEnum") +@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalStringRawValueEnum") +public func _bjs_OptionalSupportExports_static_roundTripOptionalStringRawValueEnum(_ vIsSome: Int32, _ vBytes: Int32, _ vLength: Int32) -> Void { #if arch(wasm32) - let ret = StaticPropertyEnum.computedReadonly + let ret = OptionalSupportExports.roundTripOptionalStringRawValueEnum(_: Optional.bridgeJSLiftParameter(vIsSome, vBytes, vLength)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyEnum_static_computedReadWrite_get") -@_cdecl("bjs_StaticPropertyEnum_static_computedReadWrite_get") -public func _bjs_StaticPropertyEnum_static_computedReadWrite_get() -> Void { +@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalIntRawValueEnum") +@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalIntRawValueEnum") +public func _bjs_OptionalSupportExports_static_roundTripOptionalIntRawValueEnum(_ vIsSome: Int32, _ vValue: Int32) -> Void { #if arch(wasm32) - let ret = StaticPropertyEnum.computedReadWrite + let ret = OptionalSupportExports.roundTripOptionalIntRawValueEnum(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyEnum_static_computedReadWrite_set") -@_cdecl("bjs_StaticPropertyEnum_static_computedReadWrite_set") -public func _bjs_StaticPropertyEnum_static_computedReadWrite_set(_ valueBytes: Int32, _ valueLength: Int32) -> Void { +@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalInt64RawValueEnum") +@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalInt64RawValueEnum") +public func _bjs_OptionalSupportExports_static_roundTripOptionalInt64RawValueEnum(_ vIsSome: Int32, _ vValue: Int64) -> Void { #if arch(wasm32) - StaticPropertyEnum.computedReadWrite = String.bridgeJSLiftParameter(valueBytes, valueLength) + let ret = OptionalSupportExports.roundTripOptionalInt64RawValueEnum(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyNamespace_static_namespaceProperty_get") -@_cdecl("bjs_StaticPropertyNamespace_static_namespaceProperty_get") -public func _bjs_StaticPropertyNamespace_static_namespaceProperty_get() -> Void { +@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalUInt64RawValueEnum") +@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalUInt64RawValueEnum") +public func _bjs_OptionalSupportExports_static_roundTripOptionalUInt64RawValueEnum(_ vIsSome: Int32, _ vValue: Int64) -> Void { #if arch(wasm32) - let ret = StaticPropertyNamespace.namespaceProperty + let ret = OptionalSupportExports.roundTripOptionalUInt64RawValueEnum(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyNamespace_static_namespaceProperty_set") -@_cdecl("bjs_StaticPropertyNamespace_static_namespaceProperty_set") -public func _bjs_StaticPropertyNamespace_static_namespaceProperty_set(_ valueBytes: Int32, _ valueLength: Int32) -> Void { +@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalTSEnum") +@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalTSEnum") +public func _bjs_OptionalSupportExports_static_roundTripOptionalTSEnum(_ vIsSome: Int32, _ vValue: Int32) -> Void { #if arch(wasm32) - StaticPropertyNamespace.namespaceProperty = String.bridgeJSLiftParameter(valueBytes, valueLength) + let ret = OptionalSupportExports.roundTripOptionalTSEnum(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyNamespace_static_namespaceConstant_get") -@_cdecl("bjs_StaticPropertyNamespace_static_namespaceConstant_get") -public func _bjs_StaticPropertyNamespace_static_namespaceConstant_get() -> Void { +@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalTSStringEnum") +@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalTSStringEnum") +public func _bjs_OptionalSupportExports_static_roundTripOptionalTSStringEnum(_ vIsSome: Int32, _ vBytes: Int32, _ vLength: Int32) -> Void { #if arch(wasm32) - let ret = StaticPropertyNamespace.namespaceConstant + let ret = OptionalSupportExports.roundTripOptionalTSStringEnum(_: Optional.bridgeJSLiftParameter(vIsSome, vBytes, vLength)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyNamespace_NestedProperties_static_nestedProperty_get") -@_cdecl("bjs_StaticPropertyNamespace_NestedProperties_static_nestedProperty_get") -public func _bjs_StaticPropertyNamespace_NestedProperties_static_nestedProperty_get() -> Int32 { +@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalNamespacedEnum") +@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalNamespacedEnum") +public func _bjs_OptionalSupportExports_static_roundTripOptionalNamespacedEnum(_ vIsSome: Int32, _ vValue: Int32) -> Void { #if arch(wasm32) - let ret = StaticPropertyNamespace.NestedProperties.nestedProperty + let ret = OptionalSupportExports.roundTripOptionalNamespacedEnum(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyNamespace_NestedProperties_static_nestedProperty_set") -@_cdecl("bjs_StaticPropertyNamespace_NestedProperties_static_nestedProperty_set") -public func _bjs_StaticPropertyNamespace_NestedProperties_static_nestedProperty_set(_ value: Int32) -> Void { +@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalSwiftClass") +@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalSwiftClass") +public func _bjs_OptionalSupportExports_static_roundTripOptionalSwiftClass(_ vIsSome: Int32, _ vValue: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - StaticPropertyNamespace.NestedProperties.nestedProperty = Int.bridgeJSLiftParameter(value) + let ret = OptionalSupportExports.roundTripOptionalSwiftClass(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyNamespace_NestedProperties_static_nestedConstant_get") -@_cdecl("bjs_StaticPropertyNamespace_NestedProperties_static_nestedConstant_get") -public func _bjs_StaticPropertyNamespace_NestedProperties_static_nestedConstant_get() -> Void { +@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalIntArray") +@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalIntArray") +public func _bjs_OptionalSupportExports_static_roundTripOptionalIntArray() -> Void { #if arch(wasm32) - let ret = StaticPropertyNamespace.NestedProperties.nestedConstant - return ret.bridgeJSLowerReturn() + let ret = OptionalSupportExports.roundTripOptionalIntArray(_: Optional<[Int]>.bridgeJSLiftParameter()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyNamespace_NestedProperties_static_nestedDouble_get") -@_cdecl("bjs_StaticPropertyNamespace_NestedProperties_static_nestedDouble_get") -public func _bjs_StaticPropertyNamespace_NestedProperties_static_nestedDouble_get() -> Float64 { +@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalStringArray") +@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalStringArray") +public func _bjs_OptionalSupportExports_static_roundTripOptionalStringArray() -> Void { #if arch(wasm32) - let ret = StaticPropertyNamespace.NestedProperties.nestedDouble - return ret.bridgeJSLowerReturn() + let ret = OptionalSupportExports.roundTripOptionalStringArray(_: Optional<[String]>.bridgeJSLiftParameter()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyNamespace_NestedProperties_static_nestedDouble_set") -@_cdecl("bjs_StaticPropertyNamespace_NestedProperties_static_nestedDouble_set") -public func _bjs_StaticPropertyNamespace_NestedProperties_static_nestedDouble_set(_ value: Float64) -> Void { +@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalSwiftClassArray") +@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalSwiftClassArray") +public func _bjs_OptionalSupportExports_static_roundTripOptionalSwiftClassArray() -> Void { #if arch(wasm32) - StaticPropertyNamespace.NestedProperties.nestedDouble = Double.bridgeJSLiftParameter(value) + let ret = OptionalSupportExports.roundTripOptionalSwiftClassArray(_: Optional<[Greeter]>.bridgeJSLiftParameter()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_NestedStructGroupA_static_roundtripMetadata") -@_cdecl("bjs_NestedStructGroupA_static_roundtripMetadata") -public func _bjs_NestedStructGroupA_static_roundtripMetadata() -> Void { +@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalAPIResult") +@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalAPIResult") +public func _bjs_OptionalSupportExports_static_roundTripOptionalAPIResult(_ vIsSome: Int32, _ vCaseId: Int32) -> Void { #if arch(wasm32) - let ret = NestedStructGroupA.roundtripMetadata(_: NestedStructGroupA.Metadata.bridgeJSLiftParameter()) + let ret = OptionalSupportExports.roundTripOptionalAPIResult(_: Optional.bridgeJSLiftParameter(vIsSome, vCaseId)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_NestedStructGroupB_static_roundtripMetadata") -@_cdecl("bjs_NestedStructGroupB_static_roundtripMetadata") -public func _bjs_NestedStructGroupB_static_roundtripMetadata() -> Void { +@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalTypedPayloadResult") +@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalTypedPayloadResult") +public func _bjs_OptionalSupportExports_static_roundTripOptionalTypedPayloadResult(_ vIsSome: Int32, _ vCaseId: Int32) -> Void { #if arch(wasm32) - let ret = NestedStructGroupB.roundtripMetadata(_: NestedStructGroupB.Metadata.bridgeJSLiftParameter()) + let ret = OptionalSupportExports.roundTripOptionalTypedPayloadResult(_: Optional.bridgeJSLiftParameter(vIsSome, vCaseId)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_IntegerTypesSupportExports_static_roundTripInt") -@_cdecl("bjs_IntegerTypesSupportExports_static_roundTripInt") -public func _bjs_IntegerTypesSupportExports_static_roundTripInt(_ v: Int32) -> Int32 { +@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalComplexResult") +@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalComplexResult") +public func _bjs_OptionalSupportExports_static_roundTripOptionalComplexResult(_ vIsSome: Int32, _ vCaseId: Int32) -> Void { #if arch(wasm32) - let ret = IntegerTypesSupportExports.roundTripInt(_: Int.bridgeJSLiftParameter(v)) + let ret = OptionalSupportExports.roundTripOptionalComplexResult(_: Optional.bridgeJSLiftParameter(vIsSome, vCaseId)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_IntegerTypesSupportExports_static_roundTripUInt") -@_cdecl("bjs_IntegerTypesSupportExports_static_roundTripUInt") -public func _bjs_IntegerTypesSupportExports_static_roundTripUInt(_ v: Int32) -> Int32 { +@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalAllTypesResult") +@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalAllTypesResult") +public func _bjs_OptionalSupportExports_static_roundTripOptionalAllTypesResult(_ vIsSome: Int32, _ vCaseId: Int32) -> Void { #if arch(wasm32) - let ret = IntegerTypesSupportExports.roundTripUInt(_: UInt.bridgeJSLiftParameter(v)) + let ret = OptionalSupportExports.roundTripOptionalAllTypesResult(_: Optional.bridgeJSLiftParameter(vIsSome, vCaseId)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_IntegerTypesSupportExports_static_roundTripInt8") -@_cdecl("bjs_IntegerTypesSupportExports_static_roundTripInt8") -public func _bjs_IntegerTypesSupportExports_static_roundTripInt8(_ v: Int32) -> Int32 { +@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalPayloadResult") +@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalPayloadResult") +public func _bjs_OptionalSupportExports_static_roundTripOptionalPayloadResult(_ v: Int32) -> Void { #if arch(wasm32) - let ret = IntegerTypesSupportExports.roundTripInt8(_: Int8.bridgeJSLiftParameter(v)) + let ret = OptionalSupportExports.roundTripOptionalPayloadResult(_: OptionalAllTypesResult.bridgeJSLiftParameter(v)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_IntegerTypesSupportExports_static_roundTripUInt8") -@_cdecl("bjs_IntegerTypesSupportExports_static_roundTripUInt8") -public func _bjs_IntegerTypesSupportExports_static_roundTripUInt8(_ v: Int32) -> Int32 { +@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalPayloadResultOpt") +@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalPayloadResultOpt") +public func _bjs_OptionalSupportExports_static_roundTripOptionalPayloadResultOpt(_ vIsSome: Int32, _ vCaseId: Int32) -> Void { #if arch(wasm32) - let ret = IntegerTypesSupportExports.roundTripUInt8(_: UInt8.bridgeJSLiftParameter(v)) + let ret = OptionalSupportExports.roundTripOptionalPayloadResultOpt(_: Optional.bridgeJSLiftParameter(vIsSome, vCaseId)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_IntegerTypesSupportExports_static_roundTripInt16") -@_cdecl("bjs_IntegerTypesSupportExports_static_roundTripInt16") -public func _bjs_IntegerTypesSupportExports_static_roundTripInt16(_ v: Int32) -> Int32 { +@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalAPIOptionalResult") +@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalAPIOptionalResult") +public func _bjs_OptionalSupportExports_static_roundTripOptionalAPIOptionalResult(_ vIsSome: Int32, _ vCaseId: Int32) -> Void { #if arch(wasm32) - let ret = IntegerTypesSupportExports.roundTripInt16(_: Int16.bridgeJSLiftParameter(v)) + let ret = OptionalSupportExports.roundTripOptionalAPIOptionalResult(_: Optional.bridgeJSLiftParameter(vIsSome, vCaseId)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_IntegerTypesSupportExports_static_roundTripUInt16") -@_cdecl("bjs_IntegerTypesSupportExports_static_roundTripUInt16") -public func _bjs_IntegerTypesSupportExports_static_roundTripUInt16(_ v: Int32) -> Int32 { +@_expose(wasm, "bjs_OptionalSupportExports_static_takeOptionalJSObject") +@_cdecl("bjs_OptionalSupportExports_static_takeOptionalJSObject") +public func _bjs_OptionalSupportExports_static_takeOptionalJSObject(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { #if arch(wasm32) - let ret = IntegerTypesSupportExports.roundTripUInt16(_: UInt16.bridgeJSLiftParameter(v)) - return ret.bridgeJSLowerReturn() + OptionalSupportExports.takeOptionalJSObject(_: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_IntegerTypesSupportExports_static_roundTripInt32") -@_cdecl("bjs_IntegerTypesSupportExports_static_roundTripInt32") -public func _bjs_IntegerTypesSupportExports_static_roundTripInt32(_ v: Int32) -> Int32 { +@_expose(wasm, "bjs_OptionalSupportExports_static_applyOptionalGreeter") +@_cdecl("bjs_OptionalSupportExports_static_applyOptionalGreeter") +public func _bjs_OptionalSupportExports_static_applyOptionalGreeter(_ valueIsSome: Int32, _ valueValue: UnsafeMutableRawPointer, _ transform: Int32) -> Void { #if arch(wasm32) - let ret = IntegerTypesSupportExports.roundTripInt32(_: Int32.bridgeJSLiftParameter(v)) + let ret = OptionalSupportExports.applyOptionalGreeter(_: Optional.bridgeJSLiftParameter(valueIsSome, valueValue), _: _BJS_Closure_20BridgeJSRuntimeTestsSq7GreeterC_Sq7GreeterC.bridgeJSLift(transform)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_IntegerTypesSupportExports_static_roundTripUInt32") -@_cdecl("bjs_IntegerTypesSupportExports_static_roundTripUInt32") -public func _bjs_IntegerTypesSupportExports_static_roundTripUInt32(_ v: Int32) -> Int32 { +@_expose(wasm, "bjs_OptionalSupportExports_static_makeOptionalHolder") +@_cdecl("bjs_OptionalSupportExports_static_makeOptionalHolder") +public func _bjs_OptionalSupportExports_static_makeOptionalHolder(_ nullableGreeterIsSome: Int32, _ nullableGreeterValue: UnsafeMutableRawPointer, _ undefinedNumberIsSome: Int32, _ undefinedNumberValue: Float64) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = IntegerTypesSupportExports.roundTripUInt32(_: UInt32.bridgeJSLiftParameter(v)) + let ret = OptionalSupportExports.makeOptionalHolder(nullableGreeter: Optional.bridgeJSLiftParameter(nullableGreeterIsSome, nullableGreeterValue), undefinedNumber: JSUndefinedOr.bridgeJSLiftParameter(undefinedNumberIsSome, undefinedNumberValue)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_IntegerTypesSupportExports_static_roundTripInt64") -@_cdecl("bjs_IntegerTypesSupportExports_static_roundTripInt64") -public func _bjs_IntegerTypesSupportExports_static_roundTripInt64(_ v: Int64) -> Int64 { +@_expose(wasm, "bjs_OptionalSupportExports_static_compareAPIResults") +@_cdecl("bjs_OptionalSupportExports_static_compareAPIResults") +public func _bjs_OptionalSupportExports_static_compareAPIResults(_ r1IsSome: Int32, _ r1CaseId: Int32, _ r2IsSome: Int32, _ r2CaseId: Int32) -> Void { #if arch(wasm32) - let ret = IntegerTypesSupportExports.roundTripInt64(_: Int64.bridgeJSLiftParameter(v)) + let _tmp_r2 = Optional.bridgeJSLiftParameter(r2IsSome, r2CaseId) + let _tmp_r1 = Optional.bridgeJSLiftParameter(r1IsSome, r1CaseId) + let ret = OptionalSupportExports.compareAPIResults(_: _tmp_r1, _: _tmp_r2) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_IntegerTypesSupportExports_static_roundTripUInt64") -@_cdecl("bjs_IntegerTypesSupportExports_static_roundTripUInt64") -public func _bjs_IntegerTypesSupportExports_static_roundTripUInt64(_ v: Int64) -> Int64 { - #if arch(wasm32) - let ret = IntegerTypesSupportExports.roundTripUInt64(_: UInt64.bridgeJSLiftParameter(v)) - return ret.bridgeJSLowerReturn() - #else +extension OptionalAllTypesResult: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> OptionalAllTypesResult { + switch caseId { + case 0: + return .optStruct(Optional
.bridgeJSStackPop()) + case 1: + return .optClass(Optional.bridgeJSStackPop()) + case 2: + return .optJSObject(Optional.bridgeJSStackPop()) + case 3: + return .optNestedEnum(Optional.bridgeJSStackPop()) + case 4: + return .optArray(Optional<[Int]>.bridgeJSStackPop()) + case 5: + return .optJsClass(Optional.bridgeJSStackPop().map { Foo(unsafelyWrapping: $0) }) + case 6: + return .empty + default: + fatalError("Unknown OptionalAllTypesResult case ID: \(caseId)") + } + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { + switch self { + case .optStruct(let param0): + param0.bridgeJSStackPush() + return Int32(0) + case .optClass(let param0): + param0.bridgeJSStackPush() + return Int32(1) + case .optJSObject(let param0): + param0.bridgeJSStackPush() + return Int32(2) + case .optNestedEnum(let param0): + param0.bridgeJSStackPush() + return Int32(3) + case .optArray(let param0): + param0.bridgeJSStackPush() + return Int32(4) + case .optJsClass(let param0): + param0.bridgeJSStackPush() + return Int32(5) + case .empty: + return Int32(6) + } + } +} + +extension APIOptionalResult: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> APIOptionalResult { + switch caseId { + case 0: + return .success(Optional.bridgeJSStackPop()) + case 1: + return .failure(Optional.bridgeJSStackPop(), Optional.bridgeJSStackPop()) + case 2: + return .status(Optional.bridgeJSStackPop(), Optional.bridgeJSStackPop(), Optional.bridgeJSStackPop()) + default: + fatalError("Unknown APIOptionalResult case ID: \(caseId)") + } + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { + switch self { + case .success(let param0): + param0.bridgeJSStackPush() + return Int32(0) + case .failure(let param0, let param1): + param0.bridgeJSStackPush() + param1.bridgeJSStackPush() + return Int32(1) + case .status(let param0, let param1, let param2): + param0.bridgeJSStackPush() + param1.bridgeJSStackPush() + param2.bridgeJSStackPush() + return Int32(2) + } + } +} + +extension JSCoordinate: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> JSCoordinate { + let longitude = Double.bridgeJSStackPop() + let latitude = Double.bridgeJSStackPop() + return JSCoordinate(latitude: latitude, longitude: longitude) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.latitude.bridgeJSStackPush() + self.longitude.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_JSCoordinate(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_JSCoordinate())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_JSCoordinate") +fileprivate func _bjs_struct_lower_JSCoordinate_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_JSCoordinate_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_JSCoordinate(_ objectId: Int32) -> Void { + return _bjs_struct_lower_JSCoordinate_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_JSCoordinate") +fileprivate func _bjs_struct_lift_JSCoordinate_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_JSCoordinate_extern() -> Int32 { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_JSCoordinate() -> Int32 { + return _bjs_struct_lift_JSCoordinate_extern() } -@_expose(wasm, "bjs_JSTypedArrayExports_static_roundTripUint8Array") -@_cdecl("bjs_JSTypedArrayExports_static_roundTripUint8Array") -public func _bjs_JSTypedArrayExports_static_roundTripUint8Array(_ v: Int32) -> Int32 { +@_expose(wasm, "bjs_JSCoordinate_init") +@_cdecl("bjs_JSCoordinate_init") +public func _bjs_JSCoordinate_init(_ latitude: Float64, _ longitude: Float64) -> Void { #if arch(wasm32) - let ret = JSTypedArrayExports.roundTripUint8Array(_: JSUint8Array.bridgeJSLiftParameter(v)) + let ret = JSCoordinate(latitude: Double.bridgeJSLiftParameter(latitude), longitude: Double.bridgeJSLiftParameter(longitude)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_JSTypedArrayExports_static_roundTripFloat32Array") -@_cdecl("bjs_JSTypedArrayExports_static_roundTripFloat32Array") -public func _bjs_JSTypedArrayExports_static_roundTripFloat32Array(_ v: Int32) -> Int32 { - #if arch(wasm32) - let ret = JSTypedArrayExports.roundTripFloat32Array(_: JSFloat32Array.bridgeJSLiftParameter(v)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif +extension NestedStructGroupA.Metadata: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> NestedStructGroupA.Metadata { + let count = Int.bridgeJSStackPop() + let label = String.bridgeJSStackPop() + return NestedStructGroupA.Metadata(label: label, count: count) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.label.bridgeJSStackPush() + self.count.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_NestedStructGroupA_Metadata(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_NestedStructGroupA_Metadata())) + } } -@_expose(wasm, "bjs_JSTypedArrayExports_static_roundTripFloat64Array") -@_cdecl("bjs_JSTypedArrayExports_static_roundTripFloat64Array") -public func _bjs_JSTypedArrayExports_static_roundTripFloat64Array(_ v: Int32) -> Int32 { - #if arch(wasm32) - let ret = JSTypedArrayExports.roundTripFloat64Array(_: JSFloat64Array.bridgeJSLiftParameter(v)) - return ret.bridgeJSLowerReturn() - #else +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_NestedStructGroupA_Metadata") +fileprivate func _bjs_struct_lower_NestedStructGroupA_Metadata_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_NestedStructGroupA_Metadata_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_NestedStructGroupA_Metadata(_ objectId: Int32) -> Void { + return _bjs_struct_lower_NestedStructGroupA_Metadata_extern(objectId) } -@_expose(wasm, "bjs_JSTypedArrayExports_static_roundTripInt32Array") -@_cdecl("bjs_JSTypedArrayExports_static_roundTripInt32Array") -public func _bjs_JSTypedArrayExports_static_roundTripInt32Array(_ v: Int32) -> Int32 { - #if arch(wasm32) - let ret = JSTypedArrayExports.roundTripInt32Array(_: JSInt32Array.bridgeJSLiftParameter(v)) - return ret.bridgeJSLowerReturn() - #else +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_NestedStructGroupA_Metadata") +fileprivate func _bjs_struct_lift_NestedStructGroupA_Metadata_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_NestedStructGroupA_Metadata_extern() -> Int32 { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_NestedStructGroupA_Metadata() -> Int32 { + return _bjs_struct_lift_NestedStructGroupA_Metadata_extern() } -@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalString") -@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalString") -public func _bjs_OptionalSupportExports_static_roundTripOptionalString(_ vIsSome: Int32, _ vBytes: Int32, _ vLength: Int32) -> Void { - #if arch(wasm32) - let ret = OptionalSupportExports.roundTripOptionalString(_: Optional.bridgeJSLiftParameter(vIsSome, vBytes, vLength)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif +extension NestedStructGroupB.Metadata: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> NestedStructGroupB.Metadata { + let value = Double.bridgeJSStackPop() + let tag = String.bridgeJSStackPop() + return NestedStructGroupB.Metadata(tag: tag, value: value) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.tag.bridgeJSStackPush() + self.value.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_NestedStructGroupB_Metadata(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_NestedStructGroupB_Metadata())) + } } -@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalInt") -@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalInt") -public func _bjs_OptionalSupportExports_static_roundTripOptionalInt(_ vIsSome: Int32, _ vValue: Int32) -> Void { - #if arch(wasm32) - let ret = OptionalSupportExports.roundTripOptionalInt(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) - return ret.bridgeJSLowerReturn() - #else +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_NestedStructGroupB_Metadata") +fileprivate func _bjs_struct_lower_NestedStructGroupB_Metadata_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_NestedStructGroupB_Metadata_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_NestedStructGroupB_Metadata(_ objectId: Int32) -> Void { + return _bjs_struct_lower_NestedStructGroupB_Metadata_extern(objectId) } -@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalBool") -@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalBool") -public func _bjs_OptionalSupportExports_static_roundTripOptionalBool(_ vIsSome: Int32, _ vValue: Int32) -> Void { - #if arch(wasm32) - let ret = OptionalSupportExports.roundTripOptionalBool(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) - return ret.bridgeJSLowerReturn() - #else +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_NestedStructGroupB_Metadata") +fileprivate func _bjs_struct_lift_NestedStructGroupB_Metadata_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_NestedStructGroupB_Metadata_extern() -> Int32 { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_NestedStructGroupB_Metadata() -> Int32 { + return _bjs_struct_lift_NestedStructGroupB_Metadata_extern() } -@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalFloat") -@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalFloat") -public func _bjs_OptionalSupportExports_static_roundTripOptionalFloat(_ vIsSome: Int32, _ vValue: Float32) -> Void { - #if arch(wasm32) - let ret = OptionalSupportExports.roundTripOptionalFloat(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif +extension Point: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Point { + let y = Int.bridgeJSStackPop() + let x = Int.bridgeJSStackPop() + return Point(x: x, y: y) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.x.bridgeJSStackPush() + self.y.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_Point(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Point())) + } } -@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalDouble") -@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalDouble") -public func _bjs_OptionalSupportExports_static_roundTripOptionalDouble(_ vIsSome: Int32, _ vValue: Float64) -> Void { - #if arch(wasm32) - let ret = OptionalSupportExports.roundTripOptionalDouble(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) - return ret.bridgeJSLowerReturn() - #else +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Point") +fileprivate func _bjs_struct_lower_Point_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_Point_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_Point(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Point_extern(objectId) } -@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalSyntax") -@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalSyntax") -public func _bjs_OptionalSupportExports_static_roundTripOptionalSyntax(_ vIsSome: Int32, _ vBytes: Int32, _ vLength: Int32) -> Void { - #if arch(wasm32) - let ret = OptionalSupportExports.roundTripOptionalSyntax(_: Optional.bridgeJSLiftParameter(vIsSome, vBytes, vLength)) - return ret.bridgeJSLowerReturn() - #else +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Point") +fileprivate func _bjs_struct_lift_Point_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_Point_extern() -> Int32 { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_Point() -> Int32 { + return _bjs_struct_lift_Point_extern() } -@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalCaseEnum") -@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalCaseEnum") -public func _bjs_OptionalSupportExports_static_roundTripOptionalCaseEnum(_ vIsSome: Int32, _ vValue: Int32) -> Void { - #if arch(wasm32) - let ret = OptionalSupportExports.roundTripOptionalCaseEnum(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif +extension PointerFields: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> PointerFields { + let mutPtr = UnsafeMutablePointer.bridgeJSStackPop() + let ptr = UnsafePointer.bridgeJSStackPop() + let opaque = OpaquePointer.bridgeJSStackPop() + let mutRaw = UnsafeMutableRawPointer.bridgeJSStackPop() + let raw = UnsafeRawPointer.bridgeJSStackPop() + return PointerFields(raw: raw, mutRaw: mutRaw, opaque: opaque, ptr: ptr, mutPtr: mutPtr) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.raw.bridgeJSStackPush() + self.mutRaw.bridgeJSStackPush() + self.opaque.bridgeJSStackPush() + self.ptr.bridgeJSStackPush() + self.mutPtr.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_PointerFields(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_PointerFields())) + } } -@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalStringRawValueEnum") -@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalStringRawValueEnum") -public func _bjs_OptionalSupportExports_static_roundTripOptionalStringRawValueEnum(_ vIsSome: Int32, _ vBytes: Int32, _ vLength: Int32) -> Void { - #if arch(wasm32) - let ret = OptionalSupportExports.roundTripOptionalStringRawValueEnum(_: Optional.bridgeJSLiftParameter(vIsSome, vBytes, vLength)) - return ret.bridgeJSLowerReturn() - #else +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_PointerFields") +fileprivate func _bjs_struct_lower_PointerFields_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_PointerFields_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_PointerFields(_ objectId: Int32) -> Void { + return _bjs_struct_lower_PointerFields_extern(objectId) } -@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalIntRawValueEnum") -@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalIntRawValueEnum") -public func _bjs_OptionalSupportExports_static_roundTripOptionalIntRawValueEnum(_ vIsSome: Int32, _ vValue: Int32) -> Void { - #if arch(wasm32) - let ret = OptionalSupportExports.roundTripOptionalIntRawValueEnum(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) - return ret.bridgeJSLowerReturn() - #else +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_PointerFields") +fileprivate func _bjs_struct_lift_PointerFields_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_PointerFields_extern() -> Int32 { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_PointerFields() -> Int32 { + return _bjs_struct_lift_PointerFields_extern() } -@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalInt64RawValueEnum") -@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalInt64RawValueEnum") -public func _bjs_OptionalSupportExports_static_roundTripOptionalInt64RawValueEnum(_ vIsSome: Int32, _ vValue: Int64) -> Void { +@_expose(wasm, "bjs_PointerFields_init") +@_cdecl("bjs_PointerFields_init") +public func _bjs_PointerFields_init(_ raw: UnsafeMutableRawPointer, _ mutRaw: UnsafeMutableRawPointer, _ opaque: UnsafeMutableRawPointer, _ ptr: UnsafeMutableRawPointer, _ mutPtr: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = OptionalSupportExports.roundTripOptionalInt64RawValueEnum(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) + let ret = PointerFields(raw: UnsafeRawPointer.bridgeJSLiftParameter(raw), mutRaw: UnsafeMutableRawPointer.bridgeJSLiftParameter(mutRaw), opaque: OpaquePointer.bridgeJSLiftParameter(opaque), ptr: UnsafePointer.bridgeJSLiftParameter(ptr), mutPtr: UnsafeMutablePointer.bridgeJSLiftParameter(mutPtr)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalUInt64RawValueEnum") -@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalUInt64RawValueEnum") -public func _bjs_OptionalSupportExports_static_roundTripOptionalUInt64RawValueEnum(_ vIsSome: Int32, _ vValue: Int64) -> Void { - #if arch(wasm32) - let ret = OptionalSupportExports.roundTripOptionalUInt64RawValueEnum(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif +extension DataPoint: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> DataPoint { + let optFlag = Optional.bridgeJSStackPop() + let optCount = Optional.bridgeJSStackPop() + let label = String.bridgeJSStackPop() + let y = Double.bridgeJSStackPop() + let x = Double.bridgeJSStackPop() + return DataPoint(x: x, y: y, label: label, optCount: optCount, optFlag: optFlag) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.x.bridgeJSStackPush() + self.y.bridgeJSStackPush() + self.label.bridgeJSStackPush() + self.optCount.bridgeJSStackPush() + self.optFlag.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_DataPoint(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_DataPoint())) + } } -@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalTSEnum") -@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalTSEnum") -public func _bjs_OptionalSupportExports_static_roundTripOptionalTSEnum(_ vIsSome: Int32, _ vValue: Int32) -> Void { - #if arch(wasm32) - let ret = OptionalSupportExports.roundTripOptionalTSEnum(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) - return ret.bridgeJSLowerReturn() - #else +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_DataPoint") +fileprivate func _bjs_struct_lower_DataPoint_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_DataPoint_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_DataPoint(_ objectId: Int32) -> Void { + return _bjs_struct_lower_DataPoint_extern(objectId) } -@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalTSStringEnum") -@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalTSStringEnum") -public func _bjs_OptionalSupportExports_static_roundTripOptionalTSStringEnum(_ vIsSome: Int32, _ vBytes: Int32, _ vLength: Int32) -> Void { - #if arch(wasm32) - let ret = OptionalSupportExports.roundTripOptionalTSStringEnum(_: Optional.bridgeJSLiftParameter(vIsSome, vBytes, vLength)) - return ret.bridgeJSLowerReturn() - #else +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_DataPoint") +fileprivate func _bjs_struct_lift_DataPoint_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_DataPoint_extern() -> Int32 { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_DataPoint() -> Int32 { + return _bjs_struct_lift_DataPoint_extern() } -@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalNamespacedEnum") -@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalNamespacedEnum") -public func _bjs_OptionalSupportExports_static_roundTripOptionalNamespacedEnum(_ vIsSome: Int32, _ vValue: Int32) -> Void { +@_expose(wasm, "bjs_DataPoint_init") +@_cdecl("bjs_DataPoint_init") +public func _bjs_DataPoint_init(_ x: Float64, _ y: Float64, _ labelBytes: Int32, _ labelLength: Int32, _ optCountIsSome: Int32, _ optCountValue: Int32, _ optFlagIsSome: Int32, _ optFlagValue: Int32) -> Void { #if arch(wasm32) - let ret = OptionalSupportExports.roundTripOptionalNamespacedEnum(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) + let ret = DataPoint(x: Double.bridgeJSLiftParameter(x), y: Double.bridgeJSLiftParameter(y), label: String.bridgeJSLiftParameter(labelBytes, labelLength), optCount: Optional.bridgeJSLiftParameter(optCountIsSome, optCountValue), optFlag: Optional.bridgeJSLiftParameter(optFlagIsSome, optFlagValue)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalSwiftClass") -@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalSwiftClass") -public func _bjs_OptionalSupportExports_static_roundTripOptionalSwiftClass(_ vIsSome: Int32, _ vValue: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_DataPoint_static_dimensions_get") +@_cdecl("bjs_DataPoint_static_dimensions_get") +public func _bjs_DataPoint_static_dimensions_get() -> Int32 { #if arch(wasm32) - let ret = OptionalSupportExports.roundTripOptionalSwiftClass(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) + let ret = DataPoint.dimensions return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalIntArray") -@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalIntArray") -public func _bjs_OptionalSupportExports_static_roundTripOptionalIntArray() -> Void { +@_expose(wasm, "bjs_DataPoint_static_origin") +@_cdecl("bjs_DataPoint_static_origin") +public func _bjs_DataPoint_static_origin() -> Void { #if arch(wasm32) - let ret = OptionalSupportExports.roundTripOptionalIntArray(_: Optional<[Int]>.bridgeJSLiftParameter()) - ret.bridgeJSStackPush() + let ret = DataPoint.origin() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalStringArray") -@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalStringArray") -public func _bjs_OptionalSupportExports_static_roundTripOptionalStringArray() -> Void { - #if arch(wasm32) - let ret = OptionalSupportExports.roundTripOptionalStringArray(_: Optional<[String]>.bridgeJSLiftParameter()) - ret.bridgeJSStackPush() - #else - fatalError("Only available on WebAssembly") - #endif -} +extension PublicPoint: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> PublicPoint { + let y = Int.bridgeJSStackPop() + let x = Int.bridgeJSStackPop() + return PublicPoint(x: x, y: y) + } -@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalSwiftClassArray") -@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalSwiftClassArray") -public func _bjs_OptionalSupportExports_static_roundTripOptionalSwiftClassArray() -> Void { - #if arch(wasm32) - let ret = OptionalSupportExports.roundTripOptionalSwiftClassArray(_: Optional<[Greeter]>.bridgeJSLiftParameter()) - ret.bridgeJSStackPush() - #else - fatalError("Only available on WebAssembly") - #endif + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.x.bridgeJSStackPush() + self.y.bridgeJSStackPush() + } + + public init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_PublicPoint(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + public func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_PublicPoint())) + } } -@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalAPIResult") -@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalAPIResult") -public func _bjs_OptionalSupportExports_static_roundTripOptionalAPIResult(_ vIsSome: Int32, _ vCaseId: Int32) -> Void { - #if arch(wasm32) - let ret = OptionalSupportExports.roundTripOptionalAPIResult(_: Optional.bridgeJSLiftParameter(vIsSome, vCaseId)) - return ret.bridgeJSLowerReturn() - #else +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_PublicPoint") +fileprivate func _bjs_struct_lower_PublicPoint_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_PublicPoint_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_PublicPoint(_ objectId: Int32) -> Void { + return _bjs_struct_lower_PublicPoint_extern(objectId) } -@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalTypedPayloadResult") -@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalTypedPayloadResult") -public func _bjs_OptionalSupportExports_static_roundTripOptionalTypedPayloadResult(_ vIsSome: Int32, _ vCaseId: Int32) -> Void { - #if arch(wasm32) - let ret = OptionalSupportExports.roundTripOptionalTypedPayloadResult(_: Optional.bridgeJSLiftParameter(vIsSome, vCaseId)) - return ret.bridgeJSLowerReturn() - #else +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_PublicPoint") +fileprivate func _bjs_struct_lift_PublicPoint_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_PublicPoint_extern() -> Int32 { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_PublicPoint() -> Int32 { + return _bjs_struct_lift_PublicPoint_extern() } -@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalComplexResult") -@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalComplexResult") -public func _bjs_OptionalSupportExports_static_roundTripOptionalComplexResult(_ vIsSome: Int32, _ vCaseId: Int32) -> Void { +@_expose(wasm, "bjs_PublicPoint_init") +@_cdecl("bjs_PublicPoint_init") +public func _bjs_PublicPoint_init(_ x: Int32, _ y: Int32) -> Void { #if arch(wasm32) - let ret = OptionalSupportExports.roundTripOptionalComplexResult(_: Optional.bridgeJSLiftParameter(vIsSome, vCaseId)) + let ret = PublicPoint(x: Int.bridgeJSLiftParameter(x), y: Int.bridgeJSLiftParameter(y)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalAllTypesResult") -@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalAllTypesResult") -public func _bjs_OptionalSupportExports_static_roundTripOptionalAllTypesResult(_ vIsSome: Int32, _ vCaseId: Int32) -> Void { - #if arch(wasm32) - let ret = OptionalSupportExports.roundTripOptionalAllTypesResult(_: Optional.bridgeJSLiftParameter(vIsSome, vCaseId)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif +extension Address: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Address { + let zipCode = Optional.bridgeJSStackPop() + let city = String.bridgeJSStackPop() + let street = String.bridgeJSStackPop() + return Address(street: street, city: city, zipCode: zipCode) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.street.bridgeJSStackPush() + self.city.bridgeJSStackPush() + self.zipCode.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_Address(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Address())) + } } -@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalPayloadResult") -@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalPayloadResult") -public func _bjs_OptionalSupportExports_static_roundTripOptionalPayloadResult(_ v: Int32) -> Void { - #if arch(wasm32) - let ret = OptionalSupportExports.roundTripOptionalPayloadResult(_: OptionalAllTypesResult.bridgeJSLiftParameter(v)) - return ret.bridgeJSLowerReturn() - #else +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Address") +fileprivate func _bjs_struct_lower_Address_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_Address_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") - #endif } - -@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalPayloadResultOpt") -@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalPayloadResultOpt") -public func _bjs_OptionalSupportExports_static_roundTripOptionalPayloadResultOpt(_ vIsSome: Int32, _ vCaseId: Int32) -> Void { - #if arch(wasm32) - let ret = OptionalSupportExports.roundTripOptionalPayloadResultOpt(_: Optional.bridgeJSLiftParameter(vIsSome, vCaseId)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif +#endif +@inline(never) fileprivate func _bjs_struct_lower_Address(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Address_extern(objectId) } -@_expose(wasm, "bjs_OptionalSupportExports_static_roundTripOptionalAPIOptionalResult") -@_cdecl("bjs_OptionalSupportExports_static_roundTripOptionalAPIOptionalResult") -public func _bjs_OptionalSupportExports_static_roundTripOptionalAPIOptionalResult(_ vIsSome: Int32, _ vCaseId: Int32) -> Void { - #if arch(wasm32) - let ret = OptionalSupportExports.roundTripOptionalAPIOptionalResult(_: Optional.bridgeJSLiftParameter(vIsSome, vCaseId)) - return ret.bridgeJSLowerReturn() - #else +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Address") +fileprivate func _bjs_struct_lift_Address_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_Address_extern() -> Int32 { fatalError("Only available on WebAssembly") - #endif } - -@_expose(wasm, "bjs_OptionalSupportExports_static_takeOptionalJSObject") -@_cdecl("bjs_OptionalSupportExports_static_takeOptionalJSObject") -public func _bjs_OptionalSupportExports_static_takeOptionalJSObject(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { - #if arch(wasm32) - OptionalSupportExports.takeOptionalJSObject(_: Optional.bridgeJSLiftParameter(valueIsSome, valueValue)) - #else - fatalError("Only available on WebAssembly") - #endif +#endif +@inline(never) fileprivate func _bjs_struct_lift_Address() -> Int32 { + return _bjs_struct_lift_Address_extern() } -@_expose(wasm, "bjs_OptionalSupportExports_static_applyOptionalGreeter") -@_cdecl("bjs_OptionalSupportExports_static_applyOptionalGreeter") -public func _bjs_OptionalSupportExports_static_applyOptionalGreeter(_ valueIsSome: Int32, _ valueValue: UnsafeMutableRawPointer, _ transform: Int32) -> Void { - #if arch(wasm32) - let ret = OptionalSupportExports.applyOptionalGreeter(_: Optional.bridgeJSLiftParameter(valueIsSome, valueValue), _: _BJS_Closure_20BridgeJSRuntimeTestsSq7GreeterC_Sq7GreeterC.bridgeJSLift(transform)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif +extension Contact: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Contact { + let secondaryAddress = Optional
.bridgeJSStackPop() + let email = Optional.bridgeJSStackPop() + let address = Address.bridgeJSStackPop() + let age = Int.bridgeJSStackPop() + let name = String.bridgeJSStackPop() + return Contact(name: name, age: age, address: address, email: email, secondaryAddress: secondaryAddress) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.name.bridgeJSStackPush() + self.age.bridgeJSStackPush() + self.address.bridgeJSStackPush() + self.email.bridgeJSStackPush() + self.secondaryAddress.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_Contact(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Contact())) + } } -@_expose(wasm, "bjs_OptionalSupportExports_static_makeOptionalHolder") -@_cdecl("bjs_OptionalSupportExports_static_makeOptionalHolder") -public func _bjs_OptionalSupportExports_static_makeOptionalHolder(_ nullableGreeterIsSome: Int32, _ nullableGreeterValue: UnsafeMutableRawPointer, _ undefinedNumberIsSome: Int32, _ undefinedNumberValue: Float64) -> UnsafeMutableRawPointer { - #if arch(wasm32) - let ret = OptionalSupportExports.makeOptionalHolder(nullableGreeter: Optional.bridgeJSLiftParameter(nullableGreeterIsSome, nullableGreeterValue), undefinedNumber: JSUndefinedOr.bridgeJSLiftParameter(undefinedNumberIsSome, undefinedNumberValue)) - return ret.bridgeJSLowerReturn() - #else +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Contact") +fileprivate func _bjs_struct_lower_Contact_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_Contact_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_Contact(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Contact_extern(objectId) } -@_expose(wasm, "bjs_OptionalSupportExports_static_compareAPIResults") -@_cdecl("bjs_OptionalSupportExports_static_compareAPIResults") -public func _bjs_OptionalSupportExports_static_compareAPIResults(_ r1IsSome: Int32, _ r1CaseId: Int32, _ r2IsSome: Int32, _ r2CaseId: Int32) -> Void { - #if arch(wasm32) - let _tmp_r2 = Optional.bridgeJSLiftParameter(r2IsSome, r2CaseId) - let _tmp_r1 = Optional.bridgeJSLiftParameter(r1IsSome, r1CaseId) - let ret = OptionalSupportExports.compareAPIResults(_: _tmp_r1, _: _tmp_r2) - return ret.bridgeJSLowerReturn() - #else +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Contact") +fileprivate func _bjs_struct_lift_Contact_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_Contact_extern() -> Int32 { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_Contact() -> Int32 { + return _bjs_struct_lift_Contact_extern() } -extension OptionalAllTypesResult: _BridgedSwiftAssociatedValueEnum { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> OptionalAllTypesResult { - switch caseId { - case 0: - return .optStruct(Optional
.bridgeJSStackPop()) - case 1: - return .optClass(Optional.bridgeJSStackPop()) - case 2: - return .optJSObject(Optional.bridgeJSStackPop()) - case 3: - return .optNestedEnum(Optional.bridgeJSStackPop()) - case 4: - return .optArray(Optional<[Int]>.bridgeJSStackPop()) - case 5: - return .optJsClass(Optional.bridgeJSStackPop().map { Foo(unsafelyWrapping: $0) }) - case 6: - return .empty - default: - fatalError("Unknown OptionalAllTypesResult case ID: \(caseId)") - } +extension Config: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Config { + let status = Status.bridgeJSStackPop() + let direction = Optional.bridgeJSStackPop() + let theme = Optional.bridgeJSStackPop() + let name = String.bridgeJSStackPop() + return Config(name: name, theme: theme, direction: direction, status: status) } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { - switch self { - case .optStruct(let param0): - param0.bridgeJSStackPush() - return Int32(0) - case .optClass(let param0): - param0.bridgeJSStackPush() - return Int32(1) - case .optJSObject(let param0): - param0.bridgeJSStackPush() - return Int32(2) - case .optNestedEnum(let param0): - param0.bridgeJSStackPush() - return Int32(3) - case .optArray(let param0): - param0.bridgeJSStackPush() - return Int32(4) - case .optJsClass(let param0): - param0.bridgeJSStackPush() - return Int32(5) - case .empty: - return Int32(6) - } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.name.bridgeJSStackPush() + self.theme.bridgeJSStackPush() + self.direction.bridgeJSStackPush() + self.status.bridgeJSStackPush() } -} -extension APIOptionalResult: _BridgedSwiftAssociatedValueEnum { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> APIOptionalResult { - switch caseId { - case 0: - return .success(Optional.bridgeJSStackPop()) - case 1: - return .failure(Optional.bridgeJSStackPop(), Optional.bridgeJSStackPop()) - case 2: - return .status(Optional.bridgeJSStackPop(), Optional.bridgeJSStackPop(), Optional.bridgeJSStackPop()) - default: - fatalError("Unknown APIOptionalResult case ID: \(caseId)") - } + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_Config(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() } - @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { - switch self { - case .success(let param0): - param0.bridgeJSStackPush() - return Int32(0) - case .failure(let param0, let param1): - param0.bridgeJSStackPush() - param1.bridgeJSStackPush() - return Int32(1) - case .status(let param0, let param1, let param2): - param0.bridgeJSStackPush() - param1.bridgeJSStackPush() - param2.bridgeJSStackPush() - return Int32(2) - } + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Config())) } } -extension JSCoordinate: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> JSCoordinate { - let longitude = Double.bridgeJSStackPop() - let latitude = Double.bridgeJSStackPop() - return JSCoordinate(latitude: latitude, longitude: longitude) +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Config") +fileprivate func _bjs_struct_lower_Config_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_Config_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_Config(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Config_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Config") +fileprivate func _bjs_struct_lift_Config_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_Config_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_Config() -> Int32 { + return _bjs_struct_lift_Config_extern() +} + +extension SessionData: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> SessionData { + let owner = Optional.bridgeJSStackPop() + let id = Int.bridgeJSStackPop() + return SessionData(id: id, owner: owner) } @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { - self.latitude.bridgeJSStackPush() - self.longitude.bridgeJSStackPush() + self.id.bridgeJSStackPush() + self.owner.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { - _bjs_struct_lower_JSCoordinate(jsObject.bridgeJSLowerParameter()) + _bjs_struct_lower_SessionData(jsObject.bridgeJSLowerParameter()) self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self __bjs_self.bridgeJSStackPush() - return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_JSCoordinate())) + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_SessionData())) } } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_JSCoordinate") -fileprivate func _bjs_struct_lower_JSCoordinate_extern(_ objectId: Int32) -> Void +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_SessionData") +fileprivate func _bjs_struct_lower_SessionData_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_JSCoordinate_extern(_ objectId: Int32) -> Void { +fileprivate func _bjs_struct_lower_SessionData_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_struct_lower_JSCoordinate(_ objectId: Int32) -> Void { - return _bjs_struct_lower_JSCoordinate_extern(objectId) +@inline(never) fileprivate func _bjs_struct_lower_SessionData(_ objectId: Int32) -> Void { + return _bjs_struct_lower_SessionData_extern(objectId) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_JSCoordinate") -fileprivate func _bjs_struct_lift_JSCoordinate_extern() -> Int32 +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_SessionData") +fileprivate func _bjs_struct_lift_SessionData_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_JSCoordinate_extern() -> Int32 { +fileprivate func _bjs_struct_lift_SessionData_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_struct_lift_JSCoordinate() -> Int32 { - return _bjs_struct_lift_JSCoordinate_extern() -} - -@_expose(wasm, "bjs_JSCoordinate_init") -@_cdecl("bjs_JSCoordinate_init") -public func _bjs_JSCoordinate_init(_ latitude: Float64, _ longitude: Float64) -> Void { - #if arch(wasm32) - let ret = JSCoordinate(latitude: Double.bridgeJSLiftParameter(latitude), longitude: Double.bridgeJSLiftParameter(longitude)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif +@inline(never) fileprivate func _bjs_struct_lift_SessionData() -> Int32 { + return _bjs_struct_lift_SessionData_extern() } -extension SessionState: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> SessionState { - let token = String.bridgeJSStackPop() - return SessionState(token: token) +extension ValidationReport: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> ValidationReport { + let outcome = Optional.bridgeJSStackPop() + let status = Optional.bridgeJSStackPop() + let result = APIResult.bridgeJSStackPop() + let id = Int.bridgeJSStackPop() + return ValidationReport(id: id, result: result, status: status, outcome: outcome) } @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { - self.token.bridgeJSStackPush() + self.id.bridgeJSStackPush() + self.result.bridgeJSStackPush() + self.status.bridgeJSStackPush() + self.outcome.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { - _bjs_struct_lower_SessionState(jsObject.bridgeJSLowerParameter()) + _bjs_struct_lower_ValidationReport(jsObject.bridgeJSLowerParameter()) self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self __bjs_self.bridgeJSStackPush() - return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_SessionState())) + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_ValidationReport())) } } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_SessionState") -fileprivate func _bjs_struct_lower_SessionState_extern(_ objectId: Int32) -> Void +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_ValidationReport") +fileprivate func _bjs_struct_lower_ValidationReport_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_SessionState_extern(_ objectId: Int32) -> Void { +fileprivate func _bjs_struct_lower_ValidationReport_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_struct_lower_SessionState(_ objectId: Int32) -> Void { - return _bjs_struct_lower_SessionState_extern(objectId) +@inline(never) fileprivate func _bjs_struct_lower_ValidationReport(_ objectId: Int32) -> Void { + return _bjs_struct_lower_ValidationReport_extern(objectId) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_SessionState") -fileprivate func _bjs_struct_lift_SessionState_extern() -> Int32 +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_ValidationReport") +fileprivate func _bjs_struct_lift_ValidationReport_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_SessionState_extern() -> Int32 { +fileprivate func _bjs_struct_lift_ValidationReport_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_struct_lift_SessionState() -> Int32 { - return _bjs_struct_lift_SessionState_extern() -} - -@_expose(wasm, "bjs_SessionState_init") -@_cdecl("bjs_SessionState_init") -public func _bjs_SessionState_init(_ tokenBytes: Int32, _ tokenLength: Int32) -> Void { - #if arch(wasm32) - let ret = SessionState(token: String.bridgeJSLiftParameter(tokenBytes, tokenLength)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif +@inline(never) fileprivate func _bjs_struct_lift_ValidationReport() -> Int32 { + return _bjs_struct_lift_ValidationReport_extern() } -extension NestedStructGroupA.Metadata: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> NestedStructGroupA.Metadata { - let count = Int.bridgeJSStackPop() - let label = String.bridgeJSStackPop() - return NestedStructGroupA.Metadata(label: label, count: count) +extension AdvancedConfig: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> AdvancedConfig { + let overrideDefaults = Optional.bridgeJSStackPop() + let defaults = ConfigStruct.bridgeJSStackPop() + let location = Optional.bridgeJSStackPop() + let metadata = Optional.bridgeJSStackPop() + let result = Optional.bridgeJSStackPop() + let status = Status.bridgeJSStackPop() + let theme = Theme.bridgeJSStackPop() + let enabled = Bool.bridgeJSStackPop() + let title = String.bridgeJSStackPop() + let id = Int.bridgeJSStackPop() + return AdvancedConfig(id: id, title: title, enabled: enabled, theme: theme, status: status, result: result, metadata: metadata, location: location, defaults: defaults, overrideDefaults: overrideDefaults) } @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { - self.label.bridgeJSStackPush() - self.count.bridgeJSStackPush() + self.id.bridgeJSStackPush() + self.title.bridgeJSStackPush() + self.enabled.bridgeJSStackPush() + self.theme.bridgeJSStackPush() + self.status.bridgeJSStackPush() + self.result.bridgeJSStackPush() + self.metadata.bridgeJSStackPush() + self.location.bridgeJSStackPush() + self.defaults.bridgeJSStackPush() + self.overrideDefaults.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { - _bjs_struct_lower_NestedStructGroupA_Metadata(jsObject.bridgeJSLowerParameter()) + _bjs_struct_lower_AdvancedConfig(jsObject.bridgeJSLowerParameter()) self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self __bjs_self.bridgeJSStackPush() - return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_NestedStructGroupA_Metadata())) + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_AdvancedConfig())) } } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_NestedStructGroupA_Metadata") -fileprivate func _bjs_struct_lower_NestedStructGroupA_Metadata_extern(_ objectId: Int32) -> Void +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_AdvancedConfig") +fileprivate func _bjs_struct_lower_AdvancedConfig_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_NestedStructGroupA_Metadata_extern(_ objectId: Int32) -> Void { +fileprivate func _bjs_struct_lower_AdvancedConfig_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_struct_lower_NestedStructGroupA_Metadata(_ objectId: Int32) -> Void { - return _bjs_struct_lower_NestedStructGroupA_Metadata_extern(objectId) +@inline(never) fileprivate func _bjs_struct_lower_AdvancedConfig(_ objectId: Int32) -> Void { + return _bjs_struct_lower_AdvancedConfig_extern(objectId) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_NestedStructGroupA_Metadata") -fileprivate func _bjs_struct_lift_NestedStructGroupA_Metadata_extern() -> Int32 +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_AdvancedConfig") +fileprivate func _bjs_struct_lift_AdvancedConfig_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_NestedStructGroupA_Metadata_extern() -> Int32 { +fileprivate func _bjs_struct_lift_AdvancedConfig_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_struct_lift_NestedStructGroupA_Metadata() -> Int32 { - return _bjs_struct_lift_NestedStructGroupA_Metadata_extern() +@inline(never) fileprivate func _bjs_struct_lift_AdvancedConfig() -> Int32 { + return _bjs_struct_lift_AdvancedConfig_extern() } -extension NestedStructGroupB.Metadata: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> NestedStructGroupB.Metadata { - let value = Double.bridgeJSStackPop() - let tag = String.bridgeJSStackPop() - return NestedStructGroupB.Metadata(tag: tag, value: value) +extension MeasurementConfig: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> MeasurementConfig { + let optionalRatio = Optional.bridgeJSStackPop() + let optionalPrecision = Optional.bridgeJSStackPop() + let ratio = Ratio.bridgeJSStackPop() + let precision = Precision.bridgeJSStackPop() + return MeasurementConfig(precision: precision, ratio: ratio, optionalPrecision: optionalPrecision, optionalRatio: optionalRatio) } @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { - self.tag.bridgeJSStackPush() - self.value.bridgeJSStackPush() + self.precision.bridgeJSStackPush() + self.ratio.bridgeJSStackPush() + self.optionalPrecision.bridgeJSStackPush() + self.optionalRatio.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { - _bjs_struct_lower_NestedStructGroupB_Metadata(jsObject.bridgeJSLowerParameter()) + _bjs_struct_lower_MeasurementConfig(jsObject.bridgeJSLowerParameter()) self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self __bjs_self.bridgeJSStackPush() - return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_NestedStructGroupB_Metadata())) + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_MeasurementConfig())) } } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_NestedStructGroupB_Metadata") -fileprivate func _bjs_struct_lower_NestedStructGroupB_Metadata_extern(_ objectId: Int32) -> Void +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_MeasurementConfig") +fileprivate func _bjs_struct_lower_MeasurementConfig_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_NestedStructGroupB_Metadata_extern(_ objectId: Int32) -> Void { +fileprivate func _bjs_struct_lower_MeasurementConfig_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_struct_lower_NestedStructGroupB_Metadata(_ objectId: Int32) -> Void { - return _bjs_struct_lower_NestedStructGroupB_Metadata_extern(objectId) +@inline(never) fileprivate func _bjs_struct_lower_MeasurementConfig(_ objectId: Int32) -> Void { + return _bjs_struct_lower_MeasurementConfig_extern(objectId) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_NestedStructGroupB_Metadata") -fileprivate func _bjs_struct_lift_NestedStructGroupB_Metadata_extern() -> Int32 +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_MeasurementConfig") +fileprivate func _bjs_struct_lift_MeasurementConfig_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_NestedStructGroupB_Metadata_extern() -> Int32 { +fileprivate func _bjs_struct_lift_MeasurementConfig_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_struct_lift_NestedStructGroupB_Metadata() -> Int32 { - return _bjs_struct_lift_NestedStructGroupB_Metadata_extern() +@inline(never) fileprivate func _bjs_struct_lift_MeasurementConfig() -> Int32 { + return _bjs_struct_lift_MeasurementConfig_extern() } -extension Point: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Point { - let y = Int.bridgeJSStackPop() - let x = Int.bridgeJSStackPop() - return Point(x: x, y: y) +extension MathOperations: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> MathOperations { + let baseValue = Double.bridgeJSStackPop() + return MathOperations(baseValue: baseValue) } @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { - self.x.bridgeJSStackPush() - self.y.bridgeJSStackPush() + self.baseValue.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { - _bjs_struct_lower_Point(jsObject.bridgeJSLowerParameter()) + _bjs_struct_lower_MathOperations(jsObject.bridgeJSLowerParameter()) self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self __bjs_self.bridgeJSStackPush() - return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Point())) + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_MathOperations())) } } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Point") -fileprivate func _bjs_struct_lower_Point_extern(_ objectId: Int32) -> Void +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_MathOperations") +fileprivate func _bjs_struct_lower_MathOperations_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_Point_extern(_ objectId: Int32) -> Void { +fileprivate func _bjs_struct_lower_MathOperations_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_struct_lower_Point(_ objectId: Int32) -> Void { - return _bjs_struct_lower_Point_extern(objectId) +@inline(never) fileprivate func _bjs_struct_lower_MathOperations(_ objectId: Int32) -> Void { + return _bjs_struct_lower_MathOperations_extern(objectId) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Point") -fileprivate func _bjs_struct_lift_Point_extern() -> Int32 +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_MathOperations") +fileprivate func _bjs_struct_lift_MathOperations_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_Point_extern() -> Int32 { +fileprivate func _bjs_struct_lift_MathOperations_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_struct_lift_Point() -> Int32 { - return _bjs_struct_lift_Point_extern() +@inline(never) fileprivate func _bjs_struct_lift_MathOperations() -> Int32 { + return _bjs_struct_lift_MathOperations_extern() } -extension PointerFields: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> PointerFields { - let mutPtr = UnsafeMutablePointer.bridgeJSStackPop() - let ptr = UnsafePointer.bridgeJSStackPop() - let opaque = OpaquePointer.bridgeJSStackPop() - let mutRaw = UnsafeMutableRawPointer.bridgeJSStackPop() - let raw = UnsafeRawPointer.bridgeJSStackPop() - return PointerFields(raw: raw, mutRaw: mutRaw, opaque: opaque, ptr: ptr, mutPtr: mutPtr) +@_expose(wasm, "bjs_MathOperations_init") +@_cdecl("bjs_MathOperations_init") +public func _bjs_MathOperations_init(_ baseValue: Float64) -> Void { + #if arch(wasm32) + let ret = MathOperations(baseValue: Double.bridgeJSLiftParameter(baseValue)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_MathOperations_add") +@_cdecl("bjs_MathOperations_add") +public func _bjs_MathOperations_add(_ a: Float64, _ b: Float64) -> Float64 { + #if arch(wasm32) + let ret = MathOperations.bridgeJSLiftParameter().add(a: Double.bridgeJSLiftParameter(a), b: Double.bridgeJSLiftParameter(b)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_MathOperations_multiply") +@_cdecl("bjs_MathOperations_multiply") +public func _bjs_MathOperations_multiply(_ a: Float64, _ b: Float64) -> Float64 { + #if arch(wasm32) + let ret = MathOperations.bridgeJSLiftParameter().multiply(a: Double.bridgeJSLiftParameter(a), b: Double.bridgeJSLiftParameter(b)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_MathOperations_static_subtract") +@_cdecl("bjs_MathOperations_static_subtract") +public func _bjs_MathOperations_static_subtract(_ a: Float64, _ b: Float64) -> Float64 { + #if arch(wasm32) + let ret = MathOperations.subtract(a: Double.bridgeJSLiftParameter(a), b: Double.bridgeJSLiftParameter(b)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension CopyableCart: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> CopyableCart { + let note = Optional.bridgeJSStackPop() + let x = Int.bridgeJSStackPop() + return CopyableCart(x: x, note: note) } @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { - self.raw.bridgeJSStackPush() - self.mutRaw.bridgeJSStackPush() - self.opaque.bridgeJSStackPush() - self.ptr.bridgeJSStackPush() - self.mutPtr.bridgeJSStackPush() + self.x.bridgeJSStackPush() + self.note.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { - _bjs_struct_lower_PointerFields(jsObject.bridgeJSLowerParameter()) + _bjs_struct_lower_CopyableCart(jsObject.bridgeJSLowerParameter()) self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self __bjs_self.bridgeJSStackPush() - return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_PointerFields())) + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_CopyableCart())) } } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_PointerFields") -fileprivate func _bjs_struct_lower_PointerFields_extern(_ objectId: Int32) -> Void +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_CopyableCart") +fileprivate func _bjs_struct_lower_CopyableCart_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_PointerFields_extern(_ objectId: Int32) -> Void { +fileprivate func _bjs_struct_lower_CopyableCart_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_struct_lower_PointerFields(_ objectId: Int32) -> Void { - return _bjs_struct_lower_PointerFields_extern(objectId) +@inline(never) fileprivate func _bjs_struct_lower_CopyableCart(_ objectId: Int32) -> Void { + return _bjs_struct_lower_CopyableCart_extern(objectId) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_PointerFields") -fileprivate func _bjs_struct_lift_PointerFields_extern() -> Int32 +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_CopyableCart") +fileprivate func _bjs_struct_lift_CopyableCart_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_PointerFields_extern() -> Int32 { +fileprivate func _bjs_struct_lift_CopyableCart_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_struct_lift_PointerFields() -> Int32 { - return _bjs_struct_lift_PointerFields_extern() +@inline(never) fileprivate func _bjs_struct_lift_CopyableCart() -> Int32 { + return _bjs_struct_lift_CopyableCart_extern() } -@_expose(wasm, "bjs_PointerFields_init") -@_cdecl("bjs_PointerFields_init") -public func _bjs_PointerFields_init(_ raw: UnsafeMutableRawPointer, _ mutRaw: UnsafeMutableRawPointer, _ opaque: UnsafeMutableRawPointer, _ ptr: UnsafeMutableRawPointer, _ mutPtr: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_CopyableCart_static_fromJSObject") +@_cdecl("bjs_CopyableCart_static_fromJSObject") +public func _bjs_CopyableCart_static_fromJSObject(_ object: Int32) -> Void { #if arch(wasm32) - let ret = PointerFields(raw: UnsafeRawPointer.bridgeJSLiftParameter(raw), mutRaw: UnsafeMutableRawPointer.bridgeJSLiftParameter(mutRaw), opaque: OpaquePointer.bridgeJSLiftParameter(opaque), ptr: UnsafePointer.bridgeJSLiftParameter(ptr), mutPtr: UnsafeMutablePointer.bridgeJSLiftParameter(mutPtr)) + let ret = CopyableCart.fromJSObject(_: JSObject.bridgeJSLiftParameter(object)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -extension DataPoint: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> DataPoint { - let optFlag = Optional.bridgeJSStackPop() - let optCount = Optional.bridgeJSStackPop() - let label = String.bridgeJSStackPop() - let y = Double.bridgeJSStackPop() - let x = Double.bridgeJSStackPop() - return DataPoint(x: x, y: y, label: label, optCount: optCount, optFlag: optFlag) +extension CopyableCartItem: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> CopyableCartItem { + let quantity = Int.bridgeJSStackPop() + let sku = String.bridgeJSStackPop() + return CopyableCartItem(sku: sku, quantity: quantity) } @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { - self.x.bridgeJSStackPush() - self.y.bridgeJSStackPush() - self.label.bridgeJSStackPush() - self.optCount.bridgeJSStackPush() - self.optFlag.bridgeJSStackPush() + self.sku.bridgeJSStackPush() + self.quantity.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { - _bjs_struct_lower_DataPoint(jsObject.bridgeJSLowerParameter()) + _bjs_struct_lower_CopyableCartItem(jsObject.bridgeJSLowerParameter()) self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self __bjs_self.bridgeJSStackPush() - return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_DataPoint())) + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_CopyableCartItem())) } } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_DataPoint") -fileprivate func _bjs_struct_lower_DataPoint_extern(_ objectId: Int32) -> Void +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_CopyableCartItem") +fileprivate func _bjs_struct_lower_CopyableCartItem_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_DataPoint_extern(_ objectId: Int32) -> Void { +fileprivate func _bjs_struct_lower_CopyableCartItem_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_struct_lower_DataPoint(_ objectId: Int32) -> Void { - return _bjs_struct_lower_DataPoint_extern(objectId) +@inline(never) fileprivate func _bjs_struct_lower_CopyableCartItem(_ objectId: Int32) -> Void { + return _bjs_struct_lower_CopyableCartItem_extern(objectId) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_DataPoint") -fileprivate func _bjs_struct_lift_DataPoint_extern() -> Int32 +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_CopyableCartItem") +fileprivate func _bjs_struct_lift_CopyableCartItem_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_DataPoint_extern() -> Int32 { +fileprivate func _bjs_struct_lift_CopyableCartItem_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_struct_lift_DataPoint() -> Int32 { - return _bjs_struct_lift_DataPoint_extern() -} - -@_expose(wasm, "bjs_DataPoint_init") -@_cdecl("bjs_DataPoint_init") -public func _bjs_DataPoint_init(_ x: Float64, _ y: Float64, _ labelBytes: Int32, _ labelLength: Int32, _ optCountIsSome: Int32, _ optCountValue: Int32, _ optFlagIsSome: Int32, _ optFlagValue: Int32) -> Void { - #if arch(wasm32) - let ret = DataPoint(x: Double.bridgeJSLiftParameter(x), y: Double.bridgeJSLiftParameter(y), label: String.bridgeJSLiftParameter(labelBytes, labelLength), optCount: Optional.bridgeJSLiftParameter(optCountIsSome, optCountValue), optFlag: Optional.bridgeJSLiftParameter(optFlagIsSome, optFlagValue)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_DataPoint_static_dimensions_get") -@_cdecl("bjs_DataPoint_static_dimensions_get") -public func _bjs_DataPoint_static_dimensions_get() -> Int32 { - #if arch(wasm32) - let ret = DataPoint.dimensions - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_DataPoint_static_origin") -@_cdecl("bjs_DataPoint_static_origin") -public func _bjs_DataPoint_static_origin() -> Void { - #if arch(wasm32) - let ret = DataPoint.origin() - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif +@inline(never) fileprivate func _bjs_struct_lift_CopyableCartItem() -> Int32 { + return _bjs_struct_lift_CopyableCartItem_extern() } -extension PublicPoint: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> PublicPoint { - let y = Int.bridgeJSStackPop() - let x = Int.bridgeJSStackPop() - return PublicPoint(x: x, y: y) +extension CopyableNestedCart: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> CopyableNestedCart { + let shippingAddress = Optional
.bridgeJSStackPop() + let item = CopyableCartItem.bridgeJSStackPop() + let id = Int.bridgeJSStackPop() + return CopyableNestedCart(id: id, item: item, shippingAddress: shippingAddress) } @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { - self.x.bridgeJSStackPush() - self.y.bridgeJSStackPush() + self.id.bridgeJSStackPush() + self.item.bridgeJSStackPush() + self.shippingAddress.bridgeJSStackPush() } - public init(unsafelyCopying jsObject: JSObject) { - _bjs_struct_lower_PublicPoint(jsObject.bridgeJSLowerParameter()) + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_CopyableNestedCart(jsObject.bridgeJSLowerParameter()) self = Self.bridgeJSStackPop() } - public func toJSObject() -> JSObject { + func toJSObject() -> JSObject { let __bjs_self = self __bjs_self.bridgeJSStackPush() - return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_PublicPoint())) + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_CopyableNestedCart())) } } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_PublicPoint") -fileprivate func _bjs_struct_lower_PublicPoint_extern(_ objectId: Int32) -> Void +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_CopyableNestedCart") +fileprivate func _bjs_struct_lower_CopyableNestedCart_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_PublicPoint_extern(_ objectId: Int32) -> Void { +fileprivate func _bjs_struct_lower_CopyableNestedCart_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_struct_lower_PublicPoint(_ objectId: Int32) -> Void { - return _bjs_struct_lower_PublicPoint_extern(objectId) +@inline(never) fileprivate func _bjs_struct_lower_CopyableNestedCart(_ objectId: Int32) -> Void { + return _bjs_struct_lower_CopyableNestedCart_extern(objectId) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_PublicPoint") -fileprivate func _bjs_struct_lift_PublicPoint_extern() -> Int32 +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_CopyableNestedCart") +fileprivate func _bjs_struct_lift_CopyableNestedCart_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_PublicPoint_extern() -> Int32 { +fileprivate func _bjs_struct_lift_CopyableNestedCart_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_struct_lift_PublicPoint() -> Int32 { - return _bjs_struct_lift_PublicPoint_extern() +@inline(never) fileprivate func _bjs_struct_lift_CopyableNestedCart() -> Int32 { + return _bjs_struct_lift_CopyableNestedCart_extern() } -@_expose(wasm, "bjs_PublicPoint_init") -@_cdecl("bjs_PublicPoint_init") -public func _bjs_PublicPoint_init(_ x: Int32, _ y: Int32) -> Void { +@_expose(wasm, "bjs_CopyableNestedCart_static_fromJSObject") +@_cdecl("bjs_CopyableNestedCart_static_fromJSObject") +public func _bjs_CopyableNestedCart_static_fromJSObject(_ object: Int32) -> Void { #if arch(wasm32) - let ret = PublicPoint(x: Int.bridgeJSLiftParameter(x), y: Int.bridgeJSLiftParameter(y)) + let ret = CopyableNestedCart.fromJSObject(_: JSObject.bridgeJSLiftParameter(object)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -extension Address: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Address { - let zipCode = Optional.bridgeJSStackPop() - let city = String.bridgeJSStackPop() - let street = String.bridgeJSStackPop() - return Address(street: street, city: city, zipCode: zipCode) +extension ConfigStruct: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> ConfigStruct { + let value = Int.bridgeJSStackPop() + let name = String.bridgeJSStackPop() + return ConfigStruct(name: name, value: value) } @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { - self.street.bridgeJSStackPush() - self.city.bridgeJSStackPush() - self.zipCode.bridgeJSStackPush() + self.name.bridgeJSStackPush() + self.value.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { - _bjs_struct_lower_Address(jsObject.bridgeJSLowerParameter()) + _bjs_struct_lower_ConfigStruct(jsObject.bridgeJSLowerParameter()) self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self __bjs_self.bridgeJSStackPush() - return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Address())) + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_ConfigStruct())) } } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Address") -fileprivate func _bjs_struct_lower_Address_extern(_ objectId: Int32) -> Void +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_ConfigStruct") +fileprivate func _bjs_struct_lower_ConfigStruct_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_Address_extern(_ objectId: Int32) -> Void { +fileprivate func _bjs_struct_lower_ConfigStruct_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_struct_lower_Address(_ objectId: Int32) -> Void { - return _bjs_struct_lower_Address_extern(objectId) +@inline(never) fileprivate func _bjs_struct_lower_ConfigStruct(_ objectId: Int32) -> Void { + return _bjs_struct_lower_ConfigStruct_extern(objectId) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Address") -fileprivate func _bjs_struct_lift_Address_extern() -> Int32 +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_ConfigStruct") +fileprivate func _bjs_struct_lift_ConfigStruct_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_Address_extern() -> Int32 { +fileprivate func _bjs_struct_lift_ConfigStruct_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_struct_lift_Address() -> Int32 { - return _bjs_struct_lift_Address_extern() +@inline(never) fileprivate func _bjs_struct_lift_ConfigStruct() -> Int32 { + return _bjs_struct_lift_ConfigStruct_extern() } -extension Contact: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Contact { - let secondaryAddress = Optional
.bridgeJSStackPop() - let email = Optional.bridgeJSStackPop() - let address = Address.bridgeJSStackPop() - let age = Int.bridgeJSStackPop() - let name = String.bridgeJSStackPop() - return Contact(name: name, age: age, address: address, email: email, secondaryAddress: secondaryAddress) - } - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { - self.name.bridgeJSStackPush() - self.age.bridgeJSStackPush() - self.address.bridgeJSStackPush() - self.email.bridgeJSStackPush() - self.secondaryAddress.bridgeJSStackPush() - } +@_expose(wasm, "bjs_ConfigStruct_static_defaultConfig_get") +@_cdecl("bjs_ConfigStruct_static_defaultConfig_get") +public func _bjs_ConfigStruct_static_defaultConfig_get() -> Void { + #if arch(wasm32) + let ret = ConfigStruct.defaultConfig + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} - init(unsafelyCopying jsObject: JSObject) { - _bjs_struct_lower_Contact(jsObject.bridgeJSLowerParameter()) - self = Self.bridgeJSStackPop() - } +@_expose(wasm, "bjs_ConfigStruct_static_defaultConfig_set") +@_cdecl("bjs_ConfigStruct_static_defaultConfig_set") +public func _bjs_ConfigStruct_static_defaultConfig_set(_ valueBytes: Int32, _ valueLength: Int32) -> Void { + #if arch(wasm32) + ConfigStruct.defaultConfig = String.bridgeJSLiftParameter(valueBytes, valueLength) + #else + fatalError("Only available on WebAssembly") + #endif +} - func toJSObject() -> JSObject { - let __bjs_self = self - __bjs_self.bridgeJSStackPush() - return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Contact())) - } +@_expose(wasm, "bjs_ConfigStruct_static_maxRetries_get") +@_cdecl("bjs_ConfigStruct_static_maxRetries_get") +public func _bjs_ConfigStruct_static_maxRetries_get() -> Int32 { + #if arch(wasm32) + let ret = ConfigStruct.maxRetries + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif } -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Contact") -fileprivate func _bjs_struct_lower_Contact_extern(_ objectId: Int32) -> Void -#else -fileprivate func _bjs_struct_lower_Contact_extern(_ objectId: Int32) -> Void { +@_expose(wasm, "bjs_ConfigStruct_static_timeout_get") +@_cdecl("bjs_ConfigStruct_static_timeout_get") +public func _bjs_ConfigStruct_static_timeout_get() -> Float64 { + #if arch(wasm32) + let ret = ConfigStruct.timeout + return ret.bridgeJSLowerReturn() + #else fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func _bjs_struct_lower_Contact(_ objectId: Int32) -> Void { - return _bjs_struct_lower_Contact_extern(objectId) + #endif } -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Contact") -fileprivate func _bjs_struct_lift_Contact_extern() -> Int32 -#else -fileprivate func _bjs_struct_lift_Contact_extern() -> Int32 { +@_expose(wasm, "bjs_ConfigStruct_static_timeout_set") +@_cdecl("bjs_ConfigStruct_static_timeout_set") +public func _bjs_ConfigStruct_static_timeout_set(_ value: Float64) -> Void { + #if arch(wasm32) + ConfigStruct.timeout = Double.bridgeJSLiftParameter(value) + #else fatalError("Only available on WebAssembly") + #endif } -#endif -@inline(never) fileprivate func _bjs_struct_lift_Contact() -> Int32 { - return _bjs_struct_lift_Contact_extern() + +@_expose(wasm, "bjs_ConfigStruct_static_computedSetting_get") +@_cdecl("bjs_ConfigStruct_static_computedSetting_get") +public func _bjs_ConfigStruct_static_computedSetting_get() -> Void { + #if arch(wasm32) + let ret = ConfigStruct.computedSetting + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif } -extension Config: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Config { - let status = Status.bridgeJSStackPop() - let direction = Optional.bridgeJSStackPop() - let theme = Optional.bridgeJSStackPop() - let name = String.bridgeJSStackPop() - return Config(name: name, theme: theme, direction: direction, status: status) +extension Vector2D: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Vector2D { + let dy = Double.bridgeJSStackPop() + let dx = Double.bridgeJSStackPop() + return Vector2D(dx: dx, dy: dy) } @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { - self.name.bridgeJSStackPush() - self.theme.bridgeJSStackPush() - self.direction.bridgeJSStackPush() - self.status.bridgeJSStackPush() + self.dx.bridgeJSStackPush() + self.dy.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { - _bjs_struct_lower_Config(jsObject.bridgeJSLowerParameter()) + _bjs_struct_lower_Vector2D(jsObject.bridgeJSLowerParameter()) self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self __bjs_self.bridgeJSStackPush() - return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Config())) + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Vector2D())) } } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Config") -fileprivate func _bjs_struct_lower_Config_extern(_ objectId: Int32) -> Void +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Vector2D") +fileprivate func _bjs_struct_lower_Vector2D_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_Config_extern(_ objectId: Int32) -> Void { +fileprivate func _bjs_struct_lower_Vector2D_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_struct_lower_Config(_ objectId: Int32) -> Void { - return _bjs_struct_lower_Config_extern(objectId) +@inline(never) fileprivate func _bjs_struct_lower_Vector2D(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Vector2D_extern(objectId) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Config") -fileprivate func _bjs_struct_lift_Config_extern() -> Int32 +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Vector2D") +fileprivate func _bjs_struct_lift_Vector2D_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_Config_extern() -> Int32 { +fileprivate func _bjs_struct_lift_Vector2D_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_struct_lift_Config() -> Int32 { - return _bjs_struct_lift_Config_extern() +@inline(never) fileprivate func _bjs_struct_lift_Vector2D() -> Int32 { + return _bjs_struct_lift_Vector2D_extern() } -extension SessionData: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> SessionData { - let owner = Optional.bridgeJSStackPop() - let id = Int.bridgeJSStackPop() - return SessionData(id: id, owner: owner) - } - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { - self.id.bridgeJSStackPush() - self.owner.bridgeJSStackPush() - } - - init(unsafelyCopying jsObject: JSObject) { - _bjs_struct_lower_SessionData(jsObject.bridgeJSLowerParameter()) - self = Self.bridgeJSStackPop() - } - - func toJSObject() -> JSObject { - let __bjs_self = self - __bjs_self.bridgeJSStackPush() - return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_SessionData())) - } +@_expose(wasm, "bjs_Vector2D_init") +@_cdecl("bjs_Vector2D_init") +public func _bjs_Vector2D_init(_ dx: Float64, _ dy: Float64) -> Void { + #if arch(wasm32) + let ret = Vector2D(dx: Double.bridgeJSLiftParameter(dx), dy: Double.bridgeJSLiftParameter(dy)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif } -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_SessionData") -fileprivate func _bjs_struct_lower_SessionData_extern(_ objectId: Int32) -> Void -#else -fileprivate func _bjs_struct_lower_SessionData_extern(_ objectId: Int32) -> Void { +@_expose(wasm, "bjs_Vector2D_magnitude") +@_cdecl("bjs_Vector2D_magnitude") +public func _bjs_Vector2D_magnitude() -> Float64 { + #if arch(wasm32) + let ret = Vector2D.bridgeJSLiftParameter().magnitude() + return ret.bridgeJSLowerReturn() + #else fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func _bjs_struct_lower_SessionData(_ objectId: Int32) -> Void { - return _bjs_struct_lower_SessionData_extern(objectId) + #endif } -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_SessionData") -fileprivate func _bjs_struct_lift_SessionData_extern() -> Int32 -#else -fileprivate func _bjs_struct_lift_SessionData_extern() -> Int32 { +@_expose(wasm, "bjs_Vector2D_scaled") +@_cdecl("bjs_Vector2D_scaled") +public func _bjs_Vector2D_scaled(_ factor: Float64) -> Void { + #if arch(wasm32) + let ret = Vector2D.bridgeJSLiftParameter().scaled(by: Double.bridgeJSLiftParameter(factor)) + return ret.bridgeJSLowerReturn() + #else fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func _bjs_struct_lift_SessionData() -> Int32 { - return _bjs_struct_lift_SessionData_extern() + #endif } -extension ValidationReport: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> ValidationReport { - let outcome = Optional.bridgeJSStackPop() - let status = Optional.bridgeJSStackPop() - let result = APIResult.bridgeJSStackPop() - let id = Int.bridgeJSStackPop() - return ValidationReport(id: id, result: result, status: status, outcome: outcome) +extension JSObjectContainer: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> JSObjectContainer { + let optionalObject = Optional.bridgeJSStackPop() + let object = JSObject.bridgeJSStackPop() + return JSObjectContainer(object: object, optionalObject: optionalObject) } @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { - self.id.bridgeJSStackPush() - self.result.bridgeJSStackPush() - self.status.bridgeJSStackPush() - self.outcome.bridgeJSStackPush() + self.object.bridgeJSStackPush() + self.optionalObject.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { - _bjs_struct_lower_ValidationReport(jsObject.bridgeJSLowerParameter()) + _bjs_struct_lower_JSObjectContainer(jsObject.bridgeJSLowerParameter()) self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self __bjs_self.bridgeJSStackPush() - return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_ValidationReport())) + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_JSObjectContainer())) } } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_ValidationReport") -fileprivate func _bjs_struct_lower_ValidationReport_extern(_ objectId: Int32) -> Void +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_JSObjectContainer") +fileprivate func _bjs_struct_lower_JSObjectContainer_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_ValidationReport_extern(_ objectId: Int32) -> Void { +fileprivate func _bjs_struct_lower_JSObjectContainer_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_struct_lower_ValidationReport(_ objectId: Int32) -> Void { - return _bjs_struct_lower_ValidationReport_extern(objectId) +@inline(never) fileprivate func _bjs_struct_lower_JSObjectContainer(_ objectId: Int32) -> Void { + return _bjs_struct_lower_JSObjectContainer_extern(objectId) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_ValidationReport") -fileprivate func _bjs_struct_lift_ValidationReport_extern() -> Int32 +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_JSObjectContainer") +fileprivate func _bjs_struct_lift_JSObjectContainer_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_ValidationReport_extern() -> Int32 { +fileprivate func _bjs_struct_lift_JSObjectContainer_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_struct_lift_ValidationReport() -> Int32 { - return _bjs_struct_lift_ValidationReport_extern() +@inline(never) fileprivate func _bjs_struct_lift_JSObjectContainer() -> Int32 { + return _bjs_struct_lift_JSObjectContainer_extern() } -extension AdvancedConfig: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> AdvancedConfig { - let overrideDefaults = Optional.bridgeJSStackPop() - let defaults = ConfigStruct.bridgeJSStackPop() - let location = Optional.bridgeJSStackPop() - let metadata = Optional.bridgeJSStackPop() - let result = Optional.bridgeJSStackPop() - let status = Status.bridgeJSStackPop() - let theme = Theme.bridgeJSStackPop() - let enabled = Bool.bridgeJSStackPop() - let title = String.bridgeJSStackPop() - let id = Int.bridgeJSStackPop() - return AdvancedConfig(id: id, title: title, enabled: enabled, theme: theme, status: status, result: result, metadata: metadata, location: location, defaults: defaults, overrideDefaults: overrideDefaults) +extension FooContainer: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> FooContainer { + let optionalFoo = Optional.bridgeJSStackPop().map { Foo(unsafelyWrapping: $0) } + let foo = Foo(unsafelyWrapping: JSObject.bridgeJSStackPop()) + return FooContainer(foo: foo, optionalFoo: optionalFoo) } @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { - self.id.bridgeJSStackPush() - self.title.bridgeJSStackPush() - self.enabled.bridgeJSStackPush() - self.theme.bridgeJSStackPush() - self.status.bridgeJSStackPush() - self.result.bridgeJSStackPush() - self.metadata.bridgeJSStackPush() - self.location.bridgeJSStackPush() - self.defaults.bridgeJSStackPush() - self.overrideDefaults.bridgeJSStackPush() + self.foo.jsObject.bridgeJSStackPush() + self.optionalFoo.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { - _bjs_struct_lower_AdvancedConfig(jsObject.bridgeJSLowerParameter()) + _bjs_struct_lower_FooContainer(jsObject.bridgeJSLowerParameter()) self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self __bjs_self.bridgeJSStackPush() - return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_AdvancedConfig())) + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_FooContainer())) } } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_AdvancedConfig") -fileprivate func _bjs_struct_lower_AdvancedConfig_extern(_ objectId: Int32) -> Void +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_FooContainer") +fileprivate func _bjs_struct_lower_FooContainer_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_AdvancedConfig_extern(_ objectId: Int32) -> Void { +fileprivate func _bjs_struct_lower_FooContainer_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_struct_lower_AdvancedConfig(_ objectId: Int32) -> Void { - return _bjs_struct_lower_AdvancedConfig_extern(objectId) +@inline(never) fileprivate func _bjs_struct_lower_FooContainer(_ objectId: Int32) -> Void { + return _bjs_struct_lower_FooContainer_extern(objectId) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_AdvancedConfig") -fileprivate func _bjs_struct_lift_AdvancedConfig_extern() -> Int32 +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_FooContainer") +fileprivate func _bjs_struct_lift_FooContainer_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_AdvancedConfig_extern() -> Int32 { +fileprivate func _bjs_struct_lift_FooContainer_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_struct_lift_AdvancedConfig() -> Int32 { - return _bjs_struct_lift_AdvancedConfig_extern() +@inline(never) fileprivate func _bjs_struct_lift_FooContainer() -> Int32 { + return _bjs_struct_lift_FooContainer_extern() } -extension MeasurementConfig: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> MeasurementConfig { - let optionalRatio = Optional.bridgeJSStackPop() - let optionalPrecision = Optional.bridgeJSStackPop() - let ratio = Ratio.bridgeJSStackPop() - let precision = Precision.bridgeJSStackPop() - return MeasurementConfig(precision: precision, ratio: ratio, optionalPrecision: optionalPrecision, optionalRatio: optionalRatio) +extension ArrayMembers: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> ArrayMembers { + let optStrings = Optional<[String]>.bridgeJSStackPop() + let ints = [Int].bridgeJSStackPop() + return ArrayMembers(ints: ints, optStrings: optStrings) } @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { - self.precision.bridgeJSStackPush() - self.ratio.bridgeJSStackPush() - self.optionalPrecision.bridgeJSStackPush() - self.optionalRatio.bridgeJSStackPush() + self.ints.bridgeJSStackPush() + self.optStrings.bridgeJSStackPush() } init(unsafelyCopying jsObject: JSObject) { - _bjs_struct_lower_MeasurementConfig(jsObject.bridgeJSLowerParameter()) + _bjs_struct_lower_ArrayMembers(jsObject.bridgeJSLowerParameter()) self = Self.bridgeJSStackPop() } func toJSObject() -> JSObject { let __bjs_self = self __bjs_self.bridgeJSStackPush() - return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_MeasurementConfig())) + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_ArrayMembers())) } } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_MeasurementConfig") -fileprivate func _bjs_struct_lower_MeasurementConfig_extern(_ objectId: Int32) -> Void +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_ArrayMembers") +fileprivate func _bjs_struct_lower_ArrayMembers_extern(_ objectId: Int32) -> Void #else -fileprivate func _bjs_struct_lower_MeasurementConfig_extern(_ objectId: Int32) -> Void { +fileprivate func _bjs_struct_lower_ArrayMembers_extern(_ objectId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_struct_lower_MeasurementConfig(_ objectId: Int32) -> Void { - return _bjs_struct_lower_MeasurementConfig_extern(objectId) +@inline(never) fileprivate func _bjs_struct_lower_ArrayMembers(_ objectId: Int32) -> Void { + return _bjs_struct_lower_ArrayMembers_extern(objectId) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_MeasurementConfig") -fileprivate func _bjs_struct_lift_MeasurementConfig_extern() -> Int32 +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_ArrayMembers") +fileprivate func _bjs_struct_lift_ArrayMembers_extern() -> Int32 #else -fileprivate func _bjs_struct_lift_MeasurementConfig_extern() -> Int32 { +fileprivate func _bjs_struct_lift_ArrayMembers_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_struct_lift_MeasurementConfig() -> Int32 { - return _bjs_struct_lift_MeasurementConfig_extern() +@inline(never) fileprivate func _bjs_struct_lift_ArrayMembers() -> Int32 { + return _bjs_struct_lift_ArrayMembers_extern() } -extension MathOperations: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> MathOperations { - let baseValue = Double.bridgeJSStackPop() - return MathOperations(baseValue: baseValue) - } +@_expose(wasm, "bjs_ArrayMembers_sumValues") +@_cdecl("bjs_ArrayMembers_sumValues") +public func _bjs_ArrayMembers_sumValues() -> Int32 { + #if arch(wasm32) + let ret = ArrayMembers.bridgeJSLiftParameter().sumValues(_: [Int].bridgeJSStackPop()) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} - @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { - self.baseValue.bridgeJSStackPush() - } +@_expose(wasm, "bjs_ArrayMembers_firstString") +@_cdecl("bjs_ArrayMembers_firstString") +public func _bjs_ArrayMembers_firstString() -> Void { + #if arch(wasm32) + let ret = ArrayMembers.bridgeJSLiftParameter().firstString(_: [String].bridgeJSStackPop()) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} - init(unsafelyCopying jsObject: JSObject) { - _bjs_struct_lower_MathOperations(jsObject.bridgeJSLowerParameter()) - self = Self.bridgeJSStackPop() - } +@_expose(wasm, "bjs_makeTag") +@_cdecl("bjs_makeTag") +public func _bjs_makeTag(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = makeTag(_: String.bridgeJSLiftParameter(nameBytes, nameLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} - func toJSObject() -> JSObject { - let __bjs_self = self - __bjs_self.bridgeJSStackPush() - return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_MathOperations())) +@_expose(wasm, "bjs_roundTripPolygon") +@_cdecl("bjs_roundTripPolygon") +public func _bjs_roundTripPolygon(_ polygon: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = roundTripPolygon(_: Polygon.bridgeJSLiftParameter(polygon)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_appendVertex") +@_cdecl("bjs_appendVertex") +public func _bjs_appendVertex(_ polygon: UnsafeMutableRawPointer, _ value: Float64) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = appendVertex(_: Polygon.bridgeJSLiftParameter(polygon), _: Double.bridgeJSLiftParameter(value)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_optionalRoundTripPolygon") +@_cdecl("bjs_optionalRoundTripPolygon") +public func _bjs_optionalRoundTripPolygon(_ polygonIsSome: Int32, _ polygonValue: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = optionalRoundTripPolygon(_: Optional.bridgeJSLiftParameter(polygonIsSome, polygonValue)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_polygonVertexCount") +@_cdecl("bjs_polygonVertexCount") +public func _bjs_polygonVertexCount(_ polygon: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let ret = polygonVertexCount(_: Polygon.bridgeJSLiftParameter(polygon)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripPolygonArray") +@_cdecl("bjs_roundTripPolygonArray") +public func _bjs_roundTripPolygonArray() -> Void { + #if arch(wasm32) + let ret = roundTripPolygonArray(_: [Polygon].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_concatPolygons") +@_cdecl("bjs_concatPolygons") +public func _bjs_concatPolygons() -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = concatPolygons(_: [Polygon].bridgeJSStackPop()) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_validatePolygon") +@_cdecl("bjs_validatePolygon") +public func _bjs_validatePolygon(_ polygon: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + #if arch(wasm32) + do { + let ret = try validatePolygon(_: Polygon.bridgeJSLiftParameter(polygon)) + return ret.bridgeJSLowerReturn() + } catch let error { + if let error = error.thrownValue.object { + withExtendedLifetime(error) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } else { + let jsError = JSError(message: error.description) + withExtendedLifetime(jsError.jsObject) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } + return UnsafeMutableRawPointer(bitPattern: -1).unsafelyUnwrapped } + #else + fatalError("Only available on WebAssembly") + #endif } -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_MathOperations") -fileprivate func _bjs_struct_lower_MathOperations_extern(_ objectId: Int32) -> Void -#else -fileprivate func _bjs_struct_lower_MathOperations_extern(_ objectId: Int32) -> Void { +@_expose(wasm, "bjs_splitPolygon") +@_cdecl("bjs_splitPolygon") +public func _bjs_splitPolygon(_ polygon: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = splitPolygon(_: Polygon.bridgeJSLiftParameter(polygon)) + ret.bridgeJSStackPush() + #else fatalError("Only available on WebAssembly") + #endif } -#endif -@inline(never) fileprivate func _bjs_struct_lower_MathOperations(_ objectId: Int32) -> Void { - return _bjs_struct_lower_MathOperations_extern(objectId) + +@_expose(wasm, "bjs_makePolygonInspector") +@_cdecl("bjs_makePolygonInspector") +public func _bjs_makePolygonInspector() -> Int32 { + #if arch(wasm32) + let ret = makePolygonInspector() + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif } -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_MathOperations") -fileprivate func _bjs_struct_lift_MathOperations_extern() -> Int32 -#else -fileprivate func _bjs_struct_lift_MathOperations_extern() -> Int32 { +@_expose(wasm, "bjs_roundTripOptionalPolygonArray") +@_cdecl("bjs_roundTripOptionalPolygonArray") +public func _bjs_roundTripOptionalPolygonArray() -> Void { + #if arch(wasm32) + let ret = roundTripOptionalPolygonArray(_: [Optional].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_makeTagHolder") +@_cdecl("bjs_makeTagHolder") +public func _bjs_makeTagHolder(_ nameBytes: Int32, _ nameLength: Int32, _ version: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = makeTagHolder(_: String.bridgeJSLiftParameter(nameBytes, nameLength), _: Int.bridgeJSLiftParameter(version)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripCoordinate") +@_cdecl("bjs_roundTripCoordinate") +public func _bjs_roundTripCoordinate() -> Void { + #if arch(wasm32) + let ret = roundTripCoordinate(_: Coordinate.bridgeJSLiftParameter()) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripPriority") +@_cdecl("bjs_roundTripPriority") +public func _bjs_roundTripPriority(_ priority: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = roundTripPriority(_: Priority.bridgeJSLiftParameter(priority)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripAlert") +@_cdecl("bjs_roundTripAlert") +public func _bjs_roundTripAlert(_ alert: Int32) -> Int32 { + #if arch(wasm32) + let ret = roundTripAlert(_: Alert.bridgeJSLiftParameter(alert)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_makeAlert") +@_cdecl("bjs_makeAlert") +public func _bjs_makeAlert(_ level: Int32) -> Int32 { + #if arch(wasm32) + let ret = makeAlert(_: Severity.bridgeJSLiftParameter(level)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripShape") +@_cdecl("bjs_roundTripShape") +public func _bjs_roundTripShape(_ s: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripShape(_: Shape.bridgeJSLiftParameter(s)) + return ret.bridgeJSLowerReturn() + #else fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func _bjs_struct_lift_MathOperations() -> Int32 { - return _bjs_struct_lift_MathOperations_extern() + #endif } -@_expose(wasm, "bjs_MathOperations_init") -@_cdecl("bjs_MathOperations_init") -public func _bjs_MathOperations_init(_ baseValue: Float64) -> Void { +@_expose(wasm, "bjs_makeShapePolygon") +@_cdecl("bjs_makeShapePolygon") +public func _bjs_makeShapePolygon(_ polygon: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = MathOperations(baseValue: Double.bridgeJSLiftParameter(baseValue)) + let ret = makeShapePolygon(_: Polygon.bridgeJSLiftParameter(polygon)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_MathOperations_add") -@_cdecl("bjs_MathOperations_add") -public func _bjs_MathOperations_add(_ a: Float64, _ b: Float64) -> Float64 { +@_expose(wasm, "bjs_makeShapeEmpty") +@_cdecl("bjs_makeShapeEmpty") +public func _bjs_makeShapeEmpty() -> Void { #if arch(wasm32) - let ret = MathOperations.bridgeJSLiftParameter().add(a: Double.bridgeJSLiftParameter(a), b: Double.bridgeJSLiftParameter(b)) + let ret = makeShapeEmpty() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_MathOperations_multiply") -@_cdecl("bjs_MathOperations_multiply") -public func _bjs_MathOperations_multiply(_ a: Float64, _ b: Float64) -> Float64 { +@_expose(wasm, "bjs_roundTripUserId") +@_cdecl("bjs_roundTripUserId") +public func _bjs_roundTripUserId(_ id: Int32) -> Int32 { #if arch(wasm32) - let ret = MathOperations.bridgeJSLiftParameter().multiply(a: Double.bridgeJSLiftParameter(a), b: Double.bridgeJSLiftParameter(b)) + let ret = roundTripUserId(_: UserId.bridgeJSLiftParameter(id)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_MathOperations_static_subtract") -@_cdecl("bjs_MathOperations_static_subtract") -public func _bjs_MathOperations_static_subtract(_ a: Float64, _ b: Float64) -> Float64 { +@_expose(wasm, "bjs_roundTripOptionalUserId") +@_cdecl("bjs_roundTripOptionalUserId") +public func _bjs_roundTripOptionalUserId(_ idIsSome: Int32, _ idValue: Int32) -> Void { #if arch(wasm32) - let ret = MathOperations.subtract(a: Double.bridgeJSLiftParameter(a), b: Double.bridgeJSLiftParameter(b)) + let ret = roundTripOptionalUserId(_: Optional.bridgeJSLiftParameter(idIsSome, idValue)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -extension CopyableCart: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> CopyableCart { - let note = Optional.bridgeJSStackPop() - let x = Int.bridgeJSStackPop() - return CopyableCart(x: x, note: note) - } - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { - self.x.bridgeJSStackPush() - self.note.bridgeJSStackPush() - } - - init(unsafelyCopying jsObject: JSObject) { - _bjs_struct_lower_CopyableCart(jsObject.bridgeJSLowerParameter()) - self = Self.bridgeJSStackPop() - } - - func toJSObject() -> JSObject { - let __bjs_self = self - __bjs_self.bridgeJSStackPush() - return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_CopyableCart())) - } -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_CopyableCart") -fileprivate func _bjs_struct_lower_CopyableCart_extern(_ objectId: Int32) -> Void -#else -fileprivate func _bjs_struct_lower_CopyableCart_extern(_ objectId: Int32) -> Void { +@_expose(wasm, "bjs_roundTripUserIdArray") +@_cdecl("bjs_roundTripUserIdArray") +public func _bjs_roundTripUserIdArray() -> Void { + #if arch(wasm32) + let ret = roundTripUserIdArray(_: [UserId].bridgeJSStackPop()) + ret.bridgeJSStackPush() + #else fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func _bjs_struct_lower_CopyableCart(_ objectId: Int32) -> Void { - return _bjs_struct_lower_CopyableCart_extern(objectId) + #endif } -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_CopyableCart") -fileprivate func _bjs_struct_lift_CopyableCart_extern() -> Int32 -#else -fileprivate func _bjs_struct_lift_CopyableCart_extern() -> Int32 { +@_expose(wasm, "bjs_roundTripBoxed") +@_cdecl("bjs_roundTripBoxed") +public func _bjs_roundTripBoxed(_ boxedKind: Int32, _ boxedPayload1: Int32, _ boxedPayload2: Float64) -> Void { + #if arch(wasm32) + let ret = roundTripBoxed(_: Boxed.bridgeJSLiftParameter(boxedKind, boxedPayload1, boxedPayload2)) + return ret.bridgeJSLowerReturn() + #else fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func _bjs_struct_lift_CopyableCart() -> Int32 { - return _bjs_struct_lift_CopyableCart_extern() + #endif } -@_expose(wasm, "bjs_CopyableCart_static_fromJSObject") -@_cdecl("bjs_CopyableCart_static_fromJSObject") -public func _bjs_CopyableCart_static_fromJSObject(_ object: Int32) -> Void { +@_expose(wasm, "bjs_roundTripOptionalBoxed") +@_cdecl("bjs_roundTripOptionalBoxed") +public func _bjs_roundTripOptionalBoxed(_ boxedIsSome: Int32, _ boxedKind: Int32, _ boxedPayload1: Int32, _ boxedPayload2: Float64) -> Void { #if arch(wasm32) - let ret = CopyableCart.fromJSObject(_: JSObject.bridgeJSLiftParameter(object)) + let ret = roundTripOptionalBoxed(_: Optional.bridgeJSLiftParameter(boxedIsSome, boxedKind, boxedPayload1, boxedPayload2)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -extension CopyableCartItem: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> CopyableCartItem { - let quantity = Int.bridgeJSStackPop() - let sku = String.bridgeJSStackPop() - return CopyableCartItem(sku: sku, quantity: quantity) - } - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { - self.sku.bridgeJSStackPush() - self.quantity.bridgeJSStackPush() - } - - init(unsafelyCopying jsObject: JSObject) { - _bjs_struct_lower_CopyableCartItem(jsObject.bridgeJSLowerParameter()) - self = Self.bridgeJSStackPop() - } - - func toJSObject() -> JSObject { - let __bjs_self = self - __bjs_self.bridgeJSStackPush() - return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_CopyableCartItem())) +@_expose(wasm, "bjs_awaitAsyncCallback") +@_cdecl("bjs_awaitAsyncCallback") +public func _bjs_awaitAsyncCallback(_ fetch: Int32) -> Int32 { + #if arch(wasm32) + return _bjs_makePromise(resolve: Promise_resolve_SS, reject: Promise_reject) { () async throws(JSException) -> String in + return try await awaitAsyncCallback(_: _BJS_Closure_20BridgeJSRuntimeTestsYaKSS_SS.bridgeJSLift(fetch)) } -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_CopyableCartItem") -fileprivate func _bjs_struct_lower_CopyableCartItem_extern(_ objectId: Int32) -> Void -#else -fileprivate func _bjs_struct_lower_CopyableCartItem_extern(_ objectId: Int32) -> Void { + #else fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func _bjs_struct_lower_CopyableCartItem(_ objectId: Int32) -> Void { - return _bjs_struct_lower_CopyableCartItem_extern(objectId) + #endif } -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_CopyableCartItem") -fileprivate func _bjs_struct_lift_CopyableCartItem_extern() -> Int32 -#else -fileprivate func _bjs_struct_lift_CopyableCartItem_extern() -> Int32 { +@_expose(wasm, "bjs_makeAsyncParser") +@_cdecl("bjs_makeAsyncParser") +public func _bjs_makeAsyncParser() -> Int32 { + #if arch(wasm32) + let ret = makeAsyncParser() + return ret.bridgeJSLowerReturn() + #else fatalError("Only available on WebAssembly") + #endif } -#endif -@inline(never) fileprivate func _bjs_struct_lift_CopyableCartItem() -> Int32 { - return _bjs_struct_lift_CopyableCartItem_extern() -} - -extension CopyableNestedCart: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> CopyableNestedCart { - let shippingAddress = Optional
.bridgeJSStackPop() - let item = CopyableCartItem.bridgeJSStackPop() - let id = Int.bridgeJSStackPop() - return CopyableNestedCart(id: id, item: item, shippingAddress: shippingAddress) - } - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { - self.id.bridgeJSStackPush() - self.item.bridgeJSStackPush() - self.shippingAddress.bridgeJSStackPush() - } - init(unsafelyCopying jsObject: JSObject) { - _bjs_struct_lower_CopyableNestedCart(jsObject.bridgeJSLowerParameter()) - self = Self.bridgeJSStackPop() - } - - func toJSObject() -> JSObject { - let __bjs_self = self - __bjs_self.bridgeJSStackPush() - return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_CopyableNestedCart())) - } +@_expose(wasm, "bjs_makeAsyncEcho") +@_cdecl("bjs_makeAsyncEcho") +public func _bjs_makeAsyncEcho() -> Int32 { + #if arch(wasm32) + let ret = makeAsyncEcho() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif } -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_CopyableNestedCart") -fileprivate func _bjs_struct_lower_CopyableNestedCart_extern(_ objectId: Int32) -> Void -#else -fileprivate func _bjs_struct_lower_CopyableNestedCart_extern(_ objectId: Int32) -> Void { +@_expose(wasm, "bjs_makeAsyncRecorder") +@_cdecl("bjs_makeAsyncRecorder") +public func _bjs_makeAsyncRecorder() -> Int32 { + #if arch(wasm32) + let ret = makeAsyncRecorder() + return ret.bridgeJSLowerReturn() + #else fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func _bjs_struct_lower_CopyableNestedCart(_ objectId: Int32) -> Void { - return _bjs_struct_lower_CopyableNestedCart_extern(objectId) + #endif } -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_CopyableNestedCart") -fileprivate func _bjs_struct_lift_CopyableNestedCart_extern() -> Int32 -#else -fileprivate func _bjs_struct_lift_CopyableNestedCart_extern() -> Int32 { +@_expose(wasm, "bjs_lastRecordedValue") +@_cdecl("bjs_lastRecordedValue") +public func _bjs_lastRecordedValue() -> Void { + #if arch(wasm32) + let ret = lastRecordedValue() + return ret.bridgeJSLowerReturn() + #else fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func _bjs_struct_lift_CopyableNestedCart() -> Int32 { - return _bjs_struct_lift_CopyableNestedCart_extern() + #endif } -@_expose(wasm, "bjs_CopyableNestedCart_static_fromJSObject") -@_cdecl("bjs_CopyableNestedCart_static_fromJSObject") -public func _bjs_CopyableNestedCart_static_fromJSObject(_ object: Int32) -> Void { +@_expose(wasm, "bjs_makeAsyncPayloadLoader") +@_cdecl("bjs_makeAsyncPayloadLoader") +public func _bjs_makeAsyncPayloadLoader() -> Int32 { #if arch(wasm32) - let ret = CopyableNestedCart.fromJSObject(_: JSObject.bridgeJSLiftParameter(object)) + let ret = makeAsyncPayloadLoader() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -extension ConfigStruct: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> ConfigStruct { - let value = Int.bridgeJSStackPop() - let name = String.bridgeJSStackPop() - return ConfigStruct(name: name, value: value) - } - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { - self.name.bridgeJSStackPush() - self.value.bridgeJSStackPush() - } - - init(unsafelyCopying jsObject: JSObject) { - _bjs_struct_lower_ConfigStruct(jsObject.bridgeJSLowerParameter()) - self = Self.bridgeJSStackPop() - } - - func toJSObject() -> JSObject { - let __bjs_self = self - __bjs_self.bridgeJSStackPush() - return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_ConfigStruct())) +@_expose(wasm, "bjs_awaitPayloadCallback") +@_cdecl("bjs_awaitPayloadCallback") +public func _bjs_awaitPayloadCallback(_ load: Int32) -> Int32 { + #if arch(wasm32) + return _bjs_makePromise(resolve: Promise_resolve_SS, reject: Promise_reject) { () async throws(JSException) -> String in + return try await awaitPayloadCallback(_: _BJS_Closure_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO.bridgeJSLift(load)) } + #else + fatalError("Only available on WebAssembly") + #endif } -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_ConfigStruct") -fileprivate func _bjs_struct_lower_ConfigStruct_extern(_ objectId: Int32) -> Void -#else -fileprivate func _bjs_struct_lower_ConfigStruct_extern(_ objectId: Int32) -> Void { +@_expose(wasm, "bjs_makeAsyncPointMaker") +@_cdecl("bjs_makeAsyncPointMaker") +public func _bjs_makeAsyncPointMaker() -> Int32 { + #if arch(wasm32) + let ret = makeAsyncPointMaker() + return ret.bridgeJSLowerReturn() + #else fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func _bjs_struct_lower_ConfigStruct(_ objectId: Int32) -> Void { - return _bjs_struct_lower_ConfigStruct_extern(objectId) + #endif } -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_ConfigStruct") -fileprivate func _bjs_struct_lift_ConfigStruct_extern() -> Int32 -#else -fileprivate func _bjs_struct_lift_ConfigStruct_extern() -> Int32 { +@_expose(wasm, "bjs_makeThrowingParser") +@_cdecl("bjs_makeThrowingParser") +public func _bjs_makeThrowingParser() -> Int32 { + #if arch(wasm32) + let ret = makeThrowingParser() + return ret.bridgeJSLowerReturn() + #else fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func _bjs_struct_lift_ConfigStruct() -> Int32 { - return _bjs_struct_lift_ConfigStruct_extern() + #endif } -@_expose(wasm, "bjs_ConfigStruct_static_defaultConfig_get") -@_cdecl("bjs_ConfigStruct_static_defaultConfig_get") -public func _bjs_ConfigStruct_static_defaultConfig_get() -> Void { +@_expose(wasm, "bjs_runValidator") +@_cdecl("bjs_runValidator") +public func _bjs_runValidator(_ validate: Int32) -> Int32 { #if arch(wasm32) - let ret = ConfigStruct.defaultConfig - return ret.bridgeJSLowerReturn() + do { + let ret = try runValidator(_: _BJS_Closure_20BridgeJSRuntimeTestsKSS_Sb.bridgeJSLift(validate)) + return ret.bridgeJSLowerReturn() + } catch let error { + if let error = error.thrownValue.object { + withExtendedLifetime(error) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } else { + let jsError = JSError(message: error.description) + withExtendedLifetime(jsError.jsObject) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } + return 0 + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_ConfigStruct_static_defaultConfig_set") -@_cdecl("bjs_ConfigStruct_static_defaultConfig_set") -public func _bjs_ConfigStruct_static_defaultConfig_set(_ valueBytes: Int32, _ valueLength: Int32) -> Void { +@_expose(wasm, "bjs_roundTripVoid") +@_cdecl("bjs_roundTripVoid") +public func _bjs_roundTripVoid() -> Void { #if arch(wasm32) - ConfigStruct.defaultConfig = String.bridgeJSLiftParameter(valueBytes, valueLength) + roundTripVoid() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_ConfigStruct_static_maxRetries_get") -@_cdecl("bjs_ConfigStruct_static_maxRetries_get") -public func _bjs_ConfigStruct_static_maxRetries_get() -> Int32 { +@_expose(wasm, "bjs_roundTripFloat") +@_cdecl("bjs_roundTripFloat") +public func _bjs_roundTripFloat(_ v: Float32) -> Float32 { #if arch(wasm32) - let ret = ConfigStruct.maxRetries + let ret = roundTripFloat(v: Float.bridgeJSLiftParameter(v)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_ConfigStruct_static_timeout_get") -@_cdecl("bjs_ConfigStruct_static_timeout_get") -public func _bjs_ConfigStruct_static_timeout_get() -> Float64 { +@_expose(wasm, "bjs_roundTripDouble") +@_cdecl("bjs_roundTripDouble") +public func _bjs_roundTripDouble(_ v: Float64) -> Float64 { #if arch(wasm32) - let ret = ConfigStruct.timeout + let ret = roundTripDouble(v: Double.bridgeJSLiftParameter(v)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_ConfigStruct_static_timeout_set") -@_cdecl("bjs_ConfigStruct_static_timeout_set") -public func _bjs_ConfigStruct_static_timeout_set(_ value: Float64) -> Void { +@_expose(wasm, "bjs_roundTripBool") +@_cdecl("bjs_roundTripBool") +public func _bjs_roundTripBool(_ v: Int32) -> Int32 { #if arch(wasm32) - ConfigStruct.timeout = Double.bridgeJSLiftParameter(value) + let ret = roundTripBool(v: Bool.bridgeJSLiftParameter(v)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_ConfigStruct_static_computedSetting_get") -@_cdecl("bjs_ConfigStruct_static_computedSetting_get") -public func _bjs_ConfigStruct_static_computedSetting_get() -> Void { +@_expose(wasm, "bjs_roundTripString") +@_cdecl("bjs_roundTripString") +public func _bjs_roundTripString(_ vBytes: Int32, _ vLength: Int32) -> Void { #if arch(wasm32) - let ret = ConfigStruct.computedSetting + let ret = roundTripString(v: String.bridgeJSLiftParameter(vBytes, vLength)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -extension Vector2D: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Vector2D { - let dy = Double.bridgeJSStackPop() - let dx = Double.bridgeJSStackPop() - return Vector2D(dx: dx, dy: dy) - } - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { - self.dx.bridgeJSStackPush() - self.dy.bridgeJSStackPush() - } - - init(unsafelyCopying jsObject: JSObject) { - _bjs_struct_lower_Vector2D(jsObject.bridgeJSLowerParameter()) - self = Self.bridgeJSStackPop() - } - - func toJSObject() -> JSObject { - let __bjs_self = self - __bjs_self.bridgeJSStackPush() - return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Vector2D())) - } -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Vector2D") -fileprivate func _bjs_struct_lower_Vector2D_extern(_ objectId: Int32) -> Void -#else -fileprivate func _bjs_struct_lower_Vector2D_extern(_ objectId: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func _bjs_struct_lower_Vector2D(_ objectId: Int32) -> Void { - return _bjs_struct_lower_Vector2D_extern(objectId) -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Vector2D") -fileprivate func _bjs_struct_lift_Vector2D_extern() -> Int32 -#else -fileprivate func _bjs_struct_lift_Vector2D_extern() -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func _bjs_struct_lift_Vector2D() -> Int32 { - return _bjs_struct_lift_Vector2D_extern() -} - -@_expose(wasm, "bjs_Vector2D_init") -@_cdecl("bjs_Vector2D_init") -public func _bjs_Vector2D_init(_ dx: Float64, _ dy: Float64) -> Void { +@_expose(wasm, "bjs_roundTripSwiftHeapObject") +@_cdecl("bjs_roundTripSwiftHeapObject") +public func _bjs_roundTripSwiftHeapObject(_ v: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = Vector2D(dx: Double.bridgeJSLiftParameter(dx), dy: Double.bridgeJSLiftParameter(dy)) + let ret = roundTripSwiftHeapObject(v: Greeter.bridgeJSLiftParameter(v)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_Vector2D_magnitude") -@_cdecl("bjs_Vector2D_magnitude") -public func _bjs_Vector2D_magnitude() -> Float64 { +@_expose(wasm, "bjs_roundTripUnsafeRawPointer") +@_cdecl("bjs_roundTripUnsafeRawPointer") +public func _bjs_roundTripUnsafeRawPointer(_ v: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = Vector2D.bridgeJSLiftParameter().magnitude() + let ret = roundTripUnsafeRawPointer(v: UnsafeRawPointer.bridgeJSLiftParameter(v)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_Vector2D_scaled") -@_cdecl("bjs_Vector2D_scaled") -public func _bjs_Vector2D_scaled(_ factor: Float64) -> Void { +@_expose(wasm, "bjs_roundTripUnsafeMutableRawPointer") +@_cdecl("bjs_roundTripUnsafeMutableRawPointer") +public func _bjs_roundTripUnsafeMutableRawPointer(_ v: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = Vector2D.bridgeJSLiftParameter().scaled(by: Double.bridgeJSLiftParameter(factor)) + let ret = roundTripUnsafeMutableRawPointer(v: UnsafeMutableRawPointer.bridgeJSLiftParameter(v)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -extension JSObjectContainer: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> JSObjectContainer { - let optionalObject = Optional.bridgeJSStackPop() - let object = JSObject.bridgeJSStackPop() - return JSObjectContainer(object: object, optionalObject: optionalObject) - } - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { - self.object.bridgeJSStackPush() - self.optionalObject.bridgeJSStackPush() - } - - init(unsafelyCopying jsObject: JSObject) { - _bjs_struct_lower_JSObjectContainer(jsObject.bridgeJSLowerParameter()) - self = Self.bridgeJSStackPop() - } - - func toJSObject() -> JSObject { - let __bjs_self = self - __bjs_self.bridgeJSStackPush() - return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_JSObjectContainer())) - } -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_JSObjectContainer") -fileprivate func _bjs_struct_lower_JSObjectContainer_extern(_ objectId: Int32) -> Void -#else -fileprivate func _bjs_struct_lower_JSObjectContainer_extern(_ objectId: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func _bjs_struct_lower_JSObjectContainer(_ objectId: Int32) -> Void { - return _bjs_struct_lower_JSObjectContainer_extern(objectId) -} - -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_JSObjectContainer") -fileprivate func _bjs_struct_lift_JSObjectContainer_extern() -> Int32 -#else -fileprivate func _bjs_struct_lift_JSObjectContainer_extern() -> Int32 { +@_expose(wasm, "bjs_roundTripOpaquePointer") +@_cdecl("bjs_roundTripOpaquePointer") +public func _bjs_roundTripOpaquePointer(_ v: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = roundTripOpaquePointer(v: OpaquePointer.bridgeJSLiftParameter(v)) + return ret.bridgeJSLowerReturn() + #else fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func _bjs_struct_lift_JSObjectContainer() -> Int32 { - return _bjs_struct_lift_JSObjectContainer_extern() -} - -extension FooContainer: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> FooContainer { - let optionalFoo = Optional.bridgeJSStackPop().map { Foo(unsafelyWrapping: $0) } - let foo = Foo(unsafelyWrapping: JSObject.bridgeJSStackPop()) - return FooContainer(foo: foo, optionalFoo: optionalFoo) - } - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { - self.foo.jsObject.bridgeJSStackPush() - self.optionalFoo.bridgeJSStackPush() - } - - init(unsafelyCopying jsObject: JSObject) { - _bjs_struct_lower_FooContainer(jsObject.bridgeJSLowerParameter()) - self = Self.bridgeJSStackPop() - } - - func toJSObject() -> JSObject { - let __bjs_self = self - __bjs_self.bridgeJSStackPush() - return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_FooContainer())) - } + #endif } -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_FooContainer") -fileprivate func _bjs_struct_lower_FooContainer_extern(_ objectId: Int32) -> Void -#else -fileprivate func _bjs_struct_lower_FooContainer_extern(_ objectId: Int32) -> Void { +@_expose(wasm, "bjs_roundTripUnsafePointer") +@_cdecl("bjs_roundTripUnsafePointer") +public func _bjs_roundTripUnsafePointer(_ v: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = roundTripUnsafePointer(v: UnsafePointer.bridgeJSLiftParameter(v)) + return ret.bridgeJSLowerReturn() + #else fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func _bjs_struct_lower_FooContainer(_ objectId: Int32) -> Void { - return _bjs_struct_lower_FooContainer_extern(objectId) + #endif } -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_FooContainer") -fileprivate func _bjs_struct_lift_FooContainer_extern() -> Int32 -#else -fileprivate func _bjs_struct_lift_FooContainer_extern() -> Int32 { +@_expose(wasm, "bjs_roundTripUnsafeMutablePointer") +@_cdecl("bjs_roundTripUnsafeMutablePointer") +public func _bjs_roundTripUnsafeMutablePointer(_ v: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = roundTripUnsafeMutablePointer(v: UnsafeMutablePointer.bridgeJSLiftParameter(v)) + return ret.bridgeJSLowerReturn() + #else fatalError("Only available on WebAssembly") + #endif } -#endif -@inline(never) fileprivate func _bjs_struct_lift_FooContainer() -> Int32 { - return _bjs_struct_lift_FooContainer_extern() -} - -extension ArrayMembers: _BridgedSwiftStruct { - @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> ArrayMembers { - let optStrings = Optional<[String]>.bridgeJSStackPop() - let ints = [Int].bridgeJSStackPop() - return ArrayMembers(ints: ints, optStrings: optStrings) - } - - @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { - self.ints.bridgeJSStackPush() - self.optStrings.bridgeJSStackPush() - } - - init(unsafelyCopying jsObject: JSObject) { - _bjs_struct_lower_ArrayMembers(jsObject.bridgeJSLowerParameter()) - self = Self.bridgeJSStackPop() - } - func toJSObject() -> JSObject { - let __bjs_self = self - __bjs_self.bridgeJSStackPush() - return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_ArrayMembers())) - } +@_expose(wasm, "bjs_roundTripJSObject") +@_cdecl("bjs_roundTripJSObject") +public func _bjs_roundTripJSObject(_ v: Int32) -> Int32 { + #if arch(wasm32) + let ret = roundTripJSObject(v: JSObject.bridgeJSLiftParameter(v)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif } -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_ArrayMembers") -fileprivate func _bjs_struct_lower_ArrayMembers_extern(_ objectId: Int32) -> Void -#else -fileprivate func _bjs_struct_lower_ArrayMembers_extern(_ objectId: Int32) -> Void { +@_expose(wasm, "bjs_roundTripDictionaryExport") +@_cdecl("bjs_roundTripDictionaryExport") +public func _bjs_roundTripDictionaryExport() -> Void { + #if arch(wasm32) + let ret = roundTripDictionaryExport(v: [String: Int].bridgeJSLiftParameter()) + return ret.bridgeJSLowerReturn() + #else fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func _bjs_struct_lower_ArrayMembers(_ objectId: Int32) -> Void { - return _bjs_struct_lower_ArrayMembers_extern(objectId) + #endif } -#if arch(wasm32) -@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_ArrayMembers") -fileprivate func _bjs_struct_lift_ArrayMembers_extern() -> Int32 -#else -fileprivate func _bjs_struct_lift_ArrayMembers_extern() -> Int32 { +@_expose(wasm, "bjs_roundTripOptionalDictionaryExport") +@_cdecl("bjs_roundTripOptionalDictionaryExport") +public func _bjs_roundTripOptionalDictionaryExport() -> Void { + #if arch(wasm32) + let ret = roundTripOptionalDictionaryExport(v: Optional<[String: String]>.bridgeJSLiftParameter()) + return ret.bridgeJSLowerReturn() + #else fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func _bjs_struct_lift_ArrayMembers() -> Int32 { - return _bjs_struct_lift_ArrayMembers_extern() + #endif } -@_expose(wasm, "bjs_ArrayMembers_sumValues") -@_cdecl("bjs_ArrayMembers_sumValues") -public func _bjs_ArrayMembers_sumValues() -> Int32 { +@_expose(wasm, "bjs_roundTripJSValue") +@_cdecl("bjs_roundTripJSValue") +public func _bjs_roundTripJSValue(_ vKind: Int32, _ vPayload1: Int32, _ vPayload2: Float64) -> Void { #if arch(wasm32) - let ret = ArrayMembers.bridgeJSLiftParameter().sumValues(_: [Int].bridgeJSStackPop()) + let ret = roundTripJSValue(v: JSValue.bridgeJSLiftParameter(vKind, vPayload1, vPayload2)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_ArrayMembers_firstString") -@_cdecl("bjs_ArrayMembers_firstString") -public func _bjs_ArrayMembers_firstString() -> Void { +@_expose(wasm, "bjs_roundTripOptionalJSValue") +@_cdecl("bjs_roundTripOptionalJSValue") +public func _bjs_roundTripOptionalJSValue(_ vIsSome: Int32, _ vKind: Int32, _ vPayload1: Int32, _ vPayload2: Float64) -> Void { #if arch(wasm32) - let ret = ArrayMembers.bridgeJSLiftParameter().firstString(_: [String].bridgeJSStackPop()) + let ret = roundTripOptionalJSValue(v: Optional.bridgeJSLiftParameter(vIsSome, vKind, vPayload1, vPayload2)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeTag") -@_cdecl("bjs_makeTag") -public func _bjs_makeTag(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_roundTripOptionalJSValueArray") +@_cdecl("bjs_roundTripOptionalJSValueArray") +public func _bjs_roundTripOptionalJSValueArray() -> Void { #if arch(wasm32) - let ret = makeTag(_: String.bridgeJSLiftParameter(nameBytes, nameLength)) - return ret.bridgeToJS().bridgeJSLowerReturn() + let ret = roundTripOptionalJSValueArray(v: Optional<[JSValue]>.bridgeJSLiftParameter()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripPolygon") -@_cdecl("bjs_roundTripPolygon") -public func _bjs_roundTripPolygon(_ polygon: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_makeImportedFoo") +@_cdecl("bjs_makeImportedFoo") +public func _bjs_makeImportedFoo(_ valueBytes: Int32, _ valueLength: Int32) -> Int32 { #if arch(wasm32) - let ret = roundTripPolygon(_: Polygon.bridgeFromJS(PolygonReference.bridgeJSLiftParameter(polygon))) - return ret.bridgeToJS().bridgeJSLowerReturn() + do { + let ret = try makeImportedFoo(value: String.bridgeJSLiftParameter(valueBytes, valueLength)) + return ret.bridgeJSLowerReturn() + } catch let error { + if let error = error.thrownValue.object { + withExtendedLifetime(error) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } else { + let jsError = JSError(message: error.description) + withExtendedLifetime(jsError.jsObject) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } + return 0 + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_appendVertex") -@_cdecl("bjs_appendVertex") -public func _bjs_appendVertex(_ polygon: UnsafeMutableRawPointer, _ value: Float64) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_roundTripOptionalImportedClass") +@_cdecl("bjs_roundTripOptionalImportedClass") +public func _bjs_roundTripOptionalImportedClass(_ vIsSome: Int32, _ vValue: Int32) -> Void { #if arch(wasm32) - let ret = appendVertex(_: Polygon.bridgeFromJS(PolygonReference.bridgeJSLiftParameter(polygon)), _: Double.bridgeJSLiftParameter(value)) - return ret.bridgeToJS().bridgeJSLowerReturn() + let ret = roundTripOptionalImportedClass(v: Optional.bridgeJSLiftParameter(vIsSome, vValue)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_optionalRoundTripPolygon") -@_cdecl("bjs_optionalRoundTripPolygon") -public func _bjs_optionalRoundTripPolygon(_ polygonIsSome: Int32, _ polygonValue: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_throwsSwiftError") +@_cdecl("bjs_throwsSwiftError") +public func _bjs_throwsSwiftError(_ shouldThrow: Int32) -> Void { #if arch(wasm32) - let ret = optionalRoundTripPolygon(_: Optional.bridgeJSLiftParameter(polygonIsSome, polygonValue).map { Polygon.bridgeFromJS($0) }) - return ret.map { $0.bridgeToJS() }.bridgeJSLowerReturn() + do { + try throwsSwiftError(shouldThrow: Bool.bridgeJSLiftParameter(shouldThrow)) + } catch let error { + if let error = error.thrownValue.object { + withExtendedLifetime(error) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } else { + let jsError = JSError(message: error.description) + withExtendedLifetime(jsError.jsObject) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } + return + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_polygonVertexCount") -@_cdecl("bjs_polygonVertexCount") -public func _bjs_polygonVertexCount(_ polygon: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_throwsWithIntResult") +@_cdecl("bjs_throwsWithIntResult") +public func _bjs_throwsWithIntResult() -> Int32 { #if arch(wasm32) - let ret = polygonVertexCount(_: Polygon.bridgeFromJS(PolygonReference.bridgeJSLiftParameter(polygon))) - return ret.bridgeJSLowerReturn() + do { + let ret = try throwsWithIntResult() + return ret.bridgeJSLowerReturn() + } catch let error { + if let error = error.thrownValue.object { + withExtendedLifetime(error) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } else { + let jsError = JSError(message: error.description) + withExtendedLifetime(jsError.jsObject) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } + return 0 + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripPolygonArray") -@_cdecl("bjs_roundTripPolygonArray") -public func _bjs_roundTripPolygonArray() -> Void { +@_expose(wasm, "bjs_throwsWithStringResult") +@_cdecl("bjs_throwsWithStringResult") +public func _bjs_throwsWithStringResult() -> Void { #if arch(wasm32) - let ret = roundTripPolygonArray(_: [PolygonReference].bridgeJSStackPop().map { Polygon.bridgeFromJS($0) }) - ret.map { $0.bridgeToJS() }.bridgeJSStackPush() + do { + let ret = try throwsWithStringResult() + return ret.bridgeJSLowerReturn() + } catch let error { + if let error = error.thrownValue.object { + withExtendedLifetime(error) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } else { + let jsError = JSError(message: error.description) + withExtendedLifetime(jsError.jsObject) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } + return + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_concatPolygons") -@_cdecl("bjs_concatPolygons") -public func _bjs_concatPolygons() -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_throwsWithBoolResult") +@_cdecl("bjs_throwsWithBoolResult") +public func _bjs_throwsWithBoolResult() -> Int32 { #if arch(wasm32) - let ret = concatPolygons(_: [PolygonReference].bridgeJSStackPop().map { Polygon.bridgeFromJS($0) }) - return ret.bridgeToJS().bridgeJSLowerReturn() + do { + let ret = try throwsWithBoolResult() + return ret.bridgeJSLowerReturn() + } catch let error { + if let error = error.thrownValue.object { + withExtendedLifetime(error) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } else { + let jsError = JSError(message: error.description) + withExtendedLifetime(jsError.jsObject) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } + return 0 + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_validatePolygon") -@_cdecl("bjs_validatePolygon") -public func _bjs_validatePolygon(_ polygon: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_throwsWithFloatResult") +@_cdecl("bjs_throwsWithFloatResult") +public func _bjs_throwsWithFloatResult() -> Float32 { + #if arch(wasm32) + do { + let ret = try throwsWithFloatResult() + return ret.bridgeJSLowerReturn() + } catch let error { + if let error = error.thrownValue.object { + withExtendedLifetime(error) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } else { + let jsError = JSError(message: error.description) + withExtendedLifetime(jsError.jsObject) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } + return 0.0 + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_throwsWithDoubleResult") +@_cdecl("bjs_throwsWithDoubleResult") +public func _bjs_throwsWithDoubleResult() -> Float64 { + #if arch(wasm32) + do { + let ret = try throwsWithDoubleResult() + return ret.bridgeJSLowerReturn() + } catch let error { + if let error = error.thrownValue.object { + withExtendedLifetime(error) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } else { + let jsError = JSError(message: error.description) + withExtendedLifetime(jsError.jsObject) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } + return 0.0 + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_throwsWithSwiftHeapObjectResult") +@_cdecl("bjs_throwsWithSwiftHeapObjectResult") +public func _bjs_throwsWithSwiftHeapObjectResult() -> UnsafeMutableRawPointer { #if arch(wasm32) do { - let ret = try validatePolygon(_: Polygon.bridgeFromJS(PolygonReference.bridgeJSLiftParameter(polygon))) - return ret.bridgeToJS().bridgeJSLowerReturn() + let ret = try throwsWithSwiftHeapObjectResult() + return ret.bridgeJSLowerReturn() } catch let error { if let error = error.thrownValue.object { withExtendedLifetime(error) { _swift_js_throw(Int32(bitPattern: $0.id)) } } else { - let jsError = JSError(message: String(describing: error)) + let jsError = JSError(message: error.description) withExtendedLifetime(jsError.jsObject) { _swift_js_throw(Int32(bitPattern: $0.id)) } @@ -7095,3771 +8621,3869 @@ public func _bjs_validatePolygon(_ polygon: UnsafeMutableRawPointer) -> UnsafeMu #endif } -@_expose(wasm, "bjs_splitPolygon") -@_cdecl("bjs_splitPolygon") -public func _bjs_splitPolygon(_ polygon: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_throwsWithJSObjectResult") +@_cdecl("bjs_throwsWithJSObjectResult") +public func _bjs_throwsWithJSObjectResult() -> Int32 { + #if arch(wasm32) + do { + let ret = try throwsWithJSObjectResult() + return ret.bridgeJSLowerReturn() + } catch let error { + if let error = error.thrownValue.object { + withExtendedLifetime(error) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } else { + let jsError = JSError(message: error.description) + withExtendedLifetime(jsError.jsObject) { + _swift_js_throw(Int32(bitPattern: $0.id)) + } + } + return 0 + } + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_zeroArgAsyncThrows") +@_cdecl("bjs_zeroArgAsyncThrows") +public func _bjs_zeroArgAsyncThrows() -> Int32 { #if arch(wasm32) - let ret = splitPolygon(_: Polygon.bridgeFromJS(PolygonReference.bridgeJSLiftParameter(polygon))) - ret.map { $0.bridgeToJS() }.bridgeJSStackPush() + let __bjs_capture = 0 + return _bjs_makePromise(resolve: Promise_resolve_SS, reject: Promise_reject) { [__bjs_capture] () async throws(JSException) -> String in + _ = __bjs_capture + return try await zeroArgAsyncThrows() + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_incrementToken") -@_cdecl("bjs_incrementToken") -public func _bjs_incrementToken(_ token: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_asyncRoundTripVoid") +@_cdecl("bjs_asyncRoundTripVoid") +public func _bjs_asyncRoundTripVoid() -> Int32 { #if arch(wasm32) - let ret = incrementToken(_: Token.bridgeFromJS(TokenReference.bridgeJSLiftParameter(token))) - return ret.bridgeToJS().bridgeJSLowerReturn() + return _bjs_makePromise(resolve: Promise_resolve_y, reject: Promise_reject) { + await asyncRoundTripVoid() + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeToken") -@_cdecl("bjs_makeToken") -public func _bjs_makeToken(_ value: Int32) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_asyncRoundTripInt") +@_cdecl("bjs_asyncRoundTripInt") +public func _bjs_asyncRoundTripInt(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = makeToken(_: Int.bridgeJSLiftParameter(value)) - return ret.bridgeToJS().bridgeJSLowerReturn() + return _bjs_makePromise(resolve: Promise_resolve_Si, reject: Promise_reject) { + return await asyncRoundTripInt(v: Int.bridgeJSLiftParameter(v)) + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makePolygonInspector") -@_cdecl("bjs_makePolygonInspector") -public func _bjs_makePolygonInspector() -> Int32 { +@_expose(wasm, "bjs_asyncRoundTripFloat") +@_cdecl("bjs_asyncRoundTripFloat") +public func _bjs_asyncRoundTripFloat(_ v: Float32) -> Int32 { #if arch(wasm32) - let ret = makePolygonInspector() - return JSTypedClosure(ret).bridgeJSLowerReturn() + return _bjs_makePromise(resolve: Promise_resolve_Sf, reject: Promise_reject) { + return await asyncRoundTripFloat(v: Float.bridgeJSLiftParameter(v)) + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_asyncMakePolygon") -@_cdecl("bjs_asyncMakePolygon") -public func _bjs_asyncMakePolygon(_ labelBytes: Int32, _ labelLength: Int32) -> Int32 { +@_expose(wasm, "bjs_asyncRoundTripDouble") +@_cdecl("bjs_asyncRoundTripDouble") +public func _bjs_asyncRoundTripDouble(_ v: Float64) -> Int32 { #if arch(wasm32) - let ret = JSPromise.async { - return await asyncMakePolygon(_: String.bridgeJSLiftParameter(labelBytes, labelLength)).bridgeToJS().jsValue - }.jsObject - return ret.bridgeJSLowerReturn() + return _bjs_makePromise(resolve: Promise_resolve_Sd, reject: Promise_reject) { + return await asyncRoundTripDouble(v: Double.bridgeJSLiftParameter(v)) + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalPolygonArray") -@_cdecl("bjs_roundTripOptionalPolygonArray") -public func _bjs_roundTripOptionalPolygonArray() -> Void { +@_expose(wasm, "bjs_asyncRoundTripBool") +@_cdecl("bjs_asyncRoundTripBool") +public func _bjs_asyncRoundTripBool(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = roundTripOptionalPolygonArray(_: [Optional].bridgeJSStackPop().map { $0.map { Polygon.bridgeFromJS($0) } }) - ret.map { $0.map { $0.bridgeToJS() } }.bridgeJSStackPush() + return _bjs_makePromise(resolve: Promise_resolve_Sb, reject: Promise_reject) { + return await asyncRoundTripBool(v: Bool.bridgeJSLiftParameter(v)) + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeTagHolder") -@_cdecl("bjs_makeTagHolder") -public func _bjs_makeTagHolder(_ nameBytes: Int32, _ nameLength: Int32, _ version: Int32) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_asyncRoundTripString") +@_cdecl("bjs_asyncRoundTripString") +public func _bjs_asyncRoundTripString(_ vBytes: Int32, _ vLength: Int32) -> Int32 { #if arch(wasm32) - let ret = makeTagHolder(_: String.bridgeJSLiftParameter(nameBytes, nameLength), _: Int.bridgeJSLiftParameter(version)) - return ret.bridgeToJS().bridgeJSLowerReturn() + return _bjs_makePromise(resolve: Promise_resolve_SS, reject: Promise_reject) { + return await asyncRoundTripString(v: String.bridgeJSLiftParameter(vBytes, vLength)) + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripCoordinate") -@_cdecl("bjs_roundTripCoordinate") -public func _bjs_roundTripCoordinate() -> Void { +@_expose(wasm, "bjs_asyncRoundTripSwiftHeapObject") +@_cdecl("bjs_asyncRoundTripSwiftHeapObject") +public func _bjs_asyncRoundTripSwiftHeapObject(_ v: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = roundTripCoordinate(_: Coordinate.bridgeFromJS(JSCoordinate.bridgeJSLiftParameter())) - return ret.bridgeToJS().bridgeJSLowerReturn() + return _bjs_makePromise(resolve: Promise_resolve_7GreeterC, reject: Promise_reject) { + return await asyncRoundTripSwiftHeapObject(v: Greeter.bridgeJSLiftParameter(v)) + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripPriority") -@_cdecl("bjs_roundTripPriority") -public func _bjs_roundTripPriority(_ priority: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_asyncRoundTripJSObject") +@_cdecl("bjs_asyncRoundTripJSObject") +public func _bjs_asyncRoundTripJSObject(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = roundTripPriority(_: Priority.bridgeFromJS(PriorityReference.bridgeJSLiftParameter(priority))) - return ret.bridgeToJS().bridgeJSLowerReturn() + return _bjs_makePromise(resolve: Promise_resolve_8JSObjectC, reject: Promise_reject) { + return await asyncRoundTripJSObject(v: JSObject.bridgeJSLiftParameter(v)) + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripAlert") -@_cdecl("bjs_roundTripAlert") -public func _bjs_roundTripAlert(_ alert: Int32) -> Int32 { +@_expose(wasm, "bjs_takeGreeter") +@_cdecl("bjs_takeGreeter") +public func _bjs_takeGreeter(_ g: UnsafeMutableRawPointer, _ nameBytes: Int32, _ nameLength: Int32) -> Void { #if arch(wasm32) - let ret = roundTripAlert(_: Alert.bridgeFromJS(Severity.bridgeJSLiftParameter(alert))) - return ret.bridgeToJS().bridgeJSLowerReturn() + takeGreeter(g: Greeter.bridgeJSLiftParameter(g), name: String.bridgeJSLiftParameter(nameBytes, nameLength)) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeAlert") -@_cdecl("bjs_makeAlert") -public func _bjs_makeAlert(_ level: Int32) -> Int32 { +@_expose(wasm, "bjs_createCalculator") +@_cdecl("bjs_createCalculator") +public func _bjs_createCalculator() -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = makeAlert(_: Severity.bridgeJSLiftParameter(level)) - return ret.bridgeToJS().bridgeJSLowerReturn() + let ret = createCalculator() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripSession") -@_cdecl("bjs_roundTripSession") -public func _bjs_roundTripSession() -> Void { +@_expose(wasm, "bjs_useCalculator") +@_cdecl("bjs_useCalculator") +public func _bjs_useCalculator(_ calc: UnsafeMutableRawPointer, _ x: Int32, _ y: Int32) -> Int32 { #if arch(wasm32) - let ret = roundTripSession(_: Session.bridgeFromJS(SessionState.bridgeJSLiftParameter())) - return ret.bridgeToJS().bridgeJSLowerReturn() + let ret = useCalculator(calc: Calculator.bridgeJSLiftParameter(calc), x: Int.bridgeJSLiftParameter(x), y: Int.bridgeJSLiftParameter(y)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeSession") -@_cdecl("bjs_makeSession") -public func _bjs_makeSession(_ tokenBytes: Int32, _ tokenLength: Int32) -> Void { +@_expose(wasm, "bjs_testGreeterToJSValue") +@_cdecl("bjs_testGreeterToJSValue") +public func _bjs_testGreeterToJSValue() -> Int32 { #if arch(wasm32) - let ret = makeSession(_: String.bridgeJSLiftParameter(tokenBytes, tokenLength)) - return ret.bridgeToJS().bridgeJSLowerReturn() + let ret = testGreeterToJSValue() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripShape") -@_cdecl("bjs_roundTripShape") -public func _bjs_roundTripShape(_ s: Int32) -> Void { +@_expose(wasm, "bjs_testCalculatorToJSValue") +@_cdecl("bjs_testCalculatorToJSValue") +public func _bjs_testCalculatorToJSValue() -> Int32 { #if arch(wasm32) - let ret = roundTripShape(_: Shape.bridgeJSLiftParameter(s)) + let ret = testCalculatorToJSValue() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeShapePolygon") -@_cdecl("bjs_makeShapePolygon") -public func _bjs_makeShapePolygon(_ polygon: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_testSwiftClassAsJSValue") +@_cdecl("bjs_testSwiftClassAsJSValue") +public func _bjs_testSwiftClassAsJSValue(_ greeter: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = makeShapePolygon(_: Polygon.bridgeFromJS(PolygonReference.bridgeJSLiftParameter(polygon))) + let ret = testSwiftClassAsJSValue(greeter: Greeter.bridgeJSLiftParameter(greeter)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeShapeEmpty") -@_cdecl("bjs_makeShapeEmpty") -public func _bjs_makeShapeEmpty() -> Void { +@_expose(wasm, "bjs_setDirection") +@_cdecl("bjs_setDirection") +public func _bjs_setDirection(_ direction: Int32) -> Int32 { #if arch(wasm32) - let ret = makeShapeEmpty() + let ret = setDirection(_: Direction.bridgeJSLiftParameter(direction)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripVoid") -@_cdecl("bjs_roundTripVoid") -public func _bjs_roundTripVoid() -> Void { +@_expose(wasm, "bjs_getDirection") +@_cdecl("bjs_getDirection") +public func _bjs_getDirection() -> Int32 { #if arch(wasm32) - roundTripVoid() + let ret = getDirection() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripFloat") -@_cdecl("bjs_roundTripFloat") -public func _bjs_roundTripFloat(_ v: Float32) -> Float32 { +@_expose(wasm, "bjs_processDirection") +@_cdecl("bjs_processDirection") +public func _bjs_processDirection(_ input: Int32) -> Int32 { #if arch(wasm32) - let ret = roundTripFloat(v: Float.bridgeJSLiftParameter(v)) + let ret = processDirection(_: Direction.bridgeJSLiftParameter(input)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripDouble") -@_cdecl("bjs_roundTripDouble") -public func _bjs_roundTripDouble(_ v: Float64) -> Float64 { +@_expose(wasm, "bjs_setTheme") +@_cdecl("bjs_setTheme") +public func _bjs_setTheme(_ themeBytes: Int32, _ themeLength: Int32) -> Void { #if arch(wasm32) - let ret = roundTripDouble(v: Double.bridgeJSLiftParameter(v)) + let ret = setTheme(_: Theme.bridgeJSLiftParameter(themeBytes, themeLength)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripBool") -@_cdecl("bjs_roundTripBool") -public func _bjs_roundTripBool(_ v: Int32) -> Int32 { +@_expose(wasm, "bjs_getTheme") +@_cdecl("bjs_getTheme") +public func _bjs_getTheme() -> Void { #if arch(wasm32) - let ret = roundTripBool(v: Bool.bridgeJSLiftParameter(v)) + let ret = getTheme() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripString") -@_cdecl("bjs_roundTripString") -public func _bjs_roundTripString(_ vBytes: Int32, _ vLength: Int32) -> Void { +@_expose(wasm, "bjs_asyncRoundTripTheme") +@_cdecl("bjs_asyncRoundTripTheme") +public func _bjs_asyncRoundTripTheme(_ vBytes: Int32, _ vLength: Int32) -> Int32 { #if arch(wasm32) - let ret = roundTripString(v: String.bridgeJSLiftParameter(vBytes, vLength)) - return ret.bridgeJSLowerReturn() + return _bjs_makePromise(resolve: Promise_resolve_5ThemeO, reject: Promise_reject) { + return await asyncRoundTripTheme(_: Theme.bridgeJSLiftParameter(vBytes, vLength)) + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripSwiftHeapObject") -@_cdecl("bjs_roundTripSwiftHeapObject") -public func _bjs_roundTripSwiftHeapObject(_ v: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_asyncRoundTripDirection") +@_cdecl("bjs_asyncRoundTripDirection") +public func _bjs_asyncRoundTripDirection(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = roundTripSwiftHeapObject(v: Greeter.bridgeJSLiftParameter(v)) - return ret.bridgeJSLowerReturn() + return _bjs_makePromise(resolve: Promise_resolve_9DirectionO, reject: Promise_reject) { + return await asyncRoundTripDirection(_: Direction.bridgeJSLiftParameter(v)) + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripUnsafeRawPointer") -@_cdecl("bjs_roundTripUnsafeRawPointer") -public func _bjs_roundTripUnsafeRawPointer(_ v: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_asyncRoundTripOptionalTheme") +@_cdecl("bjs_asyncRoundTripOptionalTheme") +public func _bjs_asyncRoundTripOptionalTheme(_ vIsSome: Int32, _ vBytes: Int32, _ vLength: Int32) -> Int32 { #if arch(wasm32) - let ret = roundTripUnsafeRawPointer(v: UnsafeRawPointer.bridgeJSLiftParameter(v)) - return ret.bridgeJSLowerReturn() + return _bjs_makePromise(resolve: Promise_resolve_Sq5ThemeO, reject: Promise_reject) { + return await asyncRoundTripOptionalTheme(_: Optional.bridgeJSLiftParameter(vIsSome, vBytes, vLength)) + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripUnsafeMutableRawPointer") -@_cdecl("bjs_roundTripUnsafeMutableRawPointer") -public func _bjs_roundTripUnsafeMutableRawPointer(_ v: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_asyncRoundTripOptionalDirection") +@_cdecl("bjs_asyncRoundTripOptionalDirection") +public func _bjs_asyncRoundTripOptionalDirection(_ vIsSome: Int32, _ vValue: Int32) -> Int32 { #if arch(wasm32) - let ret = roundTripUnsafeMutableRawPointer(v: UnsafeMutableRawPointer.bridgeJSLiftParameter(v)) - return ret.bridgeJSLowerReturn() + return _bjs_makePromise(resolve: Promise_resolve_Sq9DirectionO, reject: Promise_reject) { + return await asyncRoundTripOptionalDirection(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOpaquePointer") -@_cdecl("bjs_roundTripOpaquePointer") -public func _bjs_roundTripOpaquePointer(_ v: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_asyncRoundTripDirectionArray") +@_cdecl("bjs_asyncRoundTripDirectionArray") +public func _bjs_asyncRoundTripDirectionArray() -> Int32 { #if arch(wasm32) - let ret = roundTripOpaquePointer(v: OpaquePointer.bridgeJSLiftParameter(v)) - return ret.bridgeJSLowerReturn() + let _tmp_v = [Direction].bridgeJSStackPop() + return _bjs_makePromise(resolve: Promise_resolve_Sa9DirectionO, reject: Promise_reject) { + return await asyncRoundTripDirectionArray(_: _tmp_v) + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripUnsafePointer") -@_cdecl("bjs_roundTripUnsafePointer") -public func _bjs_roundTripUnsafePointer(_ v: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_asyncRoundTripDirectionDict") +@_cdecl("bjs_asyncRoundTripDirectionDict") +public func _bjs_asyncRoundTripDirectionDict() -> Int32 { #if arch(wasm32) - let ret = roundTripUnsafePointer(v: UnsafePointer.bridgeJSLiftParameter(v)) - return ret.bridgeJSLowerReturn() + let _tmp_v = [String: Direction].bridgeJSLiftParameter() + return _bjs_makePromise(resolve: Promise_resolve_SD9DirectionO, reject: Promise_reject) { + return await asyncRoundTripDirectionDict(_: _tmp_v) + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripUnsafeMutablePointer") -@_cdecl("bjs_roundTripUnsafeMutablePointer") -public func _bjs_roundTripUnsafeMutablePointer(_ v: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_asyncRoundTripThemeArray") +@_cdecl("bjs_asyncRoundTripThemeArray") +public func _bjs_asyncRoundTripThemeArray() -> Int32 { #if arch(wasm32) - let ret = roundTripUnsafeMutablePointer(v: UnsafeMutablePointer.bridgeJSLiftParameter(v)) - return ret.bridgeJSLowerReturn() + let _tmp_v = [Theme].bridgeJSStackPop() + return _bjs_makePromise(resolve: Promise_resolve_Sa5ThemeO, reject: Promise_reject) { + return await asyncRoundTripThemeArray(_: _tmp_v) + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripJSObject") -@_cdecl("bjs_roundTripJSObject") -public func _bjs_roundTripJSObject(_ v: Int32) -> Int32 { +@_expose(wasm, "bjs_asyncRoundTripThemeDict") +@_cdecl("bjs_asyncRoundTripThemeDict") +public func _bjs_asyncRoundTripThemeDict() -> Int32 { #if arch(wasm32) - let ret = roundTripJSObject(v: JSObject.bridgeJSLiftParameter(v)) - return ret.bridgeJSLowerReturn() + let _tmp_v = [String: Theme].bridgeJSLiftParameter() + return _bjs_makePromise(resolve: Promise_resolve_SD5ThemeO, reject: Promise_reject) { + return await asyncRoundTripThemeDict(_: _tmp_v) + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripDictionaryExport") -@_cdecl("bjs_roundTripDictionaryExport") -public func _bjs_roundTripDictionaryExport() -> Void { +@_expose(wasm, "bjs_asyncRoundTripFileSize") +@_cdecl("bjs_asyncRoundTripFileSize") +public func _bjs_asyncRoundTripFileSize(_ v: Int64) -> Int32 { #if arch(wasm32) - let ret = roundTripDictionaryExport(v: [String: Int].bridgeJSLiftParameter()) - return ret.bridgeJSLowerReturn() + return _bjs_makePromise(resolve: Promise_resolve_8FileSizeO, reject: Promise_reject) { + return await asyncRoundTripFileSize(_: FileSize.bridgeJSLiftParameter(v)) + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalDictionaryExport") -@_cdecl("bjs_roundTripOptionalDictionaryExport") -public func _bjs_roundTripOptionalDictionaryExport() -> Void { +@_expose(wasm, "bjs_asyncRoundTripOptionalFileSize") +@_cdecl("bjs_asyncRoundTripOptionalFileSize") +public func _bjs_asyncRoundTripOptionalFileSize(_ vIsSome: Int32, _ vValue: Int64) -> Int32 { #if arch(wasm32) - let ret = roundTripOptionalDictionaryExport(v: Optional<[String: String]>.bridgeJSLiftParameter()) - return ret.bridgeJSLowerReturn() + return _bjs_makePromise(resolve: Promise_resolve_Sq8FileSizeO, reject: Promise_reject) { + return await asyncRoundTripOptionalFileSize(_: Optional.bridgeJSLiftParameter(vIsSome, vValue)) + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripJSValue") -@_cdecl("bjs_roundTripJSValue") -public func _bjs_roundTripJSValue(_ vKind: Int32, _ vPayload1: Int32, _ vPayload2: Float64) -> Void { +@_expose(wasm, "bjs_asyncRoundTripAssociatedValueEnum") +@_cdecl("bjs_asyncRoundTripAssociatedValueEnum") +public func _bjs_asyncRoundTripAssociatedValueEnum(_ v: Int32) -> Int32 { #if arch(wasm32) - let ret = roundTripJSValue(v: JSValue.bridgeJSLiftParameter(vKind, vPayload1, vPayload2)) - return ret.bridgeJSLowerReturn() + let _tmp_v = AsyncPayloadResult.bridgeJSLiftParameter(v) + return _bjs_makePromise(resolve: Promise_resolve_18AsyncPayloadResultO, reject: Promise_reject) { + return await asyncRoundTripAssociatedValueEnum(_: _tmp_v) + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalJSValue") -@_cdecl("bjs_roundTripOptionalJSValue") -public func _bjs_roundTripOptionalJSValue(_ vIsSome: Int32, _ vKind: Int32, _ vPayload1: Int32, _ vPayload2: Float64) -> Void { +@_expose(wasm, "bjs_asyncRoundTripOptionalAssociatedValueEnum") +@_cdecl("bjs_asyncRoundTripOptionalAssociatedValueEnum") +public func _bjs_asyncRoundTripOptionalAssociatedValueEnum(_ vIsSome: Int32, _ vCaseId: Int32) -> Int32 { #if arch(wasm32) - let ret = roundTripOptionalJSValue(v: Optional.bridgeJSLiftParameter(vIsSome, vKind, vPayload1, vPayload2)) - return ret.bridgeJSLowerReturn() + let _tmp_v = Optional.bridgeJSLiftParameter(vIsSome, vCaseId) + return _bjs_makePromise(resolve: Promise_resolve_Sq18AsyncPayloadResultO, reject: Promise_reject) { + return await asyncRoundTripOptionalAssociatedValueEnum(_: _tmp_v) + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripOptionalJSValueArray") -@_cdecl("bjs_roundTripOptionalJSValueArray") -public func _bjs_roundTripOptionalJSValueArray() -> Void { +@_expose(wasm, "bjs_setHttpStatus") +@_cdecl("bjs_setHttpStatus") +public func _bjs_setHttpStatus(_ status: Int32) -> Int32 { #if arch(wasm32) - let ret = roundTripOptionalJSValueArray(v: Optional<[JSValue]>.bridgeJSLiftParameter()) - ret.bridgeJSStackPush() + let ret = setHttpStatus(_: HttpStatus.bridgeJSLiftParameter(status)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeImportedFoo") -@_cdecl("bjs_makeImportedFoo") -public func _bjs_makeImportedFoo(_ valueBytes: Int32, _ valueLength: Int32) -> Int32 { +@_expose(wasm, "bjs_getHttpStatus") +@_cdecl("bjs_getHttpStatus") +public func _bjs_getHttpStatus() -> Int32 { #if arch(wasm32) - do { - let ret = try makeImportedFoo(value: String.bridgeJSLiftParameter(valueBytes, valueLength)) - return ret.bridgeJSLowerReturn() - } catch let error { - if let error = error.thrownValue.object { - withExtendedLifetime(error) { - _swift_js_throw(Int32(bitPattern: $0.id)) - } - } else { - let jsError = JSError(message: String(describing: error)) - withExtendedLifetime(jsError.jsObject) { - _swift_js_throw(Int32(bitPattern: $0.id)) - } - } - return 0 - } + let ret = getHttpStatus() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } - -@_expose(wasm, "bjs_throwsSwiftError") -@_cdecl("bjs_throwsSwiftError") -public func _bjs_throwsSwiftError(_ shouldThrow: Int32) -> Void { - #if arch(wasm32) - do { - try throwsSwiftError(shouldThrow: Bool.bridgeJSLiftParameter(shouldThrow)) - } catch let error { - if let error = error.thrownValue.object { - withExtendedLifetime(error) { - _swift_js_throw(Int32(bitPattern: $0.id)) - } - } else { - let jsError = JSError(message: String(describing: error)) - withExtendedLifetime(jsError.jsObject) { - _swift_js_throw(Int32(bitPattern: $0.id)) - } - } - return - } + +@_expose(wasm, "bjs_setFileSize") +@_cdecl("bjs_setFileSize") +public func _bjs_setFileSize(_ size: Int64) -> Int64 { + #if arch(wasm32) + let ret = setFileSize(_: FileSize.bridgeJSLiftParameter(size)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_throwsWithIntResult") -@_cdecl("bjs_throwsWithIntResult") -public func _bjs_throwsWithIntResult() -> Int32 { +@_expose(wasm, "bjs_getFileSize") +@_cdecl("bjs_getFileSize") +public func _bjs_getFileSize() -> Int64 { #if arch(wasm32) - do { - let ret = try throwsWithIntResult() - return ret.bridgeJSLowerReturn() - } catch let error { - if let error = error.thrownValue.object { - withExtendedLifetime(error) { - _swift_js_throw(Int32(bitPattern: $0.id)) - } - } else { - let jsError = JSError(message: String(describing: error)) - withExtendedLifetime(jsError.jsObject) { - _swift_js_throw(Int32(bitPattern: $0.id)) - } - } - return 0 - } + let ret = getFileSize() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_throwsWithStringResult") -@_cdecl("bjs_throwsWithStringResult") -public func _bjs_throwsWithStringResult() -> Void { +@_expose(wasm, "bjs_setSessionId") +@_cdecl("bjs_setSessionId") +public func _bjs_setSessionId(_ session: Int64) -> Int64 { #if arch(wasm32) - do { - let ret = try throwsWithStringResult() - return ret.bridgeJSLowerReturn() - } catch let error { - if let error = error.thrownValue.object { - withExtendedLifetime(error) { - _swift_js_throw(Int32(bitPattern: $0.id)) - } - } else { - let jsError = JSError(message: String(describing: error)) - withExtendedLifetime(jsError.jsObject) { - _swift_js_throw(Int32(bitPattern: $0.id)) - } - } - return - } + let ret = setSessionId(_: SessionId.bridgeJSLiftParameter(session)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_throwsWithBoolResult") -@_cdecl("bjs_throwsWithBoolResult") -public func _bjs_throwsWithBoolResult() -> Int32 { +@_expose(wasm, "bjs_getSessionId") +@_cdecl("bjs_getSessionId") +public func _bjs_getSessionId() -> Int64 { #if arch(wasm32) - do { - let ret = try throwsWithBoolResult() - return ret.bridgeJSLowerReturn() - } catch let error { - if let error = error.thrownValue.object { - withExtendedLifetime(error) { - _swift_js_throw(Int32(bitPattern: $0.id)) - } - } else { - let jsError = JSError(message: String(describing: error)) - withExtendedLifetime(jsError.jsObject) { - _swift_js_throw(Int32(bitPattern: $0.id)) - } - } - return 0 - } + let ret = getSessionId() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_throwsWithFloatResult") -@_cdecl("bjs_throwsWithFloatResult") -public func _bjs_throwsWithFloatResult() -> Float32 { +@_expose(wasm, "bjs_processTheme") +@_cdecl("bjs_processTheme") +public func _bjs_processTheme(_ themeBytes: Int32, _ themeLength: Int32) -> Int32 { #if arch(wasm32) - do { - let ret = try throwsWithFloatResult() - return ret.bridgeJSLowerReturn() - } catch let error { - if let error = error.thrownValue.object { - withExtendedLifetime(error) { - _swift_js_throw(Int32(bitPattern: $0.id)) - } - } else { - let jsError = JSError(message: String(describing: error)) - withExtendedLifetime(jsError.jsObject) { - _swift_js_throw(Int32(bitPattern: $0.id)) - } - } - return 0.0 - } + let ret = processTheme(_: Theme.bridgeJSLiftParameter(themeBytes, themeLength)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_throwsWithDoubleResult") -@_cdecl("bjs_throwsWithDoubleResult") -public func _bjs_throwsWithDoubleResult() -> Float64 { +@_expose(wasm, "bjs_setTSDirection") +@_cdecl("bjs_setTSDirection") +public func _bjs_setTSDirection(_ direction: Int32) -> Int32 { #if arch(wasm32) - do { - let ret = try throwsWithDoubleResult() - return ret.bridgeJSLowerReturn() - } catch let error { - if let error = error.thrownValue.object { - withExtendedLifetime(error) { - _swift_js_throw(Int32(bitPattern: $0.id)) - } - } else { - let jsError = JSError(message: String(describing: error)) - withExtendedLifetime(jsError.jsObject) { - _swift_js_throw(Int32(bitPattern: $0.id)) - } - } - return 0.0 - } + let ret = setTSDirection(_: TSDirection.bridgeJSLiftParameter(direction)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_throwsWithSwiftHeapObjectResult") -@_cdecl("bjs_throwsWithSwiftHeapObjectResult") -public func _bjs_throwsWithSwiftHeapObjectResult() -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_getTSDirection") +@_cdecl("bjs_getTSDirection") +public func _bjs_getTSDirection() -> Int32 { #if arch(wasm32) - do { - let ret = try throwsWithSwiftHeapObjectResult() - return ret.bridgeJSLowerReturn() - } catch let error { - if let error = error.thrownValue.object { - withExtendedLifetime(error) { - _swift_js_throw(Int32(bitPattern: $0.id)) - } - } else { - let jsError = JSError(message: String(describing: error)) - withExtendedLifetime(jsError.jsObject) { - _swift_js_throw(Int32(bitPattern: $0.id)) - } - } - return UnsafeMutableRawPointer(bitPattern: -1).unsafelyUnwrapped - } + let ret = getTSDirection() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_throwsWithJSObjectResult") -@_cdecl("bjs_throwsWithJSObjectResult") -public func _bjs_throwsWithJSObjectResult() -> Int32 { +@_expose(wasm, "bjs_setTSTheme") +@_cdecl("bjs_setTSTheme") +public func _bjs_setTSTheme(_ themeBytes: Int32, _ themeLength: Int32) -> Void { #if arch(wasm32) - do { - let ret = try throwsWithJSObjectResult() - return ret.bridgeJSLowerReturn() - } catch let error { - if let error = error.thrownValue.object { - withExtendedLifetime(error) { - _swift_js_throw(Int32(bitPattern: $0.id)) - } - } else { - let jsError = JSError(message: String(describing: error)) - withExtendedLifetime(jsError.jsObject) { - _swift_js_throw(Int32(bitPattern: $0.id)) - } - } - return 0 - } + let ret = setTSTheme(_: TSTheme.bridgeJSLiftParameter(themeBytes, themeLength)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_asyncRoundTripVoid") -@_cdecl("bjs_asyncRoundTripVoid") -public func _bjs_asyncRoundTripVoid() -> Int32 { +@_expose(wasm, "bjs_getTSTheme") +@_cdecl("bjs_getTSTheme") +public func _bjs_getTSTheme() -> Void { #if arch(wasm32) - let ret = JSPromise.async { - await asyncRoundTripVoid() - }.jsObject + let ret = getTSTheme() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_asyncRoundTripInt") -@_cdecl("bjs_asyncRoundTripInt") -public func _bjs_asyncRoundTripInt(_ v: Int32) -> Int32 { +@_expose(wasm, "bjs_createConverter") +@_cdecl("bjs_createConverter") +public func _bjs_createConverter() -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = JSPromise.async { - return await asyncRoundTripInt(v: Int.bridgeJSLiftParameter(v)).jsValue - }.jsObject + let ret = createConverter() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_asyncRoundTripFloat") -@_cdecl("bjs_asyncRoundTripFloat") -public func _bjs_asyncRoundTripFloat(_ v: Float32) -> Int32 { +@_expose(wasm, "bjs_useConverter") +@_cdecl("bjs_useConverter") +public func _bjs_useConverter(_ converter: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - let ret = JSPromise.async { - return await asyncRoundTripFloat(v: Float.bridgeJSLiftParameter(v)).jsValue - }.jsObject + let ret = useConverter(converter: Utils.Converter.bridgeJSLiftParameter(converter), value: Int.bridgeJSLiftParameter(value)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_asyncRoundTripDouble") -@_cdecl("bjs_asyncRoundTripDouble") -public func _bjs_asyncRoundTripDouble(_ v: Float64) -> Int32 { +@_expose(wasm, "bjs_roundTripConverterArray") +@_cdecl("bjs_roundTripConverterArray") +public func _bjs_roundTripConverterArray() -> Void { #if arch(wasm32) - let ret = JSPromise.async { - return await asyncRoundTripDouble(v: Double.bridgeJSLiftParameter(v)).jsValue - }.jsObject - return ret.bridgeJSLowerReturn() + let ret = roundTripConverterArray(_: [Utils.Converter].bridgeJSStackPop()) + ret.bridgeJSStackPush() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_asyncRoundTripBool") -@_cdecl("bjs_asyncRoundTripBool") -public func _bjs_asyncRoundTripBool(_ v: Int32) -> Int32 { +@_expose(wasm, "bjs_createHTTPServer") +@_cdecl("bjs_createHTTPServer") +public func _bjs_createHTTPServer() -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = JSPromise.async { - return await asyncRoundTripBool(v: Bool.bridgeJSLiftParameter(v)).jsValue - }.jsObject + let ret = createHTTPServer() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_asyncRoundTripString") -@_cdecl("bjs_asyncRoundTripString") -public func _bjs_asyncRoundTripString(_ vBytes: Int32, _ vLength: Int32) -> Int32 { +@_expose(wasm, "bjs_createUUID") +@_cdecl("bjs_createUUID") +public func _bjs_createUUID(_ valueBytes: Int32, _ valueLength: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = JSPromise.async { - return await asyncRoundTripString(v: String.bridgeJSLiftParameter(vBytes, vLength)).jsValue - }.jsObject + let ret = createUUID(value: String.bridgeJSLiftParameter(valueBytes, valueLength)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_asyncRoundTripSwiftHeapObject") -@_cdecl("bjs_asyncRoundTripSwiftHeapObject") -public func _bjs_asyncRoundTripSwiftHeapObject(_ v: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_roundTripUUID") +@_cdecl("bjs_roundTripUUID") +public func _bjs_roundTripUUID(_ uuid: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = JSPromise.async { - return await asyncRoundTripSwiftHeapObject(v: Greeter.bridgeJSLiftParameter(v)).jsValue - }.jsObject + let ret = roundTripUUID(_: UUID.bridgeJSLiftParameter(uuid)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_asyncRoundTripJSObject") -@_cdecl("bjs_asyncRoundTripJSObject") -public func _bjs_asyncRoundTripJSObject(_ v: Int32) -> Int32 { +@_expose(wasm, "bjs_roundtripNetworkingAPIMethod") +@_cdecl("bjs_roundtripNetworkingAPIMethod") +public func _bjs_roundtripNetworkingAPIMethod(_ method: Int32) -> Int32 { #if arch(wasm32) - let ret = JSPromise.async { - return await asyncRoundTripJSObject(v: JSObject.bridgeJSLiftParameter(v)).jsValue - }.jsObject + let ret = roundtripNetworkingAPIMethod(_: Networking.API.Method.bridgeJSLiftParameter(method)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_takeGreeter") -@_cdecl("bjs_takeGreeter") -public func _bjs_takeGreeter(_ g: UnsafeMutableRawPointer, _ nameBytes: Int32, _ nameLength: Int32) -> Void { +@_expose(wasm, "bjs_roundtripConfigurationLogLevel") +@_cdecl("bjs_roundtripConfigurationLogLevel") +public func _bjs_roundtripConfigurationLogLevel(_ levelBytes: Int32, _ levelLength: Int32) -> Void { #if arch(wasm32) - takeGreeter(g: Greeter.bridgeJSLiftParameter(g), name: String.bridgeJSLiftParameter(nameBytes, nameLength)) + let ret = roundtripConfigurationLogLevel(_: Configuration.LogLevel.bridgeJSLiftParameter(levelBytes, levelLength)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_createCalculator") -@_cdecl("bjs_createCalculator") -public func _bjs_createCalculator() -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_roundtripConfigurationPort") +@_cdecl("bjs_roundtripConfigurationPort") +public func _bjs_roundtripConfigurationPort(_ port: Int32) -> Int32 { #if arch(wasm32) - let ret = createCalculator() + let ret = roundtripConfigurationPort(_: Configuration.Port.bridgeJSLiftParameter(port)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_useCalculator") -@_cdecl("bjs_useCalculator") -public func _bjs_useCalculator(_ calc: UnsafeMutableRawPointer, _ x: Int32, _ y: Int32) -> Int32 { +@_expose(wasm, "bjs_processConfigurationLogLevel") +@_cdecl("bjs_processConfigurationLogLevel") +public func _bjs_processConfigurationLogLevel(_ levelBytes: Int32, _ levelLength: Int32) -> Int32 { + #if arch(wasm32) + let ret = processConfigurationLogLevel(_: Configuration.LogLevel.bridgeJSLiftParameter(levelBytes, levelLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundtripInternalSupportedMethod") +@_cdecl("bjs_roundtripInternalSupportedMethod") +public func _bjs_roundtripInternalSupportedMethod(_ method: Int32) -> Int32 { #if arch(wasm32) - let ret = useCalculator(calc: Calculator.bridgeJSLiftParameter(calc), x: Int.bridgeJSLiftParameter(x), y: Int.bridgeJSLiftParameter(y)) + let ret = roundtripInternalSupportedMethod(_: Internal.SupportedMethod.bridgeJSLiftParameter(method)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_testGreeterToJSValue") -@_cdecl("bjs_testGreeterToJSValue") -public func _bjs_testGreeterToJSValue() -> Int32 { +@_expose(wasm, "bjs_roundtripAPIResult") +@_cdecl("bjs_roundtripAPIResult") +public func _bjs_roundtripAPIResult(_ result: Int32) -> Void { #if arch(wasm32) - let ret = testGreeterToJSValue() + let ret = roundtripAPIResult(result: APIResult.bridgeJSLiftParameter(result)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_testCalculatorToJSValue") -@_cdecl("bjs_testCalculatorToJSValue") -public func _bjs_testCalculatorToJSValue() -> Int32 { +@_expose(wasm, "bjs_makeAPIResultSuccess") +@_cdecl("bjs_makeAPIResultSuccess") +public func _bjs_makeAPIResultSuccess(_ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - let ret = testCalculatorToJSValue() + let ret = makeAPIResultSuccess(_: String.bridgeJSLiftParameter(valueBytes, valueLength)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_testSwiftClassAsJSValue") -@_cdecl("bjs_testSwiftClassAsJSValue") -public func _bjs_testSwiftClassAsJSValue(_ greeter: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_makeAPIResultFailure") +@_cdecl("bjs_makeAPIResultFailure") +public func _bjs_makeAPIResultFailure(_ value: Int32) -> Void { #if arch(wasm32) - let ret = testSwiftClassAsJSValue(greeter: Greeter.bridgeJSLiftParameter(greeter)) + let ret = makeAPIResultFailure(_: Int.bridgeJSLiftParameter(value)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_setDirection") -@_cdecl("bjs_setDirection") -public func _bjs_setDirection(_ direction: Int32) -> Int32 { +@_expose(wasm, "bjs_makeAPIResultInfo") +@_cdecl("bjs_makeAPIResultInfo") +public func _bjs_makeAPIResultInfo() -> Void { #if arch(wasm32) - let ret = setDirection(_: Direction.bridgeJSLiftParameter(direction)) + let ret = makeAPIResultInfo() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_getDirection") -@_cdecl("bjs_getDirection") -public func _bjs_getDirection() -> Int32 { +@_expose(wasm, "bjs_makeAPIResultFlag") +@_cdecl("bjs_makeAPIResultFlag") +public func _bjs_makeAPIResultFlag(_ value: Int32) -> Void { #if arch(wasm32) - let ret = getDirection() + let ret = makeAPIResultFlag(_: Bool.bridgeJSLiftParameter(value)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_processDirection") -@_cdecl("bjs_processDirection") -public func _bjs_processDirection(_ input: Int32) -> Int32 { +@_expose(wasm, "bjs_makeAPIResultRate") +@_cdecl("bjs_makeAPIResultRate") +public func _bjs_makeAPIResultRate(_ value: Float32) -> Void { #if arch(wasm32) - let ret = processDirection(_: Direction.bridgeJSLiftParameter(input)) + let ret = makeAPIResultRate(_: Float.bridgeJSLiftParameter(value)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_setTheme") -@_cdecl("bjs_setTheme") -public func _bjs_setTheme(_ themeBytes: Int32, _ themeLength: Int32) -> Void { +@_expose(wasm, "bjs_makeAPIResultPrecise") +@_cdecl("bjs_makeAPIResultPrecise") +public func _bjs_makeAPIResultPrecise(_ value: Float64) -> Void { #if arch(wasm32) - let ret = setTheme(_: Theme.bridgeJSLiftParameter(themeBytes, themeLength)) + let ret = makeAPIResultPrecise(_: Double.bridgeJSLiftParameter(value)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_getTheme") -@_cdecl("bjs_getTheme") -public func _bjs_getTheme() -> Void { +@_expose(wasm, "bjs_roundtripComplexResult") +@_cdecl("bjs_roundtripComplexResult") +public func _bjs_roundtripComplexResult(_ result: Int32) -> Void { #if arch(wasm32) - let ret = getTheme() + let ret = roundtripComplexResult(_: ComplexResult.bridgeJSLiftParameter(result)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_setHttpStatus") -@_cdecl("bjs_setHttpStatus") -public func _bjs_setHttpStatus(_ status: Int32) -> Int32 { +@_expose(wasm, "bjs_makeComplexResultSuccess") +@_cdecl("bjs_makeComplexResultSuccess") +public func _bjs_makeComplexResultSuccess(_ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - let ret = setHttpStatus(_: HttpStatus.bridgeJSLiftParameter(status)) + let ret = makeComplexResultSuccess(_: String.bridgeJSLiftParameter(valueBytes, valueLength)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_getHttpStatus") -@_cdecl("bjs_getHttpStatus") -public func _bjs_getHttpStatus() -> Int32 { +@_expose(wasm, "bjs_makeComplexResultError") +@_cdecl("bjs_makeComplexResultError") +public func _bjs_makeComplexResultError(_ messageBytes: Int32, _ messageLength: Int32, _ code: Int32) -> Void { #if arch(wasm32) - let ret = getHttpStatus() + let ret = makeComplexResultError(_: String.bridgeJSLiftParameter(messageBytes, messageLength), _: Int.bridgeJSLiftParameter(code)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_setFileSize") -@_cdecl("bjs_setFileSize") -public func _bjs_setFileSize(_ size: Int64) -> Int64 { +@_expose(wasm, "bjs_makeComplexResultLocation") +@_cdecl("bjs_makeComplexResultLocation") +public func _bjs_makeComplexResultLocation(_ lat: Float64, _ lng: Float64, _ nameBytes: Int32, _ nameLength: Int32) -> Void { #if arch(wasm32) - let ret = setFileSize(_: FileSize.bridgeJSLiftParameter(size)) + let ret = makeComplexResultLocation(_: Double.bridgeJSLiftParameter(lat), _: Double.bridgeJSLiftParameter(lng), _: String.bridgeJSLiftParameter(nameBytes, nameLength)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_getFileSize") -@_cdecl("bjs_getFileSize") -public func _bjs_getFileSize() -> Int64 { +@_expose(wasm, "bjs_makeComplexResultStatus") +@_cdecl("bjs_makeComplexResultStatus") +public func _bjs_makeComplexResultStatus(_ active: Int32, _ code: Int32, _ messageBytes: Int32, _ messageLength: Int32) -> Void { #if arch(wasm32) - let ret = getFileSize() + let ret = makeComplexResultStatus(_: Bool.bridgeJSLiftParameter(active), _: Int.bridgeJSLiftParameter(code), _: String.bridgeJSLiftParameter(messageBytes, messageLength)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_setSessionId") -@_cdecl("bjs_setSessionId") -public func _bjs_setSessionId(_ session: Int64) -> Int64 { +@_expose(wasm, "bjs_makeComplexResultCoordinates") +@_cdecl("bjs_makeComplexResultCoordinates") +public func _bjs_makeComplexResultCoordinates(_ x: Float64, _ y: Float64, _ z: Float64) -> Void { #if arch(wasm32) - let ret = setSessionId(_: SessionId.bridgeJSLiftParameter(session)) + let ret = makeComplexResultCoordinates(_: Double.bridgeJSLiftParameter(x), _: Double.bridgeJSLiftParameter(y), _: Double.bridgeJSLiftParameter(z)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_getSessionId") -@_cdecl("bjs_getSessionId") -public func _bjs_getSessionId() -> Int64 { +@_expose(wasm, "bjs_makeComplexResultComprehensive") +@_cdecl("bjs_makeComplexResultComprehensive") +public func _bjs_makeComplexResultComprehensive(_ flag1: Int32, _ flag2: Int32, _ count1: Int32, _ count2: Int32, _ value1: Float64, _ value2: Float64, _ text1Bytes: Int32, _ text1Length: Int32, _ text2Bytes: Int32, _ text2Length: Int32, _ text3Bytes: Int32, _ text3Length: Int32) -> Void { #if arch(wasm32) - let ret = getSessionId() + let ret = makeComplexResultComprehensive(_: Bool.bridgeJSLiftParameter(flag1), _: Bool.bridgeJSLiftParameter(flag2), _: Int.bridgeJSLiftParameter(count1), _: Int.bridgeJSLiftParameter(count2), _: Double.bridgeJSLiftParameter(value1), _: Double.bridgeJSLiftParameter(value2), _: String.bridgeJSLiftParameter(text1Bytes, text1Length), _: String.bridgeJSLiftParameter(text2Bytes, text2Length), _: String.bridgeJSLiftParameter(text3Bytes, text3Length)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_processTheme") -@_cdecl("bjs_processTheme") -public func _bjs_processTheme(_ themeBytes: Int32, _ themeLength: Int32) -> Int32 { +@_expose(wasm, "bjs_makeComplexResultInfo") +@_cdecl("bjs_makeComplexResultInfo") +public func _bjs_makeComplexResultInfo() -> Void { #if arch(wasm32) - let ret = processTheme(_: Theme.bridgeJSLiftParameter(themeBytes, themeLength)) + let ret = makeComplexResultInfo() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_setTSDirection") -@_cdecl("bjs_setTSDirection") -public func _bjs_setTSDirection(_ direction: Int32) -> Int32 { +@_expose(wasm, "bjs_makeUtilitiesResultSuccess") +@_cdecl("bjs_makeUtilitiesResultSuccess") +public func _bjs_makeUtilitiesResultSuccess(_ messageBytes: Int32, _ messageLength: Int32) -> Void { #if arch(wasm32) - let ret = setTSDirection(_: TSDirection.bridgeJSLiftParameter(direction)) + let ret = makeUtilitiesResultSuccess(_: String.bridgeJSLiftParameter(messageBytes, messageLength)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_getTSDirection") -@_cdecl("bjs_getTSDirection") -public func _bjs_getTSDirection() -> Int32 { +@_expose(wasm, "bjs_makeUtilitiesResultFailure") +@_cdecl("bjs_makeUtilitiesResultFailure") +public func _bjs_makeUtilitiesResultFailure(_ errorBytes: Int32, _ errorLength: Int32, _ code: Int32) -> Void { #if arch(wasm32) - let ret = getTSDirection() + let ret = makeUtilitiesResultFailure(_: String.bridgeJSLiftParameter(errorBytes, errorLength), _: Int.bridgeJSLiftParameter(code)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_setTSTheme") -@_cdecl("bjs_setTSTheme") -public func _bjs_setTSTheme(_ themeBytes: Int32, _ themeLength: Int32) -> Void { +@_expose(wasm, "bjs_makeUtilitiesResultStatus") +@_cdecl("bjs_makeUtilitiesResultStatus") +public func _bjs_makeUtilitiesResultStatus(_ active: Int32, _ code: Int32, _ messageBytes: Int32, _ messageLength: Int32) -> Void { #if arch(wasm32) - let ret = setTSTheme(_: TSTheme.bridgeJSLiftParameter(themeBytes, themeLength)) + let ret = makeUtilitiesResultStatus(_: Bool.bridgeJSLiftParameter(active), _: Int.bridgeJSLiftParameter(code), _: String.bridgeJSLiftParameter(messageBytes, messageLength)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_getTSTheme") -@_cdecl("bjs_getTSTheme") -public func _bjs_getTSTheme() -> Void { +@_expose(wasm, "bjs_makeAPINetworkingResultSuccess") +@_cdecl("bjs_makeAPINetworkingResultSuccess") +public func _bjs_makeAPINetworkingResultSuccess(_ messageBytes: Int32, _ messageLength: Int32) -> Void { #if arch(wasm32) - let ret = getTSTheme() + let ret = makeAPINetworkingResultSuccess(_: String.bridgeJSLiftParameter(messageBytes, messageLength)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_createConverter") -@_cdecl("bjs_createConverter") -public func _bjs_createConverter() -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_makeAPINetworkingResultFailure") +@_cdecl("bjs_makeAPINetworkingResultFailure") +public func _bjs_makeAPINetworkingResultFailure(_ errorBytes: Int32, _ errorLength: Int32, _ code: Int32) -> Void { #if arch(wasm32) - let ret = createConverter() + let ret = makeAPINetworkingResultFailure(_: String.bridgeJSLiftParameter(errorBytes, errorLength), _: Int.bridgeJSLiftParameter(code)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_useConverter") -@_cdecl("bjs_useConverter") -public func _bjs_useConverter(_ converter: UnsafeMutableRawPointer, _ value: Int32) -> Void { +@_expose(wasm, "bjs_roundtripUtilitiesResult") +@_cdecl("bjs_roundtripUtilitiesResult") +public func _bjs_roundtripUtilitiesResult(_ result: Int32) -> Void { #if arch(wasm32) - let ret = useConverter(converter: Utils.Converter.bridgeJSLiftParameter(converter), value: Int.bridgeJSLiftParameter(value)) + let ret = roundtripUtilitiesResult(_: Utilities.Result.bridgeJSLiftParameter(result)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripConverterArray") -@_cdecl("bjs_roundTripConverterArray") -public func _bjs_roundTripConverterArray() -> Void { +@_expose(wasm, "bjs_roundtripAPINetworkingResult") +@_cdecl("bjs_roundtripAPINetworkingResult") +public func _bjs_roundtripAPINetworkingResult(_ result: Int32) -> Void { #if arch(wasm32) - let ret = roundTripConverterArray(_: [Utils.Converter].bridgeJSStackPop()) - ret.bridgeJSStackPush() + let ret = roundtripAPINetworkingResult(_: API.NetworkingResult.bridgeJSLiftParameter(result)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_createHTTPServer") -@_cdecl("bjs_createHTTPServer") -public func _bjs_createHTTPServer() -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_roundTripAllTypesResult") +@_cdecl("bjs_roundTripAllTypesResult") +public func _bjs_roundTripAllTypesResult(_ result: Int32) -> Void { #if arch(wasm32) - let ret = createHTTPServer() + let ret = roundTripAllTypesResult(_: AllTypesResult.bridgeJSLiftParameter(result)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_createUUID") -@_cdecl("bjs_createUUID") -public func _bjs_createUUID(_ valueBytes: Int32, _ valueLength: Int32) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_roundTripTypedPayloadResult") +@_cdecl("bjs_roundTripTypedPayloadResult") +public func _bjs_roundTripTypedPayloadResult(_ result: Int32) -> Void { #if arch(wasm32) - let ret = createUUID(value: String.bridgeJSLiftParameter(valueBytes, valueLength)) + let ret = roundTripTypedPayloadResult(_: TypedPayloadResult.bridgeJSLiftParameter(result)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripUUID") -@_cdecl("bjs_roundTripUUID") -public func _bjs_roundTripUUID(_ uuid: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_createPropertyHolder") +@_cdecl("bjs_createPropertyHolder") +public func _bjs_createPropertyHolder(_ intValue: Int32, _ floatValue: Float32, _ doubleValue: Float64, _ boolValue: Int32, _ stringValueBytes: Int32, _ stringValueLength: Int32, _ jsObject: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = roundTripUUID(_: UUID.bridgeJSLiftParameter(uuid)) + let ret = createPropertyHolder(intValue: Int.bridgeJSLiftParameter(intValue), floatValue: Float.bridgeJSLiftParameter(floatValue), doubleValue: Double.bridgeJSLiftParameter(doubleValue), boolValue: Bool.bridgeJSLiftParameter(boolValue), stringValue: String.bridgeJSLiftParameter(stringValueBytes, stringValueLength), jsObject: JSObject.bridgeJSLiftParameter(jsObject)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundtripNetworkingAPIMethod") -@_cdecl("bjs_roundtripNetworkingAPIMethod") -public func _bjs_roundtripNetworkingAPIMethod(_ method: Int32) -> Int32 { +@_expose(wasm, "bjs_testPropertyHolder") +@_cdecl("bjs_testPropertyHolder") +public func _bjs_testPropertyHolder(_ holder: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = roundtripNetworkingAPIMethod(_: Networking.API.Method.bridgeJSLiftParameter(method)) + let ret = testPropertyHolder(holder: PropertyHolder.bridgeJSLiftParameter(holder)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundtripConfigurationLogLevel") -@_cdecl("bjs_roundtripConfigurationLogLevel") -public func _bjs_roundtripConfigurationLogLevel(_ levelBytes: Int32, _ levelLength: Int32) -> Void { +@_expose(wasm, "bjs_resetObserverCounts") +@_cdecl("bjs_resetObserverCounts") +public func _bjs_resetObserverCounts() -> Void { #if arch(wasm32) - let ret = roundtripConfigurationLogLevel(_: Configuration.LogLevel.bridgeJSLiftParameter(levelBytes, levelLength)) - return ret.bridgeJSLowerReturn() + resetObserverCounts() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundtripConfigurationPort") -@_cdecl("bjs_roundtripConfigurationPort") -public func _bjs_roundtripConfigurationPort(_ port: Int32) -> Int32 { +@_expose(wasm, "bjs_getObserverStats") +@_cdecl("bjs_getObserverStats") +public func _bjs_getObserverStats() -> Void { #if arch(wasm32) - let ret = roundtripConfigurationPort(_: Configuration.Port.bridgeJSLiftParameter(port)) + let ret = getObserverStats() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_processConfigurationLogLevel") -@_cdecl("bjs_processConfigurationLogLevel") -public func _bjs_processConfigurationLogLevel(_ levelBytes: Int32, _ levelLength: Int32) -> Int32 { +@_expose(wasm, "bjs_formatName") +@_cdecl("bjs_formatName") +public func _bjs_formatName(_ nameBytes: Int32, _ nameLength: Int32, _ transform: Int32) -> Void { #if arch(wasm32) - let ret = processConfigurationLogLevel(_: Configuration.LogLevel.bridgeJSLiftParameter(levelBytes, levelLength)) + let ret = formatName(_: String.bridgeJSLiftParameter(nameBytes, nameLength), transform: _BJS_Closure_20BridgeJSRuntimeTestsSS_SS.bridgeJSLift(transform)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundtripInternalSupportedMethod") -@_cdecl("bjs_roundtripInternalSupportedMethod") -public func _bjs_roundtripInternalSupportedMethod(_ method: Int32) -> Int32 { +@_expose(wasm, "bjs_makeFormatter") +@_cdecl("bjs_makeFormatter") +public func _bjs_makeFormatter(_ prefixBytes: Int32, _ prefixLength: Int32) -> Int32 { #if arch(wasm32) - let ret = roundtripInternalSupportedMethod(_: Internal.SupportedMethod.bridgeJSLiftParameter(method)) - return ret.bridgeJSLowerReturn() + let ret = makeFormatter(prefix: String.bridgeJSLiftParameter(prefixBytes, prefixLength)) + return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundtripAPIResult") -@_cdecl("bjs_roundtripAPIResult") -public func _bjs_roundtripAPIResult(_ result: Int32) -> Void { +@_expose(wasm, "bjs_makeAdder") +@_cdecl("bjs_makeAdder") +public func _bjs_makeAdder(_ base: Int32) -> Int32 { #if arch(wasm32) - let ret = roundtripAPIResult(result: APIResult.bridgeJSLiftParameter(result)) - return ret.bridgeJSLowerReturn() + let ret = makeAdder(base: Int.bridgeJSLiftParameter(base)) + return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeAPIResultSuccess") -@_cdecl("bjs_makeAPIResultSuccess") -public func _bjs_makeAPIResultSuccess(_ valueBytes: Int32, _ valueLength: Int32) -> Void { +@_expose(wasm, "bjs_roundTripPointerFields") +@_cdecl("bjs_roundTripPointerFields") +public func _bjs_roundTripPointerFields() -> Void { #if arch(wasm32) - let ret = makeAPIResultSuccess(_: String.bridgeJSLiftParameter(valueBytes, valueLength)) + let ret = roundTripPointerFields(_: PointerFields.bridgeJSLiftParameter()) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeAPIResultFailure") -@_cdecl("bjs_makeAPIResultFailure") -public func _bjs_makeAPIResultFailure(_ value: Int32) -> Void { +@_expose(wasm, "bjs_testStructDefault") +@_cdecl("bjs_testStructDefault") +public func _bjs_testStructDefault() -> Void { #if arch(wasm32) - let ret = makeAPIResultFailure(_: Int.bridgeJSLiftParameter(value)) + let ret = testStructDefault(point: DataPoint.bridgeJSLiftParameter()) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeAPIResultInfo") -@_cdecl("bjs_makeAPIResultInfo") -public func _bjs_makeAPIResultInfo() -> Void { +@_expose(wasm, "bjs_cartToJSObject") +@_cdecl("bjs_cartToJSObject") +public func _bjs_cartToJSObject() -> Int32 { #if arch(wasm32) - let ret = makeAPIResultInfo() + let ret = cartToJSObject(_: CopyableCart.bridgeJSLiftParameter()) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeAPIResultFlag") -@_cdecl("bjs_makeAPIResultFlag") -public func _bjs_makeAPIResultFlag(_ value: Int32) -> Void { +@_expose(wasm, "bjs_nestedCartToJSObject") +@_cdecl("bjs_nestedCartToJSObject") +public func _bjs_nestedCartToJSObject() -> Int32 { #if arch(wasm32) - let ret = makeAPIResultFlag(_: Bool.bridgeJSLiftParameter(value)) + let ret = nestedCartToJSObject(_: CopyableNestedCart.bridgeJSLiftParameter()) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeAPIResultRate") -@_cdecl("bjs_makeAPIResultRate") -public func _bjs_makeAPIResultRate(_ value: Float32) -> Void { +@_expose(wasm, "bjs_roundTripDataPoint") +@_cdecl("bjs_roundTripDataPoint") +public func _bjs_roundTripDataPoint() -> Void { #if arch(wasm32) - let ret = makeAPIResultRate(_: Float.bridgeJSLiftParameter(value)) + let ret = roundTripDataPoint(_: DataPoint.bridgeJSLiftParameter()) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeAPIResultPrecise") -@_cdecl("bjs_makeAPIResultPrecise") -public func _bjs_makeAPIResultPrecise(_ value: Float64) -> Void { +@_expose(wasm, "bjs_roundTripPublicPoint") +@_cdecl("bjs_roundTripPublicPoint") +public func _bjs_roundTripPublicPoint() -> Void { #if arch(wasm32) - let ret = makeAPIResultPrecise(_: Double.bridgeJSLiftParameter(value)) + let ret = roundTripPublicPoint(_: PublicPoint.bridgeJSLiftParameter()) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundtripComplexResult") -@_cdecl("bjs_roundtripComplexResult") -public func _bjs_roundtripComplexResult(_ result: Int32) -> Void { +@_expose(wasm, "bjs_asyncRoundTripPublicPoint") +@_cdecl("bjs_asyncRoundTripPublicPoint") +public func _bjs_asyncRoundTripPublicPoint() -> Int32 { #if arch(wasm32) - let ret = roundtripComplexResult(_: ComplexResult.bridgeJSLiftParameter(result)) - return ret.bridgeJSLowerReturn() + let _tmp_point = PublicPoint.bridgeJSLiftParameter() + return _bjs_makePromise(resolve: Promise_resolve_11PublicPointV, reject: Promise_reject) { + return await asyncRoundTripPublicPoint(_: _tmp_point) + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeComplexResultSuccess") -@_cdecl("bjs_makeComplexResultSuccess") -public func _bjs_makeComplexResultSuccess(_ valueBytes: Int32, _ valueLength: Int32) -> Void { +@_expose(wasm, "bjs_asyncRoundTripPublicPointThrows") +@_cdecl("bjs_asyncRoundTripPublicPointThrows") +public func _bjs_asyncRoundTripPublicPointThrows() -> Int32 { #if arch(wasm32) - let ret = makeComplexResultSuccess(_: String.bridgeJSLiftParameter(valueBytes, valueLength)) - return ret.bridgeJSLowerReturn() + let _tmp_point = PublicPoint.bridgeJSLiftParameter() + return _bjs_makePromise(resolve: Promise_resolve_11PublicPointV, reject: Promise_reject) { () async throws(JSException) -> PublicPoint in + return try await asyncRoundTripPublicPointThrows(_: _tmp_point) + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeComplexResultError") -@_cdecl("bjs_makeComplexResultError") -public func _bjs_makeComplexResultError(_ messageBytes: Int32, _ messageLength: Int32, _ code: Int32) -> Void { +@_expose(wasm, "bjs_asyncStructOrThrow") +@_cdecl("bjs_asyncStructOrThrow") +public func _bjs_asyncStructOrThrow(_ shouldThrow: Int32) -> Int32 { #if arch(wasm32) - let ret = makeComplexResultError(_: String.bridgeJSLiftParameter(messageBytes, messageLength), _: Int.bridgeJSLiftParameter(code)) - return ret.bridgeJSLowerReturn() + return _bjs_makePromise(resolve: Promise_resolve_11PublicPointV, reject: Promise_reject) { () async throws(JSException) -> PublicPoint in + return try await asyncStructOrThrow(_: Bool.bridgeJSLiftParameter(shouldThrow)) + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeComplexResultLocation") -@_cdecl("bjs_makeComplexResultLocation") -public func _bjs_makeComplexResultLocation(_ lat: Float64, _ lng: Float64, _ nameBytes: Int32, _ nameLength: Int32) -> Void { +@_expose(wasm, "bjs_asyncCombinePublicPoints") +@_cdecl("bjs_asyncCombinePublicPoints") +public func _bjs_asyncCombinePublicPoints() -> Int32 { #if arch(wasm32) - let ret = makeComplexResultLocation(_: Double.bridgeJSLiftParameter(lat), _: Double.bridgeJSLiftParameter(lng), _: String.bridgeJSLiftParameter(nameBytes, nameLength)) - return ret.bridgeJSLowerReturn() + let _tmp_b = PublicPoint.bridgeJSLiftParameter() + let _tmp_a = PublicPoint.bridgeJSLiftParameter() + return _bjs_makePromise(resolve: Promise_resolve_11PublicPointV, reject: Promise_reject) { + return await asyncCombinePublicPoints(_: _tmp_a, _: _tmp_b) + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeComplexResultStatus") -@_cdecl("bjs_makeComplexResultStatus") -public func _bjs_makeComplexResultStatus(_ active: Int32, _ code: Int32, _ messageBytes: Int32, _ messageLength: Int32) -> Void { +@_expose(wasm, "bjs_asyncRoundTripContact") +@_cdecl("bjs_asyncRoundTripContact") +public func _bjs_asyncRoundTripContact() -> Int32 { #if arch(wasm32) - let ret = makeComplexResultStatus(_: Bool.bridgeJSLiftParameter(active), _: Int.bridgeJSLiftParameter(code), _: String.bridgeJSLiftParameter(messageBytes, messageLength)) - return ret.bridgeJSLowerReturn() + let _tmp_contact = Contact.bridgeJSLiftParameter() + return _bjs_makePromise(resolve: Promise_resolve_7ContactV, reject: Promise_reject) { + return await asyncRoundTripContact(_: _tmp_contact) + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeComplexResultCoordinates") -@_cdecl("bjs_makeComplexResultCoordinates") -public func _bjs_makeComplexResultCoordinates(_ x: Float64, _ y: Float64, _ z: Float64) -> Void { +@_expose(wasm, "bjs_asyncRoundTripPublicPointArray") +@_cdecl("bjs_asyncRoundTripPublicPointArray") +public func _bjs_asyncRoundTripPublicPointArray() -> Int32 { #if arch(wasm32) - let ret = makeComplexResultCoordinates(_: Double.bridgeJSLiftParameter(x), _: Double.bridgeJSLiftParameter(y), _: Double.bridgeJSLiftParameter(z)) - return ret.bridgeJSLowerReturn() + let _tmp_points = [PublicPoint].bridgeJSStackPop() + return _bjs_makePromise(resolve: Promise_resolve_Sa11PublicPointV, reject: Promise_reject) { + return await asyncRoundTripPublicPointArray(_: _tmp_points) + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeComplexResultComprehensive") -@_cdecl("bjs_makeComplexResultComprehensive") -public func _bjs_makeComplexResultComprehensive(_ flag1: Int32, _ flag2: Int32, _ count1: Int32, _ count2: Int32, _ value1: Float64, _ value2: Float64, _ text1Bytes: Int32, _ text1Length: Int32, _ text2Bytes: Int32, _ text2Length: Int32, _ text3Bytes: Int32, _ text3Length: Int32) -> Void { +@_expose(wasm, "bjs_asyncRoundTripOptionalPublicPoint") +@_cdecl("bjs_asyncRoundTripOptionalPublicPoint") +public func _bjs_asyncRoundTripOptionalPublicPoint() -> Int32 { #if arch(wasm32) - let ret = makeComplexResultComprehensive(_: Bool.bridgeJSLiftParameter(flag1), _: Bool.bridgeJSLiftParameter(flag2), _: Int.bridgeJSLiftParameter(count1), _: Int.bridgeJSLiftParameter(count2), _: Double.bridgeJSLiftParameter(value1), _: Double.bridgeJSLiftParameter(value2), _: String.bridgeJSLiftParameter(text1Bytes, text1Length), _: String.bridgeJSLiftParameter(text2Bytes, text2Length), _: String.bridgeJSLiftParameter(text3Bytes, text3Length)) - return ret.bridgeJSLowerReturn() + let _tmp_point = Optional.bridgeJSLiftParameter() + return _bjs_makePromise(resolve: Promise_resolve_Sq11PublicPointV, reject: Promise_reject) { + return await asyncRoundTripOptionalPublicPoint(_: _tmp_point) + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeComplexResultInfo") -@_cdecl("bjs_makeComplexResultInfo") -public func _bjs_makeComplexResultInfo() -> Void { +@_expose(wasm, "bjs_asyncRoundTripPublicPointDict") +@_cdecl("bjs_asyncRoundTripPublicPointDict") +public func _bjs_asyncRoundTripPublicPointDict() -> Int32 { #if arch(wasm32) - let ret = makeComplexResultInfo() - return ret.bridgeJSLowerReturn() + let _tmp_points = [String: PublicPoint].bridgeJSLiftParameter() + return _bjs_makePromise(resolve: Promise_resolve_SD11PublicPointV, reject: Promise_reject) { + return await asyncRoundTripPublicPointDict(_: _tmp_points) + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeUtilitiesResultSuccess") -@_cdecl("bjs_makeUtilitiesResultSuccess") -public func _bjs_makeUtilitiesResultSuccess(_ messageBytes: Int32, _ messageLength: Int32) -> Void { +@_expose(wasm, "bjs_roundTripContact") +@_cdecl("bjs_roundTripContact") +public func _bjs_roundTripContact() -> Void { #if arch(wasm32) - let ret = makeUtilitiesResultSuccess(_: String.bridgeJSLiftParameter(messageBytes, messageLength)) + let ret = roundTripContact(_: Contact.bridgeJSLiftParameter()) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeUtilitiesResultFailure") -@_cdecl("bjs_makeUtilitiesResultFailure") -public func _bjs_makeUtilitiesResultFailure(_ errorBytes: Int32, _ errorLength: Int32, _ code: Int32) -> Void { +@_expose(wasm, "bjs_roundTripConfig") +@_cdecl("bjs_roundTripConfig") +public func _bjs_roundTripConfig() -> Void { #if arch(wasm32) - let ret = makeUtilitiesResultFailure(_: String.bridgeJSLiftParameter(errorBytes, errorLength), _: Int.bridgeJSLiftParameter(code)) + let ret = roundTripConfig(_: Config.bridgeJSLiftParameter()) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeUtilitiesResultStatus") -@_cdecl("bjs_makeUtilitiesResultStatus") -public func _bjs_makeUtilitiesResultStatus(_ active: Int32, _ code: Int32, _ messageBytes: Int32, _ messageLength: Int32) -> Void { +@_expose(wasm, "bjs_roundTripSessionData") +@_cdecl("bjs_roundTripSessionData") +public func _bjs_roundTripSessionData() -> Void { #if arch(wasm32) - let ret = makeUtilitiesResultStatus(_: Bool.bridgeJSLiftParameter(active), _: Int.bridgeJSLiftParameter(code), _: String.bridgeJSLiftParameter(messageBytes, messageLength)) + let ret = roundTripSessionData(_: SessionData.bridgeJSLiftParameter()) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeAPINetworkingResultSuccess") -@_cdecl("bjs_makeAPINetworkingResultSuccess") -public func _bjs_makeAPINetworkingResultSuccess(_ messageBytes: Int32, _ messageLength: Int32) -> Void { +@_expose(wasm, "bjs_roundTripValidationReport") +@_cdecl("bjs_roundTripValidationReport") +public func _bjs_roundTripValidationReport() -> Void { #if arch(wasm32) - let ret = makeAPINetworkingResultSuccess(_: String.bridgeJSLiftParameter(messageBytes, messageLength)) + let ret = roundTripValidationReport(_: ValidationReport.bridgeJSLiftParameter()) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeAPINetworkingResultFailure") -@_cdecl("bjs_makeAPINetworkingResultFailure") -public func _bjs_makeAPINetworkingResultFailure(_ errorBytes: Int32, _ errorLength: Int32, _ code: Int32) -> Void { +@_expose(wasm, "bjs_roundTripAdvancedConfig") +@_cdecl("bjs_roundTripAdvancedConfig") +public func _bjs_roundTripAdvancedConfig() -> Void { #if arch(wasm32) - let ret = makeAPINetworkingResultFailure(_: String.bridgeJSLiftParameter(errorBytes, errorLength), _: Int.bridgeJSLiftParameter(code)) + let ret = roundTripAdvancedConfig(_: AdvancedConfig.bridgeJSLiftParameter()) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundtripUtilitiesResult") -@_cdecl("bjs_roundtripUtilitiesResult") -public func _bjs_roundtripUtilitiesResult(_ result: Int32) -> Void { +@_expose(wasm, "bjs_roundTripMeasurementConfig") +@_cdecl("bjs_roundTripMeasurementConfig") +public func _bjs_roundTripMeasurementConfig() -> Void { #if arch(wasm32) - let ret = roundtripUtilitiesResult(_: Utilities.Result.bridgeJSLiftParameter(result)) + let ret = roundTripMeasurementConfig(_: MeasurementConfig.bridgeJSLiftParameter()) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundtripAPINetworkingResult") -@_cdecl("bjs_roundtripAPINetworkingResult") -public func _bjs_roundtripAPINetworkingResult(_ result: Int32) -> Void { +@_expose(wasm, "bjs_updateValidationReport") +@_cdecl("bjs_updateValidationReport") +public func _bjs_updateValidationReport(_ newResultIsSome: Int32, _ newResultCaseId: Int32) -> Void { #if arch(wasm32) - let ret = roundtripAPINetworkingResult(_: API.NetworkingResult.bridgeJSLiftParameter(result)) + let _tmp_report = ValidationReport.bridgeJSLiftParameter() + let _tmp_newResult = Optional.bridgeJSLiftParameter(newResultIsSome, newResultCaseId) + let ret = updateValidationReport(_: _tmp_newResult, _: _tmp_report) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripAllTypesResult") -@_cdecl("bjs_roundTripAllTypesResult") -public func _bjs_roundTripAllTypesResult(_ result: Int32) -> Void { +@_expose(wasm, "bjs_testContainerWithStruct") +@_cdecl("bjs_testContainerWithStruct") +public func _bjs_testContainerWithStruct() -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = roundTripAllTypesResult(_: AllTypesResult.bridgeJSLiftParameter(result)) + let ret = testContainerWithStruct(_: DataPoint.bridgeJSLiftParameter()) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripTypedPayloadResult") -@_cdecl("bjs_roundTripTypedPayloadResult") -public func _bjs_roundTripTypedPayloadResult(_ result: Int32) -> Void { +@_expose(wasm, "bjs_roundTripJSObjectContainer") +@_cdecl("bjs_roundTripJSObjectContainer") +public func _bjs_roundTripJSObjectContainer() -> Void { #if arch(wasm32) - let ret = roundTripTypedPayloadResult(_: TypedPayloadResult.bridgeJSLiftParameter(result)) + let ret = roundTripJSObjectContainer(_: JSObjectContainer.bridgeJSLiftParameter()) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_createPropertyHolder") -@_cdecl("bjs_createPropertyHolder") -public func _bjs_createPropertyHolder(_ intValue: Int32, _ floatValue: Float32, _ doubleValue: Float64, _ boolValue: Int32, _ stringValueBytes: Int32, _ stringValueLength: Int32, _ jsObject: Int32) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_roundTripFooContainer") +@_cdecl("bjs_roundTripFooContainer") +public func _bjs_roundTripFooContainer() -> Void { #if arch(wasm32) - let ret = createPropertyHolder(intValue: Int.bridgeJSLiftParameter(intValue), floatValue: Float.bridgeJSLiftParameter(floatValue), doubleValue: Double.bridgeJSLiftParameter(doubleValue), boolValue: Bool.bridgeJSLiftParameter(boolValue), stringValue: String.bridgeJSLiftParameter(stringValueBytes, stringValueLength), jsObject: JSObject.bridgeJSLiftParameter(jsObject)) + let ret = roundTripFooContainer(_: FooContainer.bridgeJSLiftParameter()) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_testPropertyHolder") -@_cdecl("bjs_testPropertyHolder") -public func _bjs_testPropertyHolder(_ holder: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_roundTripArrayMembers") +@_cdecl("bjs_roundTripArrayMembers") +public func _bjs_roundTripArrayMembers() -> Void { #if arch(wasm32) - let ret = testPropertyHolder(holder: PropertyHolder.bridgeJSLiftParameter(holder)) + let ret = roundTripArrayMembers(_: ArrayMembers.bridgeJSLiftParameter()) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_resetObserverCounts") -@_cdecl("bjs_resetObserverCounts") -public func _bjs_resetObserverCounts() -> Void { +@_expose(wasm, "bjs_arrayMembersSum") +@_cdecl("bjs_arrayMembersSum") +public func _bjs_arrayMembersSum() -> Int32 { #if arch(wasm32) - resetObserverCounts() + let _tmp_values = [Int].bridgeJSStackPop() + let _tmp_value = ArrayMembers.bridgeJSLiftParameter() + let ret = arrayMembersSum(_: _tmp_value, _: _tmp_values) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_getObserverStats") -@_cdecl("bjs_getObserverStats") -public func _bjs_getObserverStats() -> Void { +@_expose(wasm, "bjs_arrayMembersFirst") +@_cdecl("bjs_arrayMembersFirst") +public func _bjs_arrayMembersFirst() -> Void { #if arch(wasm32) - let ret = getObserverStats() + let _tmp_values = [String].bridgeJSStackPop() + let _tmp_value = ArrayMembers.bridgeJSLiftParameter() + let ret = arrayMembersFirst(_: _tmp_value, _: _tmp_values) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_formatName") -@_cdecl("bjs_formatName") -public func _bjs_formatName(_ nameBytes: Int32, _ nameLength: Int32, _ transform: Int32) -> Void { +@_expose(wasm, "bjs_PolygonReference_init") +@_cdecl("bjs_PolygonReference_init") +public func _bjs_PolygonReference_init(_ labelBytes: Int32, _ labelLength: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = formatName(_: String.bridgeJSLiftParameter(nameBytes, nameLength), transform: _BJS_Closure_20BridgeJSRuntimeTestsSS_SS.bridgeJSLift(transform)) + let ret = PolygonReference(verticesData: [Double].bridgeJSStackPop(), label: String.bridgeJSLiftParameter(labelBytes, labelLength)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeFormatter") -@_cdecl("bjs_makeFormatter") -public func _bjs_makeFormatter(_ prefixBytes: Int32, _ prefixLength: Int32) -> Int32 { +@_expose(wasm, "bjs_PolygonReference_vertexCount") +@_cdecl("bjs_PolygonReference_vertexCount") +public func _bjs_PolygonReference_vertexCount(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = makeFormatter(prefix: String.bridgeJSLiftParameter(prefixBytes, prefixLength)) - return JSTypedClosure(ret).bridgeJSLowerReturn() + let ret = PolygonReference.bridgeJSLiftParameter(_self).vertexCount() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_makeAdder") -@_cdecl("bjs_makeAdder") -public func _bjs_makeAdder(_ base: Int32) -> Int32 { +@_expose(wasm, "bjs_PolygonReference_summary") +@_cdecl("bjs_PolygonReference_summary") +public func _bjs_PolygonReference_summary(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = makeAdder(base: Int.bridgeJSLiftParameter(base)) - return JSTypedClosure(ret).bridgeJSLowerReturn() + let ret = PolygonReference.bridgeJSLiftParameter(_self).summary() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripPointerFields") -@_cdecl("bjs_roundTripPointerFields") -public func _bjs_roundTripPointerFields() -> Void { +@_expose(wasm, "bjs_PolygonReference_snapshot") +@_cdecl("bjs_PolygonReference_snapshot") +public func _bjs_PolygonReference_snapshot(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = roundTripPointerFields(_: PointerFields.bridgeJSLiftParameter()) + let ret = PolygonReference.bridgeJSLiftParameter(_self).snapshot() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_testStructDefault") -@_cdecl("bjs_testStructDefault") -public func _bjs_testStructDefault() -> Void { +@_expose(wasm, "bjs_PolygonReference_merge") +@_cdecl("bjs_PolygonReference_merge") +public func _bjs_PolygonReference_merge(_ _self: UnsafeMutableRawPointer, _ other: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = testStructDefault(point: DataPoint.bridgeJSLiftParameter()) + let ret = PolygonReference.bridgeJSLiftParameter(_self).merge(_: Polygon.bridgeJSLiftParameter(other)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_cartToJSObject") -@_cdecl("bjs_cartToJSObject") -public func _bjs_cartToJSObject() -> Int32 { +@_expose(wasm, "bjs_PolygonReference_static_origin") +@_cdecl("bjs_PolygonReference_static_origin") +public func _bjs_PolygonReference_static_origin(_ labelBytes: Int32, _ labelLength: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = cartToJSObject(_: CopyableCart.bridgeJSLiftParameter()) + let ret = PolygonReference.origin(label: String.bridgeJSLiftParameter(labelBytes, labelLength)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_nestedCartToJSObject") -@_cdecl("bjs_nestedCartToJSObject") -public func _bjs_nestedCartToJSObject() -> Int32 { +@_expose(wasm, "bjs_PolygonReference_deinit") +@_cdecl("bjs_PolygonReference_deinit") +public func _bjs_PolygonReference_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = nestedCartToJSObject(_: CopyableNestedCart.bridgeJSLiftParameter()) - return ret.bridgeJSLowerReturn() + Unmanaged.fromOpaque(pointer).release() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripDataPoint") -@_cdecl("bjs_roundTripDataPoint") -public func _bjs_roundTripDataPoint() -> Void { +extension PolygonReference: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_PolygonReference_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_PolygonReference_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_PolygonReference_wrap") +fileprivate func _bjs_PolygonReference_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_PolygonReference_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_PolygonReference_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_PolygonReference_wrap_extern(pointer) +} + +@_expose(wasm, "bjs_TagReference_describe") +@_cdecl("bjs_TagReference_describe") +public func _bjs_TagReference_describe(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = roundTripDataPoint(_: DataPoint.bridgeJSLiftParameter()) + let ret = TagReference.bridgeJSLiftParameter(_self).describe() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripPublicPoint") -@_cdecl("bjs_roundTripPublicPoint") -public func _bjs_roundTripPublicPoint() -> Void { +@_expose(wasm, "bjs_TagReference_deinit") +@_cdecl("bjs_TagReference_deinit") +public func _bjs_TagReference_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = roundTripPublicPoint(_: PublicPoint.bridgeJSLiftParameter()) - return ret.bridgeJSLowerReturn() + Unmanaged.fromOpaque(pointer).release() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripContact") -@_cdecl("bjs_roundTripContact") -public func _bjs_roundTripContact() -> Void { +extension TagReference: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_TagReference_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_TagReference_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_TagReference_wrap") +fileprivate func _bjs_TagReference_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_TagReference_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_TagReference_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_TagReference_wrap_extern(pointer) +} + +@_expose(wasm, "bjs_TagHolderReference_init") +@_cdecl("bjs_TagHolderReference_init") +public func _bjs_TagHolderReference_init(_ tag: UnsafeMutableRawPointer, _ version: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = roundTripContact(_: Contact.bridgeJSLiftParameter()) + let ret = TagHolderReference(tag: Tag.bridgeJSLiftParameter(tag), version: Int.bridgeJSLiftParameter(version)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripConfig") -@_cdecl("bjs_roundTripConfig") -public func _bjs_roundTripConfig() -> Void { +@_expose(wasm, "bjs_TagHolderReference_describe") +@_cdecl("bjs_TagHolderReference_describe") +public func _bjs_TagHolderReference_describe(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = roundTripConfig(_: Config.bridgeJSLiftParameter()) + let ret = TagHolderReference.bridgeJSLiftParameter(_self).describe() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripSessionData") -@_cdecl("bjs_roundTripSessionData") -public func _bjs_roundTripSessionData() -> Void { +@_expose(wasm, "bjs_TagHolderReference_tag_get") +@_cdecl("bjs_TagHolderReference_tag_get") +public func _bjs_TagHolderReference_tag_get(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = roundTripSessionData(_: SessionData.bridgeJSLiftParameter()) + let ret = TagHolderReference.bridgeJSLiftParameter(_self).tag return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripValidationReport") -@_cdecl("bjs_roundTripValidationReport") -public func _bjs_roundTripValidationReport() -> Void { +@_expose(wasm, "bjs_TagHolderReference_tag_set") +@_cdecl("bjs_TagHolderReference_tag_set") +public func _bjs_TagHolderReference_tag_set(_ _self: UnsafeMutableRawPointer, _ value: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = roundTripValidationReport(_: ValidationReport.bridgeJSLiftParameter()) - return ret.bridgeJSLowerReturn() + TagHolderReference.bridgeJSLiftParameter(_self).tag = Tag.bridgeJSLiftParameter(value) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripAdvancedConfig") -@_cdecl("bjs_roundTripAdvancedConfig") -public func _bjs_roundTripAdvancedConfig() -> Void { +@_expose(wasm, "bjs_TagHolderReference_version_get") +@_cdecl("bjs_TagHolderReference_version_get") +public func _bjs_TagHolderReference_version_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = roundTripAdvancedConfig(_: AdvancedConfig.bridgeJSLiftParameter()) + let ret = TagHolderReference.bridgeJSLiftParameter(_self).version return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripMeasurementConfig") -@_cdecl("bjs_roundTripMeasurementConfig") -public func _bjs_roundTripMeasurementConfig() -> Void { +@_expose(wasm, "bjs_TagHolderReference_version_set") +@_cdecl("bjs_TagHolderReference_version_set") +public func _bjs_TagHolderReference_version_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - let ret = roundTripMeasurementConfig(_: MeasurementConfig.bridgeJSLiftParameter()) - return ret.bridgeJSLowerReturn() + TagHolderReference.bridgeJSLiftParameter(_self).version = Int.bridgeJSLiftParameter(value) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_updateValidationReport") -@_cdecl("bjs_updateValidationReport") -public func _bjs_updateValidationReport(_ newResultIsSome: Int32, _ newResultCaseId: Int32) -> Void { +@_expose(wasm, "bjs_TagHolderReference_deinit") +@_cdecl("bjs_TagHolderReference_deinit") +public func _bjs_TagHolderReference_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let _tmp_report = ValidationReport.bridgeJSLiftParameter() - let _tmp_newResult = Optional.bridgeJSLiftParameter(newResultIsSome, newResultCaseId) - let ret = updateValidationReport(_: _tmp_newResult, _: _tmp_report) - return ret.bridgeJSLowerReturn() + Unmanaged.fromOpaque(pointer).release() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_testContainerWithStruct") -@_cdecl("bjs_testContainerWithStruct") -public func _bjs_testContainerWithStruct() -> UnsafeMutableRawPointer { +extension TagHolderReference: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_TagHolderReference_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_TagHolderReference_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_TagHolderReference_wrap") +fileprivate func _bjs_TagHolderReference_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_TagHolderReference_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_TagHolderReference_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_TagHolderReference_wrap_extern(pointer) +} + +@_expose(wasm, "bjs_PriorityReference_describe") +@_cdecl("bjs_PriorityReference_describe") +public func _bjs_PriorityReference_describe(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = testContainerWithStruct(_: DataPoint.bridgeJSLiftParameter()) + let ret = PriorityReference.bridgeJSLiftParameter(_self).describe() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripJSObjectContainer") -@_cdecl("bjs_roundTripJSObjectContainer") -public func _bjs_roundTripJSObjectContainer() -> Void { +@_expose(wasm, "bjs_PriorityReference_weight") +@_cdecl("bjs_PriorityReference_weight") +public func _bjs_PriorityReference_weight(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = roundTripJSObjectContainer(_: JSObjectContainer.bridgeJSLiftParameter()) + let ret = PriorityReference.bridgeJSLiftParameter(_self).weight() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripFooContainer") -@_cdecl("bjs_roundTripFooContainer") -public func _bjs_roundTripFooContainer() -> Void { +@_expose(wasm, "bjs_PriorityReference_static_low") +@_cdecl("bjs_PriorityReference_static_low") +public func _bjs_PriorityReference_static_low() -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = roundTripFooContainer(_: FooContainer.bridgeJSLiftParameter()) + let ret = PriorityReference.low() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_roundTripArrayMembers") -@_cdecl("bjs_roundTripArrayMembers") -public func _bjs_roundTripArrayMembers() -> Void { +@_expose(wasm, "bjs_PriorityReference_static_medium") +@_cdecl("bjs_PriorityReference_static_medium") +public func _bjs_PriorityReference_static_medium() -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = roundTripArrayMembers(_: ArrayMembers.bridgeJSLiftParameter()) + let ret = PriorityReference.medium() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_arrayMembersSum") -@_cdecl("bjs_arrayMembersSum") -public func _bjs_arrayMembersSum() -> Int32 { +@_expose(wasm, "bjs_PriorityReference_static_high") +@_cdecl("bjs_PriorityReference_static_high") +public func _bjs_PriorityReference_static_high() -> UnsafeMutableRawPointer { #if arch(wasm32) - let _tmp_values = [Int].bridgeJSStackPop() - let _tmp_value = ArrayMembers.bridgeJSLiftParameter() - let ret = arrayMembersSum(_: _tmp_value, _: _tmp_values) + let ret = PriorityReference.high() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_arrayMembersFirst") -@_cdecl("bjs_arrayMembersFirst") -public func _bjs_arrayMembersFirst() -> Void { +@_expose(wasm, "bjs_PriorityReference_deinit") +@_cdecl("bjs_PriorityReference_deinit") +public func _bjs_PriorityReference_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let _tmp_values = [String].bridgeJSStackPop() - let _tmp_value = ArrayMembers.bridgeJSLiftParameter() - let ret = arrayMembersFirst(_: _tmp_value, _: _tmp_values) - return ret.bridgeJSLowerReturn() + Unmanaged.fromOpaque(pointer).release() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PolygonReference_init") -@_cdecl("bjs_PolygonReference_init") -public func _bjs_PolygonReference_init(_ labelBytes: Int32, _ labelLength: Int32) -> UnsafeMutableRawPointer { +extension PriorityReference: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_PriorityReference_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_PriorityReference_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_PriorityReference_wrap") +fileprivate func _bjs_PriorityReference_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_PriorityReference_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_PriorityReference_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_PriorityReference_wrap_extern(pointer) +} + +@_expose(wasm, "bjs_ClosureSupportExports_static_makeIntToInt") +@_cdecl("bjs_ClosureSupportExports_static_makeIntToInt") +public func _bjs_ClosureSupportExports_static_makeIntToInt(_ base: Int32) -> Int32 { #if arch(wasm32) - let ret = PolygonReference(verticesData: [Double].bridgeJSStackPop(), label: String.bridgeJSLiftParameter(labelBytes, labelLength)) - return ret.bridgeJSLowerReturn() + let ret = ClosureSupportExports.makeIntToInt(_: Int.bridgeJSLiftParameter(base)) + return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PolygonReference_vertexCount") -@_cdecl("bjs_PolygonReference_vertexCount") -public func _bjs_PolygonReference_vertexCount(_ _self: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_ClosureSupportExports_static_makeDoubleToDouble") +@_cdecl("bjs_ClosureSupportExports_static_makeDoubleToDouble") +public func _bjs_ClosureSupportExports_static_makeDoubleToDouble(_ base: Float64) -> Int32 { #if arch(wasm32) - let ret = PolygonReference.bridgeJSLiftParameter(_self).vertexCount() - return ret.bridgeJSLowerReturn() + let ret = ClosureSupportExports.makeDoubleToDouble(_: Double.bridgeJSLiftParameter(base)) + return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PolygonReference_summary") -@_cdecl("bjs_PolygonReference_summary") -public func _bjs_PolygonReference_summary(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_ClosureSupportExports_static_makeStringToString") +@_cdecl("bjs_ClosureSupportExports_static_makeStringToString") +public func _bjs_ClosureSupportExports_static_makeStringToString(_ prefixBytes: Int32, _ prefixLength: Int32) -> Int32 { #if arch(wasm32) - let ret = PolygonReference.bridgeJSLiftParameter(_self).summary() - return ret.bridgeJSLowerReturn() + let ret = ClosureSupportExports.makeStringToString(_: String.bridgeJSLiftParameter(prefixBytes, prefixLength)) + return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PolygonReference_snapshot") -@_cdecl("bjs_PolygonReference_snapshot") -public func _bjs_PolygonReference_snapshot(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_ClosureSupportExports_static_makeJSIntToInt") +@_cdecl("bjs_ClosureSupportExports_static_makeJSIntToInt") +public func _bjs_ClosureSupportExports_static_makeJSIntToInt(_ base: Int32) -> Int32 { #if arch(wasm32) - let ret = PolygonReference.bridgeJSLiftParameter(_self).snapshot() - return ret.bridgeToJS().bridgeJSLowerReturn() + let ret = ClosureSupportExports.makeJSIntToInt(_: Int.bridgeJSLiftParameter(base)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PolygonReference_merge") -@_cdecl("bjs_PolygonReference_merge") -public func _bjs_PolygonReference_merge(_ _self: UnsafeMutableRawPointer, _ other: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_ClosureSupportExports_static_makeJSDoubleToDouble") +@_cdecl("bjs_ClosureSupportExports_static_makeJSDoubleToDouble") +public func _bjs_ClosureSupportExports_static_makeJSDoubleToDouble(_ base: Float64) -> Int32 { #if arch(wasm32) - let ret = PolygonReference.bridgeJSLiftParameter(_self).merge(_: Polygon.bridgeFromJS(PolygonReference.bridgeJSLiftParameter(other))) - return ret.bridgeToJS().bridgeJSLowerReturn() + let ret = ClosureSupportExports.makeJSDoubleToDouble(_: Double.bridgeJSLiftParameter(base)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PolygonReference_static_origin") -@_cdecl("bjs_PolygonReference_static_origin") -public func _bjs_PolygonReference_static_origin(_ labelBytes: Int32, _ labelLength: Int32) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_ClosureSupportExports_static_makeJSStringToString") +@_cdecl("bjs_ClosureSupportExports_static_makeJSStringToString") +public func _bjs_ClosureSupportExports_static_makeJSStringToString(_ prefixBytes: Int32, _ prefixLength: Int32) -> Int32 { #if arch(wasm32) - let ret = PolygonReference.origin(label: String.bridgeJSLiftParameter(labelBytes, labelLength)) - return ret.bridgeToJS().bridgeJSLowerReturn() + let ret = ClosureSupportExports.makeJSStringToString(_: String.bridgeJSLiftParameter(prefixBytes, prefixLength)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PolygonReference_deinit") -@_cdecl("bjs_PolygonReference_deinit") -public func _bjs_PolygonReference_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_ClosureSupportExports_deinit") +@_cdecl("bjs_ClosureSupportExports_deinit") +public func _bjs_ClosureSupportExports_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() + Unmanaged.fromOpaque(pointer).release() #else fatalError("Only available on WebAssembly") #endif } -extension PolygonReference: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { +extension ClosureSupportExports: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_PolygonReference_wrap(Unmanaged.passRetained(self).toOpaque())))) + return .object(JSObject(id: UInt32(bitPattern: _bjs_ClosureSupportExports_wrap(Unmanaged.passRetained(self).toOpaque())))) } consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { - _bjs_PolygonReference_wrap(Unmanaged.passRetained(self).toOpaque()) + _bjs_ClosureSupportExports_wrap(Unmanaged.passRetained(self).toOpaque()) } } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_PolygonReference_wrap") -fileprivate func _bjs_PolygonReference_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportExports_wrap") +fileprivate func _bjs_ClosureSupportExports_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_PolygonReference_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_ClosureSupportExports_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_PolygonReference_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_PolygonReference_wrap_extern(pointer) +@inline(never) fileprivate func _bjs_ClosureSupportExports_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_ClosureSupportExports_wrap_extern(pointer) } -@_expose(wasm, "bjs_TagReference_describe") -@_cdecl("bjs_TagReference_describe") -public func _bjs_TagReference_describe(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_DefaultArgumentConstructorDefaults_init") +@_cdecl("bjs_DefaultArgumentConstructorDefaults_init") +public func _bjs_DefaultArgumentConstructorDefaults_init(_ nameBytes: Int32, _ nameLength: Int32, _ count: Int32, _ enabled: Int32, _ status: Int32, _ tagIsSome: Int32, _ tagBytes: Int32, _ tagLength: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = TagReference.bridgeJSLiftParameter(_self).describe() + let ret = DefaultArgumentConstructorDefaults(name: String.bridgeJSLiftParameter(nameBytes, nameLength), count: Int.bridgeJSLiftParameter(count), enabled: Bool.bridgeJSLiftParameter(enabled), status: Status.bridgeJSLiftParameter(status), tag: Optional.bridgeJSLiftParameter(tagIsSome, tagBytes, tagLength)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_TagReference_deinit") -@_cdecl("bjs_TagReference_deinit") -public func _bjs_TagReference_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_DefaultArgumentConstructorDefaults_describe") +@_cdecl("bjs_DefaultArgumentConstructorDefaults_describe") +public func _bjs_DefaultArgumentConstructorDefaults_describe(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() + let ret = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).describe() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -extension TagReference: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { - var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_TagReference_wrap(Unmanaged.passRetained(self).toOpaque())))) - } - consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { - _bjs_TagReference_wrap(Unmanaged.passRetained(self).toOpaque()) - } -} - -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_TagReference_wrap") -fileprivate func _bjs_TagReference_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 -#else -fileprivate func _bjs_TagReference_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func _bjs_TagReference_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_TagReference_wrap_extern(pointer) -} - -@_expose(wasm, "bjs_TokenReference_init") -@_cdecl("bjs_TokenReference_init") -public func _bjs_TokenReference_init(_ value: Int32) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_DefaultArgumentConstructorDefaults_name_get") +@_cdecl("bjs_DefaultArgumentConstructorDefaults_name_get") +public func _bjs_DefaultArgumentConstructorDefaults_name_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = TokenReference(value: Int.bridgeJSLiftParameter(value)) + let ret = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).name return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_TokenReference_read") -@_cdecl("bjs_TokenReference_read") -public func _bjs_TokenReference_read(_ _self: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_DefaultArgumentConstructorDefaults_name_set") +@_cdecl("bjs_DefaultArgumentConstructorDefaults_name_set") +public func _bjs_DefaultArgumentConstructorDefaults_name_set(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - let ret = TokenReference.bridgeJSLiftParameter(_self).read() - return ret.bridgeJSLowerReturn() + DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).name = String.bridgeJSLiftParameter(valueBytes, valueLength) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_TokenReference_deinit") -@_cdecl("bjs_TokenReference_deinit") -public func _bjs_TokenReference_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_DefaultArgumentConstructorDefaults_count_get") +@_cdecl("bjs_DefaultArgumentConstructorDefaults_count_get") +public func _bjs_DefaultArgumentConstructorDefaults_count_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() + let ret = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).count + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -extension TokenReference: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { - var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_TokenReference_wrap(Unmanaged.passRetained(self).toOpaque())))) - } - consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { - _bjs_TokenReference_wrap(Unmanaged.passRetained(self).toOpaque()) - } -} - -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_TokenReference_wrap") -fileprivate func _bjs_TokenReference_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 -#else -fileprivate func _bjs_TokenReference_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_DefaultArgumentConstructorDefaults_count_set") +@_cdecl("bjs_DefaultArgumentConstructorDefaults_count_set") +public func _bjs_DefaultArgumentConstructorDefaults_count_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { + #if arch(wasm32) + DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).count = Int.bridgeJSLiftParameter(value) + #else fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func _bjs_TokenReference_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_TokenReference_wrap_extern(pointer) + #endif } -@_expose(wasm, "bjs_TagHolderReference_init") -@_cdecl("bjs_TagHolderReference_init") -public func _bjs_TagHolderReference_init(_ tag: UnsafeMutableRawPointer, _ version: Int32) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_DefaultArgumentConstructorDefaults_enabled_get") +@_cdecl("bjs_DefaultArgumentConstructorDefaults_enabled_get") +public func _bjs_DefaultArgumentConstructorDefaults_enabled_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = TagHolderReference(tag: Tag.bridgeFromJS(TagReference.bridgeJSLiftParameter(tag)), version: Int.bridgeJSLiftParameter(version)) + let ret = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).enabled return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_TagHolderReference_describe") -@_cdecl("bjs_TagHolderReference_describe") -public func _bjs_TagHolderReference_describe(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_DefaultArgumentConstructorDefaults_enabled_set") +@_cdecl("bjs_DefaultArgumentConstructorDefaults_enabled_set") +public func _bjs_DefaultArgumentConstructorDefaults_enabled_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - let ret = TagHolderReference.bridgeJSLiftParameter(_self).describe() - return ret.bridgeJSLowerReturn() + DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).enabled = Bool.bridgeJSLiftParameter(value) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_TagHolderReference_tag_get") -@_cdecl("bjs_TagHolderReference_tag_get") -public func _bjs_TagHolderReference_tag_get(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_DefaultArgumentConstructorDefaults_status_get") +@_cdecl("bjs_DefaultArgumentConstructorDefaults_status_get") +public func _bjs_DefaultArgumentConstructorDefaults_status_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = TagHolderReference.bridgeJSLiftParameter(_self).tag - return ret.bridgeToJS().bridgeJSLowerReturn() + let ret = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).status + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_TagHolderReference_tag_set") -@_cdecl("bjs_TagHolderReference_tag_set") -public func _bjs_TagHolderReference_tag_set(_ _self: UnsafeMutableRawPointer, _ value: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_DefaultArgumentConstructorDefaults_status_set") +@_cdecl("bjs_DefaultArgumentConstructorDefaults_status_set") +public func _bjs_DefaultArgumentConstructorDefaults_status_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - TagHolderReference.bridgeJSLiftParameter(_self).tag = Tag.bridgeFromJS(TagReference.bridgeJSLiftParameter(value)) + DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).status = Status.bridgeJSLiftParameter(value) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_TagHolderReference_version_get") -@_cdecl("bjs_TagHolderReference_version_get") -public func _bjs_TagHolderReference_version_get(_ _self: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_DefaultArgumentConstructorDefaults_tag_get") +@_cdecl("bjs_DefaultArgumentConstructorDefaults_tag_get") +public func _bjs_DefaultArgumentConstructorDefaults_tag_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = TagHolderReference.bridgeJSLiftParameter(_self).version + let ret = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).tag return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_TagHolderReference_version_set") -@_cdecl("bjs_TagHolderReference_version_set") -public func _bjs_TagHolderReference_version_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { +@_expose(wasm, "bjs_DefaultArgumentConstructorDefaults_tag_set") +@_cdecl("bjs_DefaultArgumentConstructorDefaults_tag_set") +public func _bjs_DefaultArgumentConstructorDefaults_tag_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - TagHolderReference.bridgeJSLiftParameter(_self).version = Int.bridgeJSLiftParameter(value) + DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).tag = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_TagHolderReference_deinit") -@_cdecl("bjs_TagHolderReference_deinit") -public func _bjs_TagHolderReference_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_DefaultArgumentConstructorDefaults_deinit") +@_cdecl("bjs_DefaultArgumentConstructorDefaults_deinit") +public func _bjs_DefaultArgumentConstructorDefaults_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() + Unmanaged.fromOpaque(pointer).release() #else fatalError("Only available on WebAssembly") #endif } -extension TagHolderReference: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { +extension DefaultArgumentConstructorDefaults: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_TagHolderReference_wrap(Unmanaged.passRetained(self).toOpaque())))) + return .object(JSObject(id: UInt32(bitPattern: _bjs_DefaultArgumentConstructorDefaults_wrap(Unmanaged.passRetained(self).toOpaque())))) } consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { - _bjs_TagHolderReference_wrap(Unmanaged.passRetained(self).toOpaque()) + _bjs_DefaultArgumentConstructorDefaults_wrap(Unmanaged.passRetained(self).toOpaque()) } } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_TagHolderReference_wrap") -fileprivate func _bjs_TagHolderReference_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DefaultArgumentConstructorDefaults_wrap") +fileprivate func _bjs_DefaultArgumentConstructorDefaults_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_TagHolderReference_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_DefaultArgumentConstructorDefaults_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_TagHolderReference_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_TagHolderReference_wrap_extern(pointer) +@inline(never) fileprivate func _bjs_DefaultArgumentConstructorDefaults_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_DefaultArgumentConstructorDefaults_wrap_extern(pointer) } -@_expose(wasm, "bjs_PriorityReference_describe") -@_cdecl("bjs_PriorityReference_describe") -public func _bjs_PriorityReference_describe(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_Greeter_init") +@_cdecl("bjs_Greeter_init") +public func _bjs_Greeter_init(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = PriorityReference.bridgeJSLiftParameter(_self).describe() + let ret = Greeter(name: String.bridgeJSLiftParameter(nameBytes, nameLength)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PriorityReference_weight") -@_cdecl("bjs_PriorityReference_weight") -public func _bjs_PriorityReference_weight(_ _self: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_Greeter_greet") +@_cdecl("bjs_Greeter_greet") +public func _bjs_Greeter_greet(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = PriorityReference.bridgeJSLiftParameter(_self).weight() + let ret = Greeter.bridgeJSLiftParameter(_self).greet() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PriorityReference_static_low") -@_cdecl("bjs_PriorityReference_static_low") -public func _bjs_PriorityReference_static_low() -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_Greeter_changeName") +@_cdecl("bjs_Greeter_changeName") +public func _bjs_Greeter_changeName(_ _self: UnsafeMutableRawPointer, _ nameBytes: Int32, _ nameLength: Int32) -> Void { #if arch(wasm32) - let ret = PriorityReference.low() - return ret.bridgeToJS().bridgeJSLowerReturn() + Greeter.bridgeJSLiftParameter(_self).changeName(name: String.bridgeJSLiftParameter(nameBytes, nameLength)) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PriorityReference_static_medium") -@_cdecl("bjs_PriorityReference_static_medium") -public func _bjs_PriorityReference_static_medium() -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_Greeter_greetWith") +@_cdecl("bjs_Greeter_greetWith") +public func _bjs_Greeter_greetWith(_ _self: UnsafeMutableRawPointer, _ greeter: UnsafeMutableRawPointer, _ customGreeting: Int32) -> Void { #if arch(wasm32) - let ret = PriorityReference.medium() - return ret.bridgeToJS().bridgeJSLowerReturn() + let ret = Greeter.bridgeJSLiftParameter(_self).greetWith(greeter: Greeter.bridgeJSLiftParameter(greeter), customGreeting: _BJS_Closure_20BridgeJSRuntimeTests7GreeterC_SS.bridgeJSLift(customGreeting)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PriorityReference_static_high") -@_cdecl("bjs_PriorityReference_static_high") -public func _bjs_PriorityReference_static_high() -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_Greeter_makeFormatter") +@_cdecl("bjs_Greeter_makeFormatter") +public func _bjs_Greeter_makeFormatter(_ _self: UnsafeMutableRawPointer, _ suffixBytes: Int32, _ suffixLength: Int32) -> Int32 { + #if arch(wasm32) + let ret = Greeter.bridgeJSLiftParameter(_self).makeFormatter(suffix: String.bridgeJSLiftParameter(suffixBytes, suffixLength)) + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Greeter_static_makeCreator") +@_cdecl("bjs_Greeter_static_makeCreator") +public func _bjs_Greeter_static_makeCreator(_ defaultNameBytes: Int32, _ defaultNameLength: Int32) -> Int32 { + #if arch(wasm32) + let ret = Greeter.makeCreator(defaultName: String.bridgeJSLiftParameter(defaultNameBytes, defaultNameLength)) + return JSTypedClosure(ret).bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Greeter_makeCustomGreeter") +@_cdecl("bjs_Greeter_makeCustomGreeter") +public func _bjs_Greeter_makeCustomGreeter(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = PriorityReference.high() - return ret.bridgeToJS().bridgeJSLowerReturn() + let ret = Greeter.bridgeJSLiftParameter(_self).makeCustomGreeter() + return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PriorityReference_deinit") -@_cdecl("bjs_PriorityReference_deinit") -public func _bjs_PriorityReference_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_Greeter_greetEnthusiastically") +@_cdecl("bjs_Greeter_greetEnthusiastically") +public func _bjs_Greeter_greetEnthusiastically(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() + let ret = Greeter.bridgeJSLiftParameter(_self).greetEnthusiastically() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -extension PriorityReference: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { - var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_PriorityReference_wrap(Unmanaged.passRetained(self).toOpaque())))) - } - consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { - _bjs_PriorityReference_wrap(Unmanaged.passRetained(self).toOpaque()) - } -} - -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_PriorityReference_wrap") -fileprivate func _bjs_PriorityReference_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 -#else -fileprivate func _bjs_PriorityReference_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func _bjs_PriorityReference_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_PriorityReference_wrap_extern(pointer) -} - -@_expose(wasm, "bjs_ClosureSupportExports_static_makeIntToInt") -@_cdecl("bjs_ClosureSupportExports_static_makeIntToInt") -public func _bjs_ClosureSupportExports_static_makeIntToInt(_ base: Int32) -> Int32 { +@_expose(wasm, "bjs_Greeter_static_greetAnonymously") +@_cdecl("bjs_Greeter_static_greetAnonymously") +public func _bjs_Greeter_static_greetAnonymously() -> Void { #if arch(wasm32) - let ret = ClosureSupportExports.makeIntToInt(_: Int.bridgeJSLiftParameter(base)) - return JSTypedClosure(ret).bridgeJSLowerReturn() + let ret = Greeter.greetAnonymously() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_ClosureSupportExports_static_makeDoubleToDouble") -@_cdecl("bjs_ClosureSupportExports_static_makeDoubleToDouble") -public func _bjs_ClosureSupportExports_static_makeDoubleToDouble(_ base: Float64) -> Int32 { +@_expose(wasm, "bjs_Greeter_name_get") +@_cdecl("bjs_Greeter_name_get") +public func _bjs_Greeter_name_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ClosureSupportExports.makeDoubleToDouble(_: Double.bridgeJSLiftParameter(base)) - return JSTypedClosure(ret).bridgeJSLowerReturn() + let ret = Greeter.bridgeJSLiftParameter(_self).name + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_ClosureSupportExports_static_makeStringToString") -@_cdecl("bjs_ClosureSupportExports_static_makeStringToString") -public func _bjs_ClosureSupportExports_static_makeStringToString(_ prefixBytes: Int32, _ prefixLength: Int32) -> Int32 { +@_expose(wasm, "bjs_Greeter_name_set") +@_cdecl("bjs_Greeter_name_set") +public func _bjs_Greeter_name_set(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - let ret = ClosureSupportExports.makeStringToString(_: String.bridgeJSLiftParameter(prefixBytes, prefixLength)) - return JSTypedClosure(ret).bridgeJSLowerReturn() + Greeter.bridgeJSLiftParameter(_self).name = String.bridgeJSLiftParameter(valueBytes, valueLength) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_ClosureSupportExports_static_makeJSIntToInt") -@_cdecl("bjs_ClosureSupportExports_static_makeJSIntToInt") -public func _bjs_ClosureSupportExports_static_makeJSIntToInt(_ base: Int32) -> Int32 { +@_expose(wasm, "bjs_Greeter_prefix_get") +@_cdecl("bjs_Greeter_prefix_get") +public func _bjs_Greeter_prefix_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ClosureSupportExports.makeJSIntToInt(_: Int.bridgeJSLiftParameter(base)) + let ret = Greeter.bridgeJSLiftParameter(_self).prefix return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_ClosureSupportExports_static_makeJSDoubleToDouble") -@_cdecl("bjs_ClosureSupportExports_static_makeJSDoubleToDouble") -public func _bjs_ClosureSupportExports_static_makeJSDoubleToDouble(_ base: Float64) -> Int32 { +@_expose(wasm, "bjs_Greeter_nameCount_get") +@_cdecl("bjs_Greeter_nameCount_get") +public func _bjs_Greeter_nameCount_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = ClosureSupportExports.makeJSDoubleToDouble(_: Double.bridgeJSLiftParameter(base)) + let ret = Greeter.bridgeJSLiftParameter(_self).nameCount return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_ClosureSupportExports_static_makeJSStringToString") -@_cdecl("bjs_ClosureSupportExports_static_makeJSStringToString") -public func _bjs_ClosureSupportExports_static_makeJSStringToString(_ prefixBytes: Int32, _ prefixLength: Int32) -> Int32 { +@_expose(wasm, "bjs_Greeter_static_defaultGreeting_get") +@_cdecl("bjs_Greeter_static_defaultGreeting_get") +public func _bjs_Greeter_static_defaultGreeting_get() -> Void { #if arch(wasm32) - let ret = ClosureSupportExports.makeJSStringToString(_: String.bridgeJSLiftParameter(prefixBytes, prefixLength)) + let ret = Greeter.defaultGreeting return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_ClosureSupportExports_deinit") -@_cdecl("bjs_ClosureSupportExports_deinit") -public func _bjs_ClosureSupportExports_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_Greeter_deinit") +@_cdecl("bjs_Greeter_deinit") +public func _bjs_Greeter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() + Unmanaged.fromOpaque(pointer).release() #else fatalError("Only available on WebAssembly") #endif } -extension ClosureSupportExports: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { - var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_ClosureSupportExports_wrap(Unmanaged.passRetained(self).toOpaque())))) +extension Greeter: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + public var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_Greeter_wrap(Unmanaged.passRetained(self).toOpaque())))) } - consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { - _bjs_ClosureSupportExports_wrap(Unmanaged.passRetained(self).toOpaque()) + public consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_Greeter_wrap(Unmanaged.passRetained(self).toOpaque()) } } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportExports_wrap") -fileprivate func _bjs_ClosureSupportExports_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Greeter_wrap") +fileprivate func _bjs_Greeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_ClosureSupportExports_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_Greeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_ClosureSupportExports_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_ClosureSupportExports_wrap_extern(pointer) +@inline(never) fileprivate func _bjs_Greeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Greeter_wrap_extern(pointer) } -@_expose(wasm, "bjs_DefaultArgumentConstructorDefaults_init") -@_cdecl("bjs_DefaultArgumentConstructorDefaults_init") -public func _bjs_DefaultArgumentConstructorDefaults_init(_ nameBytes: Int32, _ nameLength: Int32, _ count: Int32, _ enabled: Int32, _ status: Int32, _ tagIsSome: Int32, _ tagBytes: Int32, _ tagLength: Int32) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_Calculator_square") +@_cdecl("bjs_Calculator_square") +public func _bjs_Calculator_square(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Int32 { #if arch(wasm32) - let ret = DefaultArgumentConstructorDefaults(name: String.bridgeJSLiftParameter(nameBytes, nameLength), count: Int.bridgeJSLiftParameter(count), enabled: Bool.bridgeJSLiftParameter(enabled), status: Status.bridgeJSLiftParameter(status), tag: Optional.bridgeJSLiftParameter(tagIsSome, tagBytes, tagLength)) + let ret = Calculator.bridgeJSLiftParameter(_self).square(value: Int.bridgeJSLiftParameter(value)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DefaultArgumentConstructorDefaults_describe") -@_cdecl("bjs_DefaultArgumentConstructorDefaults_describe") -public func _bjs_DefaultArgumentConstructorDefaults_describe(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_Calculator_add") +@_cdecl("bjs_Calculator_add") +public func _bjs_Calculator_add(_ _self: UnsafeMutableRawPointer, _ a: Int32, _ b: Int32) -> Int32 { #if arch(wasm32) - let ret = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).describe() + let ret = Calculator.bridgeJSLiftParameter(_self).add(a: Int.bridgeJSLiftParameter(a), b: Int.bridgeJSLiftParameter(b)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DefaultArgumentConstructorDefaults_name_get") -@_cdecl("bjs_DefaultArgumentConstructorDefaults_name_get") -public func _bjs_DefaultArgumentConstructorDefaults_name_get(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_Calculator_asyncMakePoint") +@_cdecl("bjs_Calculator_asyncMakePoint") +public func _bjs_Calculator_asyncMakePoint(_ _self: UnsafeMutableRawPointer, _ x: Int32, _ y: Int32) -> Int32 { #if arch(wasm32) - let ret = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).name - return ret.bridgeJSLowerReturn() + return _bjs_makePromise(resolve: Promise_resolve_11PublicPointV, reject: Promise_reject) { + return await Calculator.bridgeJSLiftParameter(_self).asyncMakePoint(x: Int.bridgeJSLiftParameter(x), y: Int.bridgeJSLiftParameter(y)) + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DefaultArgumentConstructorDefaults_name_set") -@_cdecl("bjs_DefaultArgumentConstructorDefaults_name_set") -public func _bjs_DefaultArgumentConstructorDefaults_name_set(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { +@_expose(wasm, "bjs_Calculator_deinit") +@_cdecl("bjs_Calculator_deinit") +public func _bjs_Calculator_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).name = String.bridgeJSLiftParameter(valueBytes, valueLength) + Unmanaged.fromOpaque(pointer).release() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DefaultArgumentConstructorDefaults_count_get") -@_cdecl("bjs_DefaultArgumentConstructorDefaults_count_get") -public func _bjs_DefaultArgumentConstructorDefaults_count_get(_ _self: UnsafeMutableRawPointer) -> Int32 { - #if arch(wasm32) - let ret = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).count - return ret.bridgeJSLowerReturn() - #else +extension Calculator: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_Calculator_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_Calculator_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Calculator_wrap") +fileprivate func _bjs_Calculator_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_Calculator_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func _bjs_Calculator_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Calculator_wrap_extern(pointer) } -@_expose(wasm, "bjs_DefaultArgumentConstructorDefaults_count_set") -@_cdecl("bjs_DefaultArgumentConstructorDefaults_count_set") -public func _bjs_DefaultArgumentConstructorDefaults_count_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { +@_expose(wasm, "bjs_InternalGreeter_deinit") +@_cdecl("bjs_InternalGreeter_deinit") +public func _bjs_InternalGreeter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).count = Int.bridgeJSLiftParameter(value) + Unmanaged.fromOpaque(pointer).release() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DefaultArgumentConstructorDefaults_enabled_get") -@_cdecl("bjs_DefaultArgumentConstructorDefaults_enabled_get") -public func _bjs_DefaultArgumentConstructorDefaults_enabled_get(_ _self: UnsafeMutableRawPointer) -> Int32 { +extension InternalGreeter: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + internal var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_InternalGreeter_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + internal consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_InternalGreeter_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_InternalGreeter_wrap") +fileprivate func _bjs_InternalGreeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_InternalGreeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_InternalGreeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_InternalGreeter_wrap_extern(pointer) +} + +@_expose(wasm, "bjs_PublicGreeter_deinit") +@_cdecl("bjs_PublicGreeter_deinit") +public func _bjs_PublicGreeter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).enabled - return ret.bridgeJSLowerReturn() + Unmanaged.fromOpaque(pointer).release() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DefaultArgumentConstructorDefaults_enabled_set") -@_cdecl("bjs_DefaultArgumentConstructorDefaults_enabled_set") -public func _bjs_DefaultArgumentConstructorDefaults_enabled_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { +extension PublicGreeter: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + public var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_PublicGreeter_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + public consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_PublicGreeter_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_PublicGreeter_wrap") +fileprivate func _bjs_PublicGreeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_PublicGreeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_PublicGreeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_PublicGreeter_wrap_extern(pointer) +} + +@_expose(wasm, "bjs_PackageGreeter_deinit") +@_cdecl("bjs_PackageGreeter_deinit") +public func _bjs_PackageGreeter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).enabled = Bool.bridgeJSLiftParameter(value) + Unmanaged.fromOpaque(pointer).release() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DefaultArgumentConstructorDefaults_status_get") -@_cdecl("bjs_DefaultArgumentConstructorDefaults_status_get") -public func _bjs_DefaultArgumentConstructorDefaults_status_get(_ _self: UnsafeMutableRawPointer) -> Int32 { +extension PackageGreeter: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + package var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_PackageGreeter_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + package consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_PackageGreeter_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_PackageGreeter_wrap") +fileprivate func _bjs_PackageGreeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_PackageGreeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_PackageGreeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_PackageGreeter_wrap_extern(pointer) +} + +@_expose(wasm, "bjs_Utils_Converter_init") +@_cdecl("bjs_Utils_Converter_init") +public func _bjs_Utils_Converter_init() -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).status + let ret = Utils.Converter() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DefaultArgumentConstructorDefaults_status_set") -@_cdecl("bjs_DefaultArgumentConstructorDefaults_status_set") -public func _bjs_DefaultArgumentConstructorDefaults_status_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { +@_expose(wasm, "bjs_Utils_Converter_toString") +@_cdecl("bjs_Utils_Converter_toString") +public func _bjs_Utils_Converter_toString(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).status = Status.bridgeJSLiftParameter(value) + let ret = Utils.Converter.bridgeJSLiftParameter(_self).toString(value: Int.bridgeJSLiftParameter(value)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DefaultArgumentConstructorDefaults_tag_get") -@_cdecl("bjs_DefaultArgumentConstructorDefaults_tag_get") -public func _bjs_DefaultArgumentConstructorDefaults_tag_get(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_Utils_Converter_precision_get") +@_cdecl("bjs_Utils_Converter_precision_get") +public func _bjs_Utils_Converter_precision_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).tag + let ret = Utils.Converter.bridgeJSLiftParameter(_self).precision return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DefaultArgumentConstructorDefaults_tag_set") -@_cdecl("bjs_DefaultArgumentConstructorDefaults_tag_set") -public func _bjs_DefaultArgumentConstructorDefaults_tag_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { +@_expose(wasm, "bjs_Utils_Converter_precision_set") +@_cdecl("bjs_Utils_Converter_precision_set") +public func _bjs_Utils_Converter_precision_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - DefaultArgumentConstructorDefaults.bridgeJSLiftParameter(_self).tag = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) + Utils.Converter.bridgeJSLiftParameter(_self).precision = Int.bridgeJSLiftParameter(value) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DefaultArgumentConstructorDefaults_deinit") -@_cdecl("bjs_DefaultArgumentConstructorDefaults_deinit") -public func _bjs_DefaultArgumentConstructorDefaults_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_Utils_Converter_deinit") +@_cdecl("bjs_Utils_Converter_deinit") +public func _bjs_Utils_Converter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() + Unmanaged.fromOpaque(pointer).release() #else fatalError("Only available on WebAssembly") #endif } -extension DefaultArgumentConstructorDefaults: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { +extension Utils.Converter: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_DefaultArgumentConstructorDefaults_wrap(Unmanaged.passRetained(self).toOpaque())))) + return .object(JSObject(id: UInt32(bitPattern: _bjs_Utils_Converter_wrap(Unmanaged.passRetained(self).toOpaque())))) } consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { - _bjs_DefaultArgumentConstructorDefaults_wrap(Unmanaged.passRetained(self).toOpaque()) + _bjs_Utils_Converter_wrap(Unmanaged.passRetained(self).toOpaque()) } } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DefaultArgumentConstructorDefaults_wrap") -fileprivate func _bjs_DefaultArgumentConstructorDefaults_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Utils_Converter_wrap") +fileprivate func _bjs_Utils_Converter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_DefaultArgumentConstructorDefaults_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_Utils_Converter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_DefaultArgumentConstructorDefaults_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_DefaultArgumentConstructorDefaults_wrap_extern(pointer) +@inline(never) fileprivate func _bjs_Utils_Converter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Utils_Converter_wrap_extern(pointer) } -@_expose(wasm, "bjs_Greeter_init") -@_cdecl("bjs_Greeter_init") -public func _bjs_Greeter_init(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_Networking_API_HTTPServer_init") +@_cdecl("bjs_Networking_API_HTTPServer_init") +public func _bjs_Networking_API_HTTPServer_init() -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = Greeter(name: String.bridgeJSLiftParameter(nameBytes, nameLength)) + let ret = Networking.API.HTTPServer() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_Greeter_greet") -@_cdecl("bjs_Greeter_greet") -public func _bjs_Greeter_greet(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_Networking_API_HTTPServer_call") +@_cdecl("bjs_Networking_API_HTTPServer_call") +public func _bjs_Networking_API_HTTPServer_call(_ _self: UnsafeMutableRawPointer, _ method: Int32) -> Void { #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).greet() - return ret.bridgeJSLowerReturn() + Networking.API.HTTPServer.bridgeJSLiftParameter(_self).call(_: Networking.API.Method.bridgeJSLiftParameter(method)) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_Greeter_changeName") -@_cdecl("bjs_Greeter_changeName") -public func _bjs_Greeter_changeName(_ _self: UnsafeMutableRawPointer, _ nameBytes: Int32, _ nameLength: Int32) -> Void { +@_expose(wasm, "bjs_Networking_API_HTTPServer_deinit") +@_cdecl("bjs_Networking_API_HTTPServer_deinit") +public func _bjs_Networking_API_HTTPServer_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - Greeter.bridgeJSLiftParameter(_self).changeName(name: String.bridgeJSLiftParameter(nameBytes, nameLength)) + Unmanaged.fromOpaque(pointer).release() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_Greeter_greetWith") -@_cdecl("bjs_Greeter_greetWith") -public func _bjs_Greeter_greetWith(_ _self: UnsafeMutableRawPointer, _ greeter: UnsafeMutableRawPointer, _ customGreeting: Int32) -> Void { - #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).greetWith(greeter: Greeter.bridgeJSLiftParameter(greeter), customGreeting: _BJS_Closure_20BridgeJSRuntimeTests7GreeterC_SS.bridgeJSLift(customGreeting)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif +extension Networking.API.HTTPServer: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_Networking_API_HTTPServer_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_Networking_API_HTTPServer_wrap(Unmanaged.passRetained(self).toOpaque()) + } } -@_expose(wasm, "bjs_Greeter_makeFormatter") -@_cdecl("bjs_Greeter_makeFormatter") -public func _bjs_Greeter_makeFormatter(_ _self: UnsafeMutableRawPointer, _ suffixBytes: Int32, _ suffixLength: Int32) -> Int32 { - #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).makeFormatter(suffix: String.bridgeJSLiftParameter(suffixBytes, suffixLength)) - return JSTypedClosure(ret).bridgeJSLowerReturn() - #else +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Networking_API_HTTPServer_wrap") +fileprivate func _bjs_Networking_API_HTTPServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_Networking_API_HTTPServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") - #endif } - -@_expose(wasm, "bjs_Greeter_static_makeCreator") -@_cdecl("bjs_Greeter_static_makeCreator") -public func _bjs_Greeter_static_makeCreator(_ defaultNameBytes: Int32, _ defaultNameLength: Int32) -> Int32 { - #if arch(wasm32) - let ret = Greeter.makeCreator(defaultName: String.bridgeJSLiftParameter(defaultNameBytes, defaultNameLength)) - return JSTypedClosure(ret).bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif +#endif +@inline(never) fileprivate func _bjs_Networking_API_HTTPServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Networking_API_HTTPServer_wrap_extern(pointer) } -@_expose(wasm, "bjs_Greeter_makeCustomGreeter") -@_cdecl("bjs_Greeter_makeCustomGreeter") -public func _bjs_Greeter_makeCustomGreeter(_ _self: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs___Swift_Foundation_UUID_init") +@_cdecl("bjs___Swift_Foundation_UUID_init") +public func _bjs___Swift_Foundation_UUID_init(_ valueBytes: Int32, _ valueLength: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).makeCustomGreeter() - return JSTypedClosure(ret).bridgeJSLowerReturn() + let ret = UUID(value: String.bridgeJSLiftParameter(valueBytes, valueLength)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_Greeter_greetEnthusiastically") -@_cdecl("bjs_Greeter_greetEnthusiastically") -public func _bjs_Greeter_greetEnthusiastically(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs___Swift_Foundation_UUID_uuidString") +@_cdecl("bjs___Swift_Foundation_UUID_uuidString") +public func _bjs___Swift_Foundation_UUID_uuidString(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).greetEnthusiastically() + let ret = UUID.bridgeJSLiftParameter(_self).uuidString() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_Greeter_static_greetAnonymously") -@_cdecl("bjs_Greeter_static_greetAnonymously") -public func _bjs_Greeter_static_greetAnonymously() -> Void { +@_expose(wasm, "bjs___Swift_Foundation_UUID_static_fromValue") +@_cdecl("bjs___Swift_Foundation_UUID_static_fromValue") +public func _bjs___Swift_Foundation_UUID_static_fromValue(_ valueBytes: Int32, _ valueLength: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = Greeter.greetAnonymously() + let ret = UUID.fromValue(_: String.bridgeJSLiftParameter(valueBytes, valueLength)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_Greeter_name_get") -@_cdecl("bjs_Greeter_name_get") -public func _bjs_Greeter_name_get(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs___Swift_Foundation_UUID_static_placeholder_get") +@_cdecl("bjs___Swift_Foundation_UUID_static_placeholder_get") +public func _bjs___Swift_Foundation_UUID_static_placeholder_get() -> Void { #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).name + let ret = UUID.placeholder return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_Greeter_name_set") -@_cdecl("bjs_Greeter_name_set") -public func _bjs_Greeter_name_set(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { +@_expose(wasm, "bjs___Swift_Foundation_UUID_deinit") +@_cdecl("bjs___Swift_Foundation_UUID_deinit") +public func _bjs___Swift_Foundation_UUID_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - Greeter.bridgeJSLiftParameter(_self).name = String.bridgeJSLiftParameter(valueBytes, valueLength) + Unmanaged.fromOpaque(pointer).release() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_Greeter_prefix_get") -@_cdecl("bjs_Greeter_prefix_get") -public func _bjs_Greeter_prefix_get(_ _self: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).prefix - return ret.bridgeJSLowerReturn() - #else +extension UUID: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs___Swift_Foundation_UUID_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs___Swift_Foundation_UUID_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs___Swift_Foundation_UUID_wrap") +fileprivate func _bjs___Swift_Foundation_UUID_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs___Swift_Foundation_UUID_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func _bjs___Swift_Foundation_UUID_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs___Swift_Foundation_UUID_wrap_extern(pointer) } -@_expose(wasm, "bjs_Greeter_nameCount_get") -@_cdecl("bjs_Greeter_nameCount_get") -public func _bjs_Greeter_nameCount_get(_ _self: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_Networking_APIV2_Internal_TestServer_init") +@_cdecl("bjs_Networking_APIV2_Internal_TestServer_init") +public func _bjs_Networking_APIV2_Internal_TestServer_init() -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = Greeter.bridgeJSLiftParameter(_self).nameCount + let ret = Internal.TestServer() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_Greeter_static_defaultGreeting_get") -@_cdecl("bjs_Greeter_static_defaultGreeting_get") -public func _bjs_Greeter_static_defaultGreeting_get() -> Void { +@_expose(wasm, "bjs_Networking_APIV2_Internal_TestServer_call") +@_cdecl("bjs_Networking_APIV2_Internal_TestServer_call") +public func _bjs_Networking_APIV2_Internal_TestServer_call(_ _self: UnsafeMutableRawPointer, _ method: Int32) -> Void { #if arch(wasm32) - let ret = Greeter.defaultGreeting - return ret.bridgeJSLowerReturn() + Internal.TestServer.bridgeJSLiftParameter(_self).call(_: Internal.SupportedMethod.bridgeJSLiftParameter(method)) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_Greeter_deinit") -@_cdecl("bjs_Greeter_deinit") -public func _bjs_Greeter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_Networking_APIV2_Internal_TestServer_deinit") +@_cdecl("bjs_Networking_APIV2_Internal_TestServer_deinit") +public func _bjs_Networking_APIV2_Internal_TestServer_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() + Unmanaged.fromOpaque(pointer).release() #else fatalError("Only available on WebAssembly") #endif } -extension Greeter: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { - public var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_Greeter_wrap(Unmanaged.passRetained(self).toOpaque())))) +extension Internal.TestServer: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_Networking_APIV2_Internal_TestServer_wrap(Unmanaged.passRetained(self).toOpaque())))) } - public consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { - _bjs_Greeter_wrap(Unmanaged.passRetained(self).toOpaque()) + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_Networking_APIV2_Internal_TestServer_wrap(Unmanaged.passRetained(self).toOpaque()) } } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Greeter_wrap") -fileprivate func _bjs_Greeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Networking_APIV2_Internal_TestServer_wrap") +fileprivate func _bjs_Networking_APIV2_Internal_TestServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_Greeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_Networking_APIV2_Internal_TestServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_Greeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_Greeter_wrap_extern(pointer) +@inline(never) fileprivate func _bjs_Networking_APIV2_Internal_TestServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Networking_APIV2_Internal_TestServer_wrap_extern(pointer) } -@_expose(wasm, "bjs_Calculator_square") -@_cdecl("bjs_Calculator_square") -public func _bjs_Calculator_square(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Int32 { +@_expose(wasm, "bjs_SimplePropertyHolder_init") +@_cdecl("bjs_SimplePropertyHolder_init") +public func _bjs_SimplePropertyHolder_init(_ value: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = SimplePropertyHolder(value: Int.bridgeJSLiftParameter(value)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_SimplePropertyHolder_value_get") +@_cdecl("bjs_SimplePropertyHolder_value_get") +public func _bjs_SimplePropertyHolder_value_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = Calculator.bridgeJSLiftParameter(_self).square(value: Int.bridgeJSLiftParameter(value)) + let ret = SimplePropertyHolder.bridgeJSLiftParameter(_self).value return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_Calculator_add") -@_cdecl("bjs_Calculator_add") -public func _bjs_Calculator_add(_ _self: UnsafeMutableRawPointer, _ a: Int32, _ b: Int32) -> Int32 { +@_expose(wasm, "bjs_SimplePropertyHolder_value_set") +@_cdecl("bjs_SimplePropertyHolder_value_set") +public func _bjs_SimplePropertyHolder_value_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - let ret = Calculator.bridgeJSLiftParameter(_self).add(a: Int.bridgeJSLiftParameter(a), b: Int.bridgeJSLiftParameter(b)) - return ret.bridgeJSLowerReturn() + SimplePropertyHolder.bridgeJSLiftParameter(_self).value = Int.bridgeJSLiftParameter(value) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_Calculator_deinit") -@_cdecl("bjs_Calculator_deinit") -public func _bjs_Calculator_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_SimplePropertyHolder_deinit") +@_cdecl("bjs_SimplePropertyHolder_deinit") +public func _bjs_SimplePropertyHolder_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() + Unmanaged.fromOpaque(pointer).release() #else fatalError("Only available on WebAssembly") #endif } -extension Calculator: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { +extension SimplePropertyHolder: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_Calculator_wrap(Unmanaged.passRetained(self).toOpaque())))) + return .object(JSObject(id: UInt32(bitPattern: _bjs_SimplePropertyHolder_wrap(Unmanaged.passRetained(self).toOpaque())))) } consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { - _bjs_Calculator_wrap(Unmanaged.passRetained(self).toOpaque()) + _bjs_SimplePropertyHolder_wrap(Unmanaged.passRetained(self).toOpaque()) } } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Calculator_wrap") -fileprivate func _bjs_Calculator_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_SimplePropertyHolder_wrap") +fileprivate func _bjs_SimplePropertyHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_Calculator_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_SimplePropertyHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_Calculator_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_Calculator_wrap_extern(pointer) +@inline(never) fileprivate func _bjs_SimplePropertyHolder_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_SimplePropertyHolder_wrap_extern(pointer) } -@_expose(wasm, "bjs_InternalGreeter_deinit") -@_cdecl("bjs_InternalGreeter_deinit") -public func _bjs_InternalGreeter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_PropertyHolder_init") +@_cdecl("bjs_PropertyHolder_init") +public func _bjs_PropertyHolder_init(_ intValue: Int32, _ floatValue: Float32, _ doubleValue: Float64, _ boolValue: Int32, _ stringValueBytes: Int32, _ stringValueLength: Int32, _ jsObject: Int32, _ sibling: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() + let ret = PropertyHolder(intValue: Int.bridgeJSLiftParameter(intValue), floatValue: Float.bridgeJSLiftParameter(floatValue), doubleValue: Double.bridgeJSLiftParameter(doubleValue), boolValue: Bool.bridgeJSLiftParameter(boolValue), stringValue: String.bridgeJSLiftParameter(stringValueBytes, stringValueLength), jsObject: JSObject.bridgeJSLiftParameter(jsObject), sibling: SimplePropertyHolder.bridgeJSLiftParameter(sibling)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -extension InternalGreeter: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { - internal var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_InternalGreeter_wrap(Unmanaged.passRetained(self).toOpaque())))) - } - internal consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { - _bjs_InternalGreeter_wrap(Unmanaged.passRetained(self).toOpaque()) - } +@_expose(wasm, "bjs_PropertyHolder_getAllValues") +@_cdecl("bjs_PropertyHolder_getAllValues") +public func _bjs_PropertyHolder_getAllValues(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = PropertyHolder.bridgeJSLiftParameter(_self).getAllValues() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif } -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_InternalGreeter_wrap") -fileprivate func _bjs_InternalGreeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 -#else -fileprivate func _bjs_InternalGreeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_PropertyHolder_intValue_get") +@_cdecl("bjs_PropertyHolder_intValue_get") +public func _bjs_PropertyHolder_intValue_get(_ _self: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let ret = PropertyHolder.bridgeJSLiftParameter(_self).intValue + return ret.bridgeJSLowerReturn() + #else fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func _bjs_InternalGreeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_InternalGreeter_wrap_extern(pointer) + #endif } -@_expose(wasm, "bjs_PublicGreeter_deinit") -@_cdecl("bjs_PublicGreeter_deinit") -public func _bjs_PublicGreeter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_PropertyHolder_intValue_set") +@_cdecl("bjs_PropertyHolder_intValue_set") +public func _bjs_PropertyHolder_intValue_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() + PropertyHolder.bridgeJSLiftParameter(_self).intValue = Int.bridgeJSLiftParameter(value) #else fatalError("Only available on WebAssembly") #endif } -extension PublicGreeter: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { - public var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_PublicGreeter_wrap(Unmanaged.passRetained(self).toOpaque())))) - } - public consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { - _bjs_PublicGreeter_wrap(Unmanaged.passRetained(self).toOpaque()) - } +@_expose(wasm, "bjs_PropertyHolder_floatValue_get") +@_cdecl("bjs_PropertyHolder_floatValue_get") +public func _bjs_PropertyHolder_floatValue_get(_ _self: UnsafeMutableRawPointer) -> Float32 { + #if arch(wasm32) + let ret = PropertyHolder.bridgeJSLiftParameter(_self).floatValue + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif } -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_PublicGreeter_wrap") -fileprivate func _bjs_PublicGreeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 -#else -fileprivate func _bjs_PublicGreeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_PropertyHolder_floatValue_set") +@_cdecl("bjs_PropertyHolder_floatValue_set") +public func _bjs_PropertyHolder_floatValue_set(_ _self: UnsafeMutableRawPointer, _ value: Float32) -> Void { + #if arch(wasm32) + PropertyHolder.bridgeJSLiftParameter(_self).floatValue = Float.bridgeJSLiftParameter(value) + #else fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func _bjs_PublicGreeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_PublicGreeter_wrap_extern(pointer) + #endif } -@_expose(wasm, "bjs_PackageGreeter_deinit") -@_cdecl("bjs_PackageGreeter_deinit") -public func _bjs_PackageGreeter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_PropertyHolder_doubleValue_get") +@_cdecl("bjs_PropertyHolder_doubleValue_get") +public func _bjs_PropertyHolder_doubleValue_get(_ _self: UnsafeMutableRawPointer) -> Float64 { #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() + let ret = PropertyHolder.bridgeJSLiftParameter(_self).doubleValue + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -extension PackageGreeter: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { - package var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_PackageGreeter_wrap(Unmanaged.passRetained(self).toOpaque())))) - } - package consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { - _bjs_PackageGreeter_wrap(Unmanaged.passRetained(self).toOpaque()) - } +@_expose(wasm, "bjs_PropertyHolder_doubleValue_set") +@_cdecl("bjs_PropertyHolder_doubleValue_set") +public func _bjs_PropertyHolder_doubleValue_set(_ _self: UnsafeMutableRawPointer, _ value: Float64) -> Void { + #if arch(wasm32) + PropertyHolder.bridgeJSLiftParameter(_self).doubleValue = Double.bridgeJSLiftParameter(value) + #else + fatalError("Only available on WebAssembly") + #endif } -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_PackageGreeter_wrap") -fileprivate func _bjs_PackageGreeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 -#else -fileprivate func _bjs_PackageGreeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_PropertyHolder_boolValue_get") +@_cdecl("bjs_PropertyHolder_boolValue_get") +public func _bjs_PropertyHolder_boolValue_get(_ _self: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let ret = PropertyHolder.bridgeJSLiftParameter(_self).boolValue + return ret.bridgeJSLowerReturn() + #else fatalError("Only available on WebAssembly") + #endif } -#endif -@inline(never) fileprivate func _bjs_PackageGreeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_PackageGreeter_wrap_extern(pointer) + +@_expose(wasm, "bjs_PropertyHolder_boolValue_set") +@_cdecl("bjs_PropertyHolder_boolValue_set") +public func _bjs_PropertyHolder_boolValue_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { + #if arch(wasm32) + PropertyHolder.bridgeJSLiftParameter(_self).boolValue = Bool.bridgeJSLiftParameter(value) + #else + fatalError("Only available on WebAssembly") + #endif } -@_expose(wasm, "bjs_Utils_Converter_init") -@_cdecl("bjs_Utils_Converter_init") -public func _bjs_Utils_Converter_init() -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_PropertyHolder_stringValue_get") +@_cdecl("bjs_PropertyHolder_stringValue_get") +public func _bjs_PropertyHolder_stringValue_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = Utils.Converter() + let ret = PropertyHolder.bridgeJSLiftParameter(_self).stringValue return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_Utils_Converter_toString") -@_cdecl("bjs_Utils_Converter_toString") -public func _bjs_Utils_Converter_toString(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { +@_expose(wasm, "bjs_PropertyHolder_stringValue_set") +@_cdecl("bjs_PropertyHolder_stringValue_set") +public func _bjs_PropertyHolder_stringValue_set(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - let ret = Utils.Converter.bridgeJSLiftParameter(_self).toString(value: Int.bridgeJSLiftParameter(value)) - return ret.bridgeJSLowerReturn() + PropertyHolder.bridgeJSLiftParameter(_self).stringValue = String.bridgeJSLiftParameter(valueBytes, valueLength) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_Utils_Converter_precision_get") -@_cdecl("bjs_Utils_Converter_precision_get") -public func _bjs_Utils_Converter_precision_get(_ _self: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_PropertyHolder_readonlyInt_get") +@_cdecl("bjs_PropertyHolder_readonlyInt_get") +public func _bjs_PropertyHolder_readonlyInt_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = Utils.Converter.bridgeJSLiftParameter(_self).precision + let ret = PropertyHolder.bridgeJSLiftParameter(_self).readonlyInt return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_Utils_Converter_precision_set") -@_cdecl("bjs_Utils_Converter_precision_set") -public func _bjs_Utils_Converter_precision_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { +@_expose(wasm, "bjs_PropertyHolder_readonlyFloat_get") +@_cdecl("bjs_PropertyHolder_readonlyFloat_get") +public func _bjs_PropertyHolder_readonlyFloat_get(_ _self: UnsafeMutableRawPointer) -> Float32 { #if arch(wasm32) - Utils.Converter.bridgeJSLiftParameter(_self).precision = Int.bridgeJSLiftParameter(value) + let ret = PropertyHolder.bridgeJSLiftParameter(_self).readonlyFloat + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_Utils_Converter_deinit") -@_cdecl("bjs_Utils_Converter_deinit") -public func _bjs_Utils_Converter_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_PropertyHolder_readonlyDouble_get") +@_cdecl("bjs_PropertyHolder_readonlyDouble_get") +public func _bjs_PropertyHolder_readonlyDouble_get(_ _self: UnsafeMutableRawPointer) -> Float64 { #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() + let ret = PropertyHolder.bridgeJSLiftParameter(_self).readonlyDouble + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -extension Utils.Converter: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { - var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_Utils_Converter_wrap(Unmanaged.passRetained(self).toOpaque())))) - } - consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { - _bjs_Utils_Converter_wrap(Unmanaged.passRetained(self).toOpaque()) - } +@_expose(wasm, "bjs_PropertyHolder_readonlyBool_get") +@_cdecl("bjs_PropertyHolder_readonlyBool_get") +public func _bjs_PropertyHolder_readonlyBool_get(_ _self: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let ret = PropertyHolder.bridgeJSLiftParameter(_self).readonlyBool + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif } -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Utils_Converter_wrap") -fileprivate func _bjs_Utils_Converter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 -#else -fileprivate func _bjs_Utils_Converter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_PropertyHolder_readonlyString_get") +@_cdecl("bjs_PropertyHolder_readonlyString_get") +public func _bjs_PropertyHolder_readonlyString_get(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = PropertyHolder.bridgeJSLiftParameter(_self).readonlyString + return ret.bridgeJSLowerReturn() + #else fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func _bjs_Utils_Converter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_Utils_Converter_wrap_extern(pointer) + #endif } -@_expose(wasm, "bjs_Networking_API_HTTPServer_init") -@_cdecl("bjs_Networking_API_HTTPServer_init") -public func _bjs_Networking_API_HTTPServer_init() -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_PropertyHolder_jsObject_get") +@_cdecl("bjs_PropertyHolder_jsObject_get") +public func _bjs_PropertyHolder_jsObject_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = Networking.API.HTTPServer() + let ret = PropertyHolder.bridgeJSLiftParameter(_self).jsObject return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_Networking_API_HTTPServer_call") -@_cdecl("bjs_Networking_API_HTTPServer_call") -public func _bjs_Networking_API_HTTPServer_call(_ _self: UnsafeMutableRawPointer, _ method: Int32) -> Void { +@_expose(wasm, "bjs_PropertyHolder_jsObject_set") +@_cdecl("bjs_PropertyHolder_jsObject_set") +public func _bjs_PropertyHolder_jsObject_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - Networking.API.HTTPServer.bridgeJSLiftParameter(_self).call(_: Networking.API.Method.bridgeJSLiftParameter(method)) + PropertyHolder.bridgeJSLiftParameter(_self).jsObject = JSObject.bridgeJSLiftParameter(value) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_Networking_API_HTTPServer_deinit") -@_cdecl("bjs_Networking_API_HTTPServer_deinit") -public func _bjs_Networking_API_HTTPServer_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_PropertyHolder_sibling_get") +@_cdecl("bjs_PropertyHolder_sibling_get") +public func _bjs_PropertyHolder_sibling_get(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() + let ret = PropertyHolder.bridgeJSLiftParameter(_self).sibling + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -extension Networking.API.HTTPServer: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { - var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_Networking_API_HTTPServer_wrap(Unmanaged.passRetained(self).toOpaque())))) - } - consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { - _bjs_Networking_API_HTTPServer_wrap(Unmanaged.passRetained(self).toOpaque()) - } -} - -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Networking_API_HTTPServer_wrap") -fileprivate func _bjs_Networking_API_HTTPServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 -#else -fileprivate func _bjs_Networking_API_HTTPServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_PropertyHolder_sibling_set") +@_cdecl("bjs_PropertyHolder_sibling_set") +public func _bjs_PropertyHolder_sibling_set(_ _self: UnsafeMutableRawPointer, _ value: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + PropertyHolder.bridgeJSLiftParameter(_self).sibling = SimplePropertyHolder.bridgeJSLiftParameter(value) + #else fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func _bjs_Networking_API_HTTPServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_Networking_API_HTTPServer_wrap_extern(pointer) + #endif } -@_expose(wasm, "bjs___Swift_Foundation_UUID_init") -@_cdecl("bjs___Swift_Foundation_UUID_init") -public func _bjs___Swift_Foundation_UUID_init(_ valueBytes: Int32, _ valueLength: Int32) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_PropertyHolder_lazyValue_get") +@_cdecl("bjs_PropertyHolder_lazyValue_get") +public func _bjs_PropertyHolder_lazyValue_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = UUID(value: String.bridgeJSLiftParameter(valueBytes, valueLength)) + let ret = PropertyHolder.bridgeJSLiftParameter(_self).lazyValue return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs___Swift_Foundation_UUID_uuidString") -@_cdecl("bjs___Swift_Foundation_UUID_uuidString") -public func _bjs___Swift_Foundation_UUID_uuidString(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_PropertyHolder_lazyValue_set") +@_cdecl("bjs_PropertyHolder_lazyValue_set") +public func _bjs_PropertyHolder_lazyValue_set(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - let ret = UUID.bridgeJSLiftParameter(_self).uuidString() - return ret.bridgeJSLowerReturn() + PropertyHolder.bridgeJSLiftParameter(_self).lazyValue = String.bridgeJSLiftParameter(valueBytes, valueLength) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs___Swift_Foundation_UUID_static_fromValue") -@_cdecl("bjs___Swift_Foundation_UUID_static_fromValue") -public func _bjs___Swift_Foundation_UUID_static_fromValue(_ valueBytes: Int32, _ valueLength: Int32) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_PropertyHolder_computedReadonly_get") +@_cdecl("bjs_PropertyHolder_computedReadonly_get") +public func _bjs_PropertyHolder_computedReadonly_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = UUID.fromValue(_: String.bridgeJSLiftParameter(valueBytes, valueLength)) + let ret = PropertyHolder.bridgeJSLiftParameter(_self).computedReadonly return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs___Swift_Foundation_UUID_static_placeholder_get") -@_cdecl("bjs___Swift_Foundation_UUID_static_placeholder_get") -public func _bjs___Swift_Foundation_UUID_static_placeholder_get() -> Void { +@_expose(wasm, "bjs_PropertyHolder_computedReadWrite_get") +@_cdecl("bjs_PropertyHolder_computedReadWrite_get") +public func _bjs_PropertyHolder_computedReadWrite_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = UUID.placeholder + let ret = PropertyHolder.bridgeJSLiftParameter(_self).computedReadWrite return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs___Swift_Foundation_UUID_deinit") -@_cdecl("bjs___Swift_Foundation_UUID_deinit") -public func _bjs___Swift_Foundation_UUID_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_PropertyHolder_computedReadWrite_set") +@_cdecl("bjs_PropertyHolder_computedReadWrite_set") +public func _bjs_PropertyHolder_computedReadWrite_set(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() + PropertyHolder.bridgeJSLiftParameter(_self).computedReadWrite = String.bridgeJSLiftParameter(valueBytes, valueLength) #else fatalError("Only available on WebAssembly") #endif } -extension UUID: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { - var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs___Swift_Foundation_UUID_wrap(Unmanaged.passRetained(self).toOpaque())))) - } - consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { - _bjs___Swift_Foundation_UUID_wrap(Unmanaged.passRetained(self).toOpaque()) - } -} - -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs___Swift_Foundation_UUID_wrap") -fileprivate func _bjs___Swift_Foundation_UUID_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 -#else -fileprivate func _bjs___Swift_Foundation_UUID_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func _bjs___Swift_Foundation_UUID_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs___Swift_Foundation_UUID_wrap_extern(pointer) -} - -@_expose(wasm, "bjs_Networking_APIV2_Internal_TestServer_init") -@_cdecl("bjs_Networking_APIV2_Internal_TestServer_init") -public func _bjs_Networking_APIV2_Internal_TestServer_init() -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_PropertyHolder_observedProperty_get") +@_cdecl("bjs_PropertyHolder_observedProperty_get") +public func _bjs_PropertyHolder_observedProperty_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = Internal.TestServer() + let ret = PropertyHolder.bridgeJSLiftParameter(_self).observedProperty return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_Networking_APIV2_Internal_TestServer_call") -@_cdecl("bjs_Networking_APIV2_Internal_TestServer_call") -public func _bjs_Networking_APIV2_Internal_TestServer_call(_ _self: UnsafeMutableRawPointer, _ method: Int32) -> Void { +@_expose(wasm, "bjs_PropertyHolder_observedProperty_set") +@_cdecl("bjs_PropertyHolder_observedProperty_set") +public func _bjs_PropertyHolder_observedProperty_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - Internal.TestServer.bridgeJSLiftParameter(_self).call(_: Internal.SupportedMethod.bridgeJSLiftParameter(method)) + PropertyHolder.bridgeJSLiftParameter(_self).observedProperty = Int.bridgeJSLiftParameter(value) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_Networking_APIV2_Internal_TestServer_deinit") -@_cdecl("bjs_Networking_APIV2_Internal_TestServer_deinit") -public func _bjs_Networking_APIV2_Internal_TestServer_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_PropertyHolder_deinit") +@_cdecl("bjs_PropertyHolder_deinit") +public func _bjs_PropertyHolder_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() + Unmanaged.fromOpaque(pointer).release() #else fatalError("Only available on WebAssembly") #endif } -extension Internal.TestServer: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { +extension PropertyHolder: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_Networking_APIV2_Internal_TestServer_wrap(Unmanaged.passRetained(self).toOpaque())))) + return .object(JSObject(id: UInt32(bitPattern: _bjs_PropertyHolder_wrap(Unmanaged.passRetained(self).toOpaque())))) } consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { - _bjs_Networking_APIV2_Internal_TestServer_wrap(Unmanaged.passRetained(self).toOpaque()) + _bjs_PropertyHolder_wrap(Unmanaged.passRetained(self).toOpaque()) } } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Networking_APIV2_Internal_TestServer_wrap") -fileprivate func _bjs_Networking_APIV2_Internal_TestServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_PropertyHolder_wrap") +fileprivate func _bjs_PropertyHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_Networking_APIV2_Internal_TestServer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_PropertyHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_Networking_APIV2_Internal_TestServer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_Networking_APIV2_Internal_TestServer_wrap_extern(pointer) +@inline(never) fileprivate func _bjs_PropertyHolder_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_PropertyHolder_wrap_extern(pointer) } -@_expose(wasm, "bjs_SimplePropertyHolder_init") -@_cdecl("bjs_SimplePropertyHolder_init") -public func _bjs_SimplePropertyHolder_init(_ value: Int32) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_MathUtils_static_add") +@_cdecl("bjs_MathUtils_static_add") +public func _bjs_MathUtils_static_add(_ a: Int32, _ b: Int32) -> Int32 { #if arch(wasm32) - let ret = SimplePropertyHolder(value: Int.bridgeJSLiftParameter(value)) + let ret = MathUtils.add(a: Int.bridgeJSLiftParameter(a), b: Int.bridgeJSLiftParameter(b)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_SimplePropertyHolder_value_get") -@_cdecl("bjs_SimplePropertyHolder_value_get") -public func _bjs_SimplePropertyHolder_value_get(_ _self: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_MathUtils_static_substract") +@_cdecl("bjs_MathUtils_static_substract") +public func _bjs_MathUtils_static_substract(_ a: Int32, _ b: Int32) -> Int32 { #if arch(wasm32) - let ret = SimplePropertyHolder.bridgeJSLiftParameter(_self).value + let ret = MathUtils.substract(a: Int.bridgeJSLiftParameter(a), b: Int.bridgeJSLiftParameter(b)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_SimplePropertyHolder_value_set") -@_cdecl("bjs_SimplePropertyHolder_value_set") -public func _bjs_SimplePropertyHolder_value_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { - #if arch(wasm32) - SimplePropertyHolder.bridgeJSLiftParameter(_self).value = Int.bridgeJSLiftParameter(value) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_SimplePropertyHolder_deinit") -@_cdecl("bjs_SimplePropertyHolder_deinit") -public func _bjs_SimplePropertyHolder_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_MathUtils_deinit") +@_cdecl("bjs_MathUtils_deinit") +public func _bjs_MathUtils_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() + Unmanaged.fromOpaque(pointer).release() #else fatalError("Only available on WebAssembly") #endif } -extension SimplePropertyHolder: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { +extension MathUtils: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_SimplePropertyHolder_wrap(Unmanaged.passRetained(self).toOpaque())))) + return .object(JSObject(id: UInt32(bitPattern: _bjs_MathUtils_wrap(Unmanaged.passRetained(self).toOpaque())))) } consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { - _bjs_SimplePropertyHolder_wrap(Unmanaged.passRetained(self).toOpaque()) + _bjs_MathUtils_wrap(Unmanaged.passRetained(self).toOpaque()) } } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_SimplePropertyHolder_wrap") -fileprivate func _bjs_SimplePropertyHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_MathUtils_wrap") +fileprivate func _bjs_MathUtils_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_SimplePropertyHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_MathUtils_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_SimplePropertyHolder_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_SimplePropertyHolder_wrap_extern(pointer) +@inline(never) fileprivate func _bjs_MathUtils_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_MathUtils_wrap_extern(pointer) } -@_expose(wasm, "bjs_PropertyHolder_init") -@_cdecl("bjs_PropertyHolder_init") -public func _bjs_PropertyHolder_init(_ intValue: Int32, _ floatValue: Float32, _ doubleValue: Float64, _ boolValue: Int32, _ stringValueBytes: Int32, _ stringValueLength: Int32, _ jsObject: Int32, _ sibling: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_StaticPropertyHolder_init") +@_cdecl("bjs_StaticPropertyHolder_init") +public func _bjs_StaticPropertyHolder_init() -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = PropertyHolder(intValue: Int.bridgeJSLiftParameter(intValue), floatValue: Float.bridgeJSLiftParameter(floatValue), doubleValue: Double.bridgeJSLiftParameter(doubleValue), boolValue: Bool.bridgeJSLiftParameter(boolValue), stringValue: String.bridgeJSLiftParameter(stringValueBytes, stringValueLength), jsObject: JSObject.bridgeJSLiftParameter(jsObject), sibling: SimplePropertyHolder.bridgeJSLiftParameter(sibling)) + let ret = StaticPropertyHolder() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PropertyHolder_getAllValues") -@_cdecl("bjs_PropertyHolder_getAllValues") -public func _bjs_PropertyHolder_getAllValues(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_StaticPropertyHolder_static_staticConstant_get") +@_cdecl("bjs_StaticPropertyHolder_static_staticConstant_get") +public func _bjs_StaticPropertyHolder_static_staticConstant_get() -> Void { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).getAllValues() + let ret = StaticPropertyHolder.staticConstant return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PropertyHolder_intValue_get") -@_cdecl("bjs_PropertyHolder_intValue_get") -public func _bjs_PropertyHolder_intValue_get(_ _self: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_StaticPropertyHolder_static_staticVariable_get") +@_cdecl("bjs_StaticPropertyHolder_static_staticVariable_get") +public func _bjs_StaticPropertyHolder_static_staticVariable_get() -> Int32 { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).intValue + let ret = StaticPropertyHolder.staticVariable return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PropertyHolder_intValue_set") -@_cdecl("bjs_PropertyHolder_intValue_set") -public func _bjs_PropertyHolder_intValue_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { +@_expose(wasm, "bjs_StaticPropertyHolder_static_staticVariable_set") +@_cdecl("bjs_StaticPropertyHolder_static_staticVariable_set") +public func _bjs_StaticPropertyHolder_static_staticVariable_set(_ value: Int32) -> Void { #if arch(wasm32) - PropertyHolder.bridgeJSLiftParameter(_self).intValue = Int.bridgeJSLiftParameter(value) + StaticPropertyHolder.staticVariable = Int.bridgeJSLiftParameter(value) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PropertyHolder_floatValue_get") -@_cdecl("bjs_PropertyHolder_floatValue_get") -public func _bjs_PropertyHolder_floatValue_get(_ _self: UnsafeMutableRawPointer) -> Float32 { +@_expose(wasm, "bjs_StaticPropertyHolder_static_staticString_get") +@_cdecl("bjs_StaticPropertyHolder_static_staticString_get") +public func _bjs_StaticPropertyHolder_static_staticString_get() -> Void { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).floatValue + let ret = StaticPropertyHolder.staticString return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PropertyHolder_floatValue_set") -@_cdecl("bjs_PropertyHolder_floatValue_set") -public func _bjs_PropertyHolder_floatValue_set(_ _self: UnsafeMutableRawPointer, _ value: Float32) -> Void { +@_expose(wasm, "bjs_StaticPropertyHolder_static_staticString_set") +@_cdecl("bjs_StaticPropertyHolder_static_staticString_set") +public func _bjs_StaticPropertyHolder_static_staticString_set(_ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - PropertyHolder.bridgeJSLiftParameter(_self).floatValue = Float.bridgeJSLiftParameter(value) + StaticPropertyHolder.staticString = String.bridgeJSLiftParameter(valueBytes, valueLength) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PropertyHolder_doubleValue_get") -@_cdecl("bjs_PropertyHolder_doubleValue_get") -public func _bjs_PropertyHolder_doubleValue_get(_ _self: UnsafeMutableRawPointer) -> Float64 { +@_expose(wasm, "bjs_StaticPropertyHolder_static_staticBool_get") +@_cdecl("bjs_StaticPropertyHolder_static_staticBool_get") +public func _bjs_StaticPropertyHolder_static_staticBool_get() -> Int32 { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).doubleValue + let ret = StaticPropertyHolder.staticBool return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PropertyHolder_doubleValue_set") -@_cdecl("bjs_PropertyHolder_doubleValue_set") -public func _bjs_PropertyHolder_doubleValue_set(_ _self: UnsafeMutableRawPointer, _ value: Float64) -> Void { +@_expose(wasm, "bjs_StaticPropertyHolder_static_staticBool_set") +@_cdecl("bjs_StaticPropertyHolder_static_staticBool_set") +public func _bjs_StaticPropertyHolder_static_staticBool_set(_ value: Int32) -> Void { #if arch(wasm32) - PropertyHolder.bridgeJSLiftParameter(_self).doubleValue = Double.bridgeJSLiftParameter(value) + StaticPropertyHolder.staticBool = Bool.bridgeJSLiftParameter(value) #else fatalError("Only available on WebAssembly") #endif } - -@_expose(wasm, "bjs_PropertyHolder_boolValue_get") -@_cdecl("bjs_PropertyHolder_boolValue_get") -public func _bjs_PropertyHolder_boolValue_get(_ _self: UnsafeMutableRawPointer) -> Int32 { + +@_expose(wasm, "bjs_StaticPropertyHolder_static_staticFloat_get") +@_cdecl("bjs_StaticPropertyHolder_static_staticFloat_get") +public func _bjs_StaticPropertyHolder_static_staticFloat_get() -> Float32 { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).boolValue + let ret = StaticPropertyHolder.staticFloat return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PropertyHolder_boolValue_set") -@_cdecl("bjs_PropertyHolder_boolValue_set") -public func _bjs_PropertyHolder_boolValue_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { +@_expose(wasm, "bjs_StaticPropertyHolder_static_staticFloat_set") +@_cdecl("bjs_StaticPropertyHolder_static_staticFloat_set") +public func _bjs_StaticPropertyHolder_static_staticFloat_set(_ value: Float32) -> Void { #if arch(wasm32) - PropertyHolder.bridgeJSLiftParameter(_self).boolValue = Bool.bridgeJSLiftParameter(value) + StaticPropertyHolder.staticFloat = Float.bridgeJSLiftParameter(value) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PropertyHolder_stringValue_get") -@_cdecl("bjs_PropertyHolder_stringValue_get") -public func _bjs_PropertyHolder_stringValue_get(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_StaticPropertyHolder_static_staticDouble_get") +@_cdecl("bjs_StaticPropertyHolder_static_staticDouble_get") +public func _bjs_StaticPropertyHolder_static_staticDouble_get() -> Float64 { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).stringValue + let ret = StaticPropertyHolder.staticDouble return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PropertyHolder_stringValue_set") -@_cdecl("bjs_PropertyHolder_stringValue_set") -public func _bjs_PropertyHolder_stringValue_set(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { +@_expose(wasm, "bjs_StaticPropertyHolder_static_staticDouble_set") +@_cdecl("bjs_StaticPropertyHolder_static_staticDouble_set") +public func _bjs_StaticPropertyHolder_static_staticDouble_set(_ value: Float64) -> Void { #if arch(wasm32) - PropertyHolder.bridgeJSLiftParameter(_self).stringValue = String.bridgeJSLiftParameter(valueBytes, valueLength) + StaticPropertyHolder.staticDouble = Double.bridgeJSLiftParameter(value) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PropertyHolder_readonlyInt_get") -@_cdecl("bjs_PropertyHolder_readonlyInt_get") -public func _bjs_PropertyHolder_readonlyInt_get(_ _self: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_StaticPropertyHolder_static_computedProperty_get") +@_cdecl("bjs_StaticPropertyHolder_static_computedProperty_get") +public func _bjs_StaticPropertyHolder_static_computedProperty_get() -> Void { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).readonlyInt + let ret = StaticPropertyHolder.computedProperty return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PropertyHolder_readonlyFloat_get") -@_cdecl("bjs_PropertyHolder_readonlyFloat_get") -public func _bjs_PropertyHolder_readonlyFloat_get(_ _self: UnsafeMutableRawPointer) -> Float32 { +@_expose(wasm, "bjs_StaticPropertyHolder_static_computedProperty_set") +@_cdecl("bjs_StaticPropertyHolder_static_computedProperty_set") +public func _bjs_StaticPropertyHolder_static_computedProperty_set(_ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).readonlyFloat - return ret.bridgeJSLowerReturn() + StaticPropertyHolder.computedProperty = String.bridgeJSLiftParameter(valueBytes, valueLength) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PropertyHolder_readonlyDouble_get") -@_cdecl("bjs_PropertyHolder_readonlyDouble_get") -public func _bjs_PropertyHolder_readonlyDouble_get(_ _self: UnsafeMutableRawPointer) -> Float64 { +@_expose(wasm, "bjs_StaticPropertyHolder_static_readOnlyComputed_get") +@_cdecl("bjs_StaticPropertyHolder_static_readOnlyComputed_get") +public func _bjs_StaticPropertyHolder_static_readOnlyComputed_get() -> Int32 { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).readonlyDouble + let ret = StaticPropertyHolder.readOnlyComputed return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PropertyHolder_readonlyBool_get") -@_cdecl("bjs_PropertyHolder_readonlyBool_get") -public func _bjs_PropertyHolder_readonlyBool_get(_ _self: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_StaticPropertyHolder_static_optionalString_get") +@_cdecl("bjs_StaticPropertyHolder_static_optionalString_get") +public func _bjs_StaticPropertyHolder_static_optionalString_get() -> Void { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).readonlyBool + let ret = StaticPropertyHolder.optionalString return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PropertyHolder_readonlyString_get") -@_cdecl("bjs_PropertyHolder_readonlyString_get") -public func _bjs_PropertyHolder_readonlyString_get(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_StaticPropertyHolder_static_optionalString_set") +@_cdecl("bjs_StaticPropertyHolder_static_optionalString_set") +public func _bjs_StaticPropertyHolder_static_optionalString_set(_ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).readonlyString - return ret.bridgeJSLowerReturn() + StaticPropertyHolder.optionalString = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PropertyHolder_jsObject_get") -@_cdecl("bjs_PropertyHolder_jsObject_get") -public func _bjs_PropertyHolder_jsObject_get(_ _self: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_StaticPropertyHolder_static_optionalInt_get") +@_cdecl("bjs_StaticPropertyHolder_static_optionalInt_get") +public func _bjs_StaticPropertyHolder_static_optionalInt_get() -> Void { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).jsObject + let ret = StaticPropertyHolder.optionalInt return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PropertyHolder_jsObject_set") -@_cdecl("bjs_PropertyHolder_jsObject_set") -public func _bjs_PropertyHolder_jsObject_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { +@_expose(wasm, "bjs_StaticPropertyHolder_static_optionalInt_set") +@_cdecl("bjs_StaticPropertyHolder_static_optionalInt_set") +public func _bjs_StaticPropertyHolder_static_optionalInt_set(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { #if arch(wasm32) - PropertyHolder.bridgeJSLiftParameter(_self).jsObject = JSObject.bridgeJSLiftParameter(value) + StaticPropertyHolder.optionalInt = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PropertyHolder_sibling_get") -@_cdecl("bjs_PropertyHolder_sibling_get") -public func _bjs_PropertyHolder_sibling_get(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_StaticPropertyHolder_static_jsObjectProperty_get") +@_cdecl("bjs_StaticPropertyHolder_static_jsObjectProperty_get") +public func _bjs_StaticPropertyHolder_static_jsObjectProperty_get() -> Int32 { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).sibling + let ret = StaticPropertyHolder.jsObjectProperty return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PropertyHolder_sibling_set") -@_cdecl("bjs_PropertyHolder_sibling_set") -public func _bjs_PropertyHolder_sibling_set(_ _self: UnsafeMutableRawPointer, _ value: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_StaticPropertyHolder_static_jsObjectProperty_set") +@_cdecl("bjs_StaticPropertyHolder_static_jsObjectProperty_set") +public func _bjs_StaticPropertyHolder_static_jsObjectProperty_set(_ value: Int32) -> Void { #if arch(wasm32) - PropertyHolder.bridgeJSLiftParameter(_self).sibling = SimplePropertyHolder.bridgeJSLiftParameter(value) + StaticPropertyHolder.jsObjectProperty = JSObject.bridgeJSLiftParameter(value) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PropertyHolder_lazyValue_get") -@_cdecl("bjs_PropertyHolder_lazyValue_get") -public func _bjs_PropertyHolder_lazyValue_get(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_StaticPropertyHolder_deinit") +@_cdecl("bjs_StaticPropertyHolder_deinit") +public func _bjs_StaticPropertyHolder_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).lazyValue - return ret.bridgeJSLowerReturn() + Unmanaged.fromOpaque(pointer).release() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PropertyHolder_lazyValue_set") -@_cdecl("bjs_PropertyHolder_lazyValue_set") -public func _bjs_PropertyHolder_lazyValue_set(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { - #if arch(wasm32) - PropertyHolder.bridgeJSLiftParameter(_self).lazyValue = String.bridgeJSLiftParameter(valueBytes, valueLength) - #else +extension StaticPropertyHolder: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_StaticPropertyHolder_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_StaticPropertyHolder_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_StaticPropertyHolder_wrap") +fileprivate func _bjs_StaticPropertyHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_StaticPropertyHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func _bjs_StaticPropertyHolder_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_StaticPropertyHolder_wrap_extern(pointer) } -@_expose(wasm, "bjs_PropertyHolder_computedReadonly_get") -@_cdecl("bjs_PropertyHolder_computedReadonly_get") -public func _bjs_PropertyHolder_computedReadonly_get(_ _self: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_DataProcessorManager_init") +@_cdecl("bjs_DataProcessorManager_init") +public func _bjs_DataProcessorManager_init(_ processor: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).computedReadonly + let ret = DataProcessorManager(processor: AnyDataProcessor.bridgeJSLiftParameter(processor)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PropertyHolder_computedReadWrite_get") -@_cdecl("bjs_PropertyHolder_computedReadWrite_get") -public func _bjs_PropertyHolder_computedReadWrite_get(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_DataProcessorManager_incrementByAmount") +@_cdecl("bjs_DataProcessorManager_incrementByAmount") +public func _bjs_DataProcessorManager_incrementByAmount(_ _self: UnsafeMutableRawPointer, _ amount: Int32) -> Void { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).computedReadWrite - return ret.bridgeJSLowerReturn() + DataProcessorManager.bridgeJSLiftParameter(_self).incrementByAmount(_: Int.bridgeJSLiftParameter(amount)) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PropertyHolder_computedReadWrite_set") -@_cdecl("bjs_PropertyHolder_computedReadWrite_set") -public func _bjs_PropertyHolder_computedReadWrite_set(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { +@_expose(wasm, "bjs_DataProcessorManager_setProcessorLabel") +@_cdecl("bjs_DataProcessorManager_setProcessorLabel") +public func _bjs_DataProcessorManager_setProcessorLabel(_ _self: UnsafeMutableRawPointer, _ prefixBytes: Int32, _ prefixLength: Int32, _ suffixBytes: Int32, _ suffixLength: Int32) -> Void { #if arch(wasm32) - PropertyHolder.bridgeJSLiftParameter(_self).computedReadWrite = String.bridgeJSLiftParameter(valueBytes, valueLength) + DataProcessorManager.bridgeJSLiftParameter(_self).setProcessorLabel(_: String.bridgeJSLiftParameter(prefixBytes, prefixLength), _: String.bridgeJSLiftParameter(suffixBytes, suffixLength)) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PropertyHolder_observedProperty_get") -@_cdecl("bjs_PropertyHolder_observedProperty_get") -public func _bjs_PropertyHolder_observedProperty_get(_ _self: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_DataProcessorManager_isProcessorEven") +@_cdecl("bjs_DataProcessorManager_isProcessorEven") +public func _bjs_DataProcessorManager_isProcessorEven(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = PropertyHolder.bridgeJSLiftParameter(_self).observedProperty + let ret = DataProcessorManager.bridgeJSLiftParameter(_self).isProcessorEven() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PropertyHolder_observedProperty_set") -@_cdecl("bjs_PropertyHolder_observedProperty_set") -public func _bjs_PropertyHolder_observedProperty_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { +@_expose(wasm, "bjs_DataProcessorManager_getProcessorLabel") +@_cdecl("bjs_DataProcessorManager_getProcessorLabel") +public func _bjs_DataProcessorManager_getProcessorLabel(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - PropertyHolder.bridgeJSLiftParameter(_self).observedProperty = Int.bridgeJSLiftParameter(value) + let ret = DataProcessorManager.bridgeJSLiftParameter(_self).getProcessorLabel() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_PropertyHolder_deinit") -@_cdecl("bjs_PropertyHolder_deinit") -public func _bjs_PropertyHolder_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_DataProcessorManager_getCurrentValue") +@_cdecl("bjs_DataProcessorManager_getCurrentValue") +public func _bjs_DataProcessorManager_getCurrentValue(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() + let ret = DataProcessorManager.bridgeJSLiftParameter(_self).getCurrentValue() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -extension PropertyHolder: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { - var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_PropertyHolder_wrap(Unmanaged.passRetained(self).toOpaque())))) - } - consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { - _bjs_PropertyHolder_wrap(Unmanaged.passRetained(self).toOpaque()) - } -} - -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_PropertyHolder_wrap") -fileprivate func _bjs_PropertyHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 -#else -fileprivate func _bjs_PropertyHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func _bjs_PropertyHolder_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_PropertyHolder_wrap_extern(pointer) -} - -@_expose(wasm, "bjs_MathUtils_static_add") -@_cdecl("bjs_MathUtils_static_add") -public func _bjs_MathUtils_static_add(_ a: Int32, _ b: Int32) -> Int32 { +@_expose(wasm, "bjs_DataProcessorManager_incrementBoth") +@_cdecl("bjs_DataProcessorManager_incrementBoth") +public func _bjs_DataProcessorManager_incrementBoth(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = MathUtils.add(a: Int.bridgeJSLiftParameter(a), b: Int.bridgeJSLiftParameter(b)) - return ret.bridgeJSLowerReturn() + DataProcessorManager.bridgeJSLiftParameter(_self).incrementBoth() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_MathUtils_static_substract") -@_cdecl("bjs_MathUtils_static_substract") -public func _bjs_MathUtils_static_substract(_ a: Int32, _ b: Int32) -> Int32 { +@_expose(wasm, "bjs_DataProcessorManager_getBackupValue") +@_cdecl("bjs_DataProcessorManager_getBackupValue") +public func _bjs_DataProcessorManager_getBackupValue(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = MathUtils.substract(a: Int.bridgeJSLiftParameter(a), b: Int.bridgeJSLiftParameter(b)) + let ret = DataProcessorManager.bridgeJSLiftParameter(_self).getBackupValue() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_MathUtils_deinit") -@_cdecl("bjs_MathUtils_deinit") -public func _bjs_MathUtils_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_DataProcessorManager_hasBackup") +@_cdecl("bjs_DataProcessorManager_hasBackup") +public func _bjs_DataProcessorManager_hasBackup(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() + let ret = DataProcessorManager.bridgeJSLiftParameter(_self).hasBackup() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -extension MathUtils: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { - var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_MathUtils_wrap(Unmanaged.passRetained(self).toOpaque())))) - } - consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { - _bjs_MathUtils_wrap(Unmanaged.passRetained(self).toOpaque()) - } -} - -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_MathUtils_wrap") -fileprivate func _bjs_MathUtils_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 -#else -fileprivate func _bjs_MathUtils_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_DataProcessorManager_getProcessorOptionalTag") +@_cdecl("bjs_DataProcessorManager_getProcessorOptionalTag") +public func _bjs_DataProcessorManager_getProcessorOptionalTag(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = DataProcessorManager.bridgeJSLiftParameter(_self).getProcessorOptionalTag() + return ret.bridgeJSLowerReturn() + #else fatalError("Only available on WebAssembly") + #endif } -#endif -@inline(never) fileprivate func _bjs_MathUtils_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_MathUtils_wrap_extern(pointer) + +@_expose(wasm, "bjs_DataProcessorManager_setProcessorOptionalTag") +@_cdecl("bjs_DataProcessorManager_setProcessorOptionalTag") +public func _bjs_DataProcessorManager_setProcessorOptionalTag(_ _self: UnsafeMutableRawPointer, _ tagIsSome: Int32, _ tagBytes: Int32, _ tagLength: Int32) -> Void { + #if arch(wasm32) + DataProcessorManager.bridgeJSLiftParameter(_self).setProcessorOptionalTag(_: Optional.bridgeJSLiftParameter(tagIsSome, tagBytes, tagLength)) + #else + fatalError("Only available on WebAssembly") + #endif } -@_expose(wasm, "bjs_StaticPropertyHolder_init") -@_cdecl("bjs_StaticPropertyHolder_init") -public func _bjs_StaticPropertyHolder_init() -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_DataProcessorManager_getProcessorOptionalCount") +@_cdecl("bjs_DataProcessorManager_getProcessorOptionalCount") +public func _bjs_DataProcessorManager_getProcessorOptionalCount(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = StaticPropertyHolder() + let ret = DataProcessorManager.bridgeJSLiftParameter(_self).getProcessorOptionalCount() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyHolder_static_staticConstant_get") -@_cdecl("bjs_StaticPropertyHolder_static_staticConstant_get") -public func _bjs_StaticPropertyHolder_static_staticConstant_get() -> Void { +@_expose(wasm, "bjs_DataProcessorManager_setProcessorOptionalCount") +@_cdecl("bjs_DataProcessorManager_setProcessorOptionalCount") +public func _bjs_DataProcessorManager_setProcessorOptionalCount(_ _self: UnsafeMutableRawPointer, _ countIsSome: Int32, _ countValue: Int32) -> Void { #if arch(wasm32) - let ret = StaticPropertyHolder.staticConstant - return ret.bridgeJSLowerReturn() + DataProcessorManager.bridgeJSLiftParameter(_self).setProcessorOptionalCount(_: Optional.bridgeJSLiftParameter(countIsSome, countValue)) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyHolder_static_staticVariable_get") -@_cdecl("bjs_StaticPropertyHolder_static_staticVariable_get") -public func _bjs_StaticPropertyHolder_static_staticVariable_get() -> Int32 { +@_expose(wasm, "bjs_DataProcessorManager_getProcessorDirection") +@_cdecl("bjs_DataProcessorManager_getProcessorDirection") +public func _bjs_DataProcessorManager_getProcessorDirection(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = StaticPropertyHolder.staticVariable + let ret = DataProcessorManager.bridgeJSLiftParameter(_self).getProcessorDirection() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyHolder_static_staticVariable_set") -@_cdecl("bjs_StaticPropertyHolder_static_staticVariable_set") -public func _bjs_StaticPropertyHolder_static_staticVariable_set(_ value: Int32) -> Void { +@_expose(wasm, "bjs_DataProcessorManager_setProcessorDirection") +@_cdecl("bjs_DataProcessorManager_setProcessorDirection") +public func _bjs_DataProcessorManager_setProcessorDirection(_ _self: UnsafeMutableRawPointer, _ directionIsSome: Int32, _ directionValue: Int32) -> Void { #if arch(wasm32) - StaticPropertyHolder.staticVariable = Int.bridgeJSLiftParameter(value) + DataProcessorManager.bridgeJSLiftParameter(_self).setProcessorDirection(_: Optional.bridgeJSLiftParameter(directionIsSome, directionValue)) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyHolder_static_staticString_get") -@_cdecl("bjs_StaticPropertyHolder_static_staticString_get") -public func _bjs_StaticPropertyHolder_static_staticString_get() -> Void { +@_expose(wasm, "bjs_DataProcessorManager_getProcessorTheme") +@_cdecl("bjs_DataProcessorManager_getProcessorTheme") +public func _bjs_DataProcessorManager_getProcessorTheme(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = StaticPropertyHolder.staticString + let ret = DataProcessorManager.bridgeJSLiftParameter(_self).getProcessorTheme() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyHolder_static_staticString_set") -@_cdecl("bjs_StaticPropertyHolder_static_staticString_set") -public func _bjs_StaticPropertyHolder_static_staticString_set(_ valueBytes: Int32, _ valueLength: Int32) -> Void { +@_expose(wasm, "bjs_DataProcessorManager_setProcessorTheme") +@_cdecl("bjs_DataProcessorManager_setProcessorTheme") +public func _bjs_DataProcessorManager_setProcessorTheme(_ _self: UnsafeMutableRawPointer, _ themeIsSome: Int32, _ themeBytes: Int32, _ themeLength: Int32) -> Void { #if arch(wasm32) - StaticPropertyHolder.staticString = String.bridgeJSLiftParameter(valueBytes, valueLength) + DataProcessorManager.bridgeJSLiftParameter(_self).setProcessorTheme(_: Optional.bridgeJSLiftParameter(themeIsSome, themeBytes, themeLength)) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyHolder_static_staticBool_get") -@_cdecl("bjs_StaticPropertyHolder_static_staticBool_get") -public func _bjs_StaticPropertyHolder_static_staticBool_get() -> Int32 { +@_expose(wasm, "bjs_DataProcessorManager_getProcessorHttpStatus") +@_cdecl("bjs_DataProcessorManager_getProcessorHttpStatus") +public func _bjs_DataProcessorManager_getProcessorHttpStatus(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = StaticPropertyHolder.staticBool + let ret = DataProcessorManager.bridgeJSLiftParameter(_self).getProcessorHttpStatus() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyHolder_static_staticBool_set") -@_cdecl("bjs_StaticPropertyHolder_static_staticBool_set") -public func _bjs_StaticPropertyHolder_static_staticBool_set(_ value: Int32) -> Void { +@_expose(wasm, "bjs_DataProcessorManager_setProcessorHttpStatus") +@_cdecl("bjs_DataProcessorManager_setProcessorHttpStatus") +public func _bjs_DataProcessorManager_setProcessorHttpStatus(_ _self: UnsafeMutableRawPointer, _ statusIsSome: Int32, _ statusValue: Int32) -> Void { #if arch(wasm32) - StaticPropertyHolder.staticBool = Bool.bridgeJSLiftParameter(value) + DataProcessorManager.bridgeJSLiftParameter(_self).setProcessorHttpStatus(_: Optional.bridgeJSLiftParameter(statusIsSome, statusValue)) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyHolder_static_staticFloat_get") -@_cdecl("bjs_StaticPropertyHolder_static_staticFloat_get") -public func _bjs_StaticPropertyHolder_static_staticFloat_get() -> Float32 { +@_expose(wasm, "bjs_DataProcessorManager_getProcessorAPIResult") +@_cdecl("bjs_DataProcessorManager_getProcessorAPIResult") +public func _bjs_DataProcessorManager_getProcessorAPIResult(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = StaticPropertyHolder.staticFloat + let ret = DataProcessorManager.bridgeJSLiftParameter(_self).getProcessorAPIResult() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyHolder_static_staticFloat_set") -@_cdecl("bjs_StaticPropertyHolder_static_staticFloat_set") -public func _bjs_StaticPropertyHolder_static_staticFloat_set(_ value: Float32) -> Void { +@_expose(wasm, "bjs_DataProcessorManager_setProcessorAPIResult") +@_cdecl("bjs_DataProcessorManager_setProcessorAPIResult") +public func _bjs_DataProcessorManager_setProcessorAPIResult(_ _self: UnsafeMutableRawPointer, _ apiResultIsSome: Int32, _ apiResultCaseId: Int32) -> Void { #if arch(wasm32) - StaticPropertyHolder.staticFloat = Float.bridgeJSLiftParameter(value) + DataProcessorManager.bridgeJSLiftParameter(_self).setProcessorAPIResult(_: Optional.bridgeJSLiftParameter(apiResultIsSome, apiResultCaseId)) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyHolder_static_staticDouble_get") -@_cdecl("bjs_StaticPropertyHolder_static_staticDouble_get") -public func _bjs_StaticPropertyHolder_static_staticDouble_get() -> Float64 { +@_expose(wasm, "bjs_DataProcessorManager_processor_get") +@_cdecl("bjs_DataProcessorManager_processor_get") +public func _bjs_DataProcessorManager_processor_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = StaticPropertyHolder.staticDouble - return ret.bridgeJSLowerReturn() + let ret = DataProcessorManager.bridgeJSLiftParameter(_self).processor as! _BridgedSwiftProtocolExportable + return ret.bridgeJSLowerAsProtocolReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyHolder_static_staticDouble_set") -@_cdecl("bjs_StaticPropertyHolder_static_staticDouble_set") -public func _bjs_StaticPropertyHolder_static_staticDouble_set(_ value: Float64) -> Void { +@_expose(wasm, "bjs_DataProcessorManager_processor_set") +@_cdecl("bjs_DataProcessorManager_processor_set") +public func _bjs_DataProcessorManager_processor_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - StaticPropertyHolder.staticDouble = Double.bridgeJSLiftParameter(value) + DataProcessorManager.bridgeJSLiftParameter(_self).processor = AnyDataProcessor.bridgeJSLiftParameter(value) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyHolder_static_computedProperty_get") -@_cdecl("bjs_StaticPropertyHolder_static_computedProperty_get") -public func _bjs_StaticPropertyHolder_static_computedProperty_get() -> Void { +@_expose(wasm, "bjs_DataProcessorManager_backupProcessor_get") +@_cdecl("bjs_DataProcessorManager_backupProcessor_get") +public func _bjs_DataProcessorManager_backupProcessor_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = StaticPropertyHolder.computedProperty - return ret.bridgeJSLowerReturn() + let ret = DataProcessorManager.bridgeJSLiftParameter(_self).backupProcessor + if let ret { + _swift_js_return_optional_object(1, (ret as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()) + } else { + _swift_js_return_optional_object(0, 0) + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyHolder_static_computedProperty_set") -@_cdecl("bjs_StaticPropertyHolder_static_computedProperty_set") -public func _bjs_StaticPropertyHolder_static_computedProperty_set(_ valueBytes: Int32, _ valueLength: Int32) -> Void { +@_expose(wasm, "bjs_DataProcessorManager_backupProcessor_set") +@_cdecl("bjs_DataProcessorManager_backupProcessor_set") +public func _bjs_DataProcessorManager_backupProcessor_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { #if arch(wasm32) - StaticPropertyHolder.computedProperty = String.bridgeJSLiftParameter(valueBytes, valueLength) + DataProcessorManager.bridgeJSLiftParameter(_self).backupProcessor = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyHolder_static_readOnlyComputed_get") -@_cdecl("bjs_StaticPropertyHolder_static_readOnlyComputed_get") -public func _bjs_StaticPropertyHolder_static_readOnlyComputed_get() -> Int32 { +@_expose(wasm, "bjs_DataProcessorManager_deinit") +@_cdecl("bjs_DataProcessorManager_deinit") +public func _bjs_DataProcessorManager_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = StaticPropertyHolder.readOnlyComputed - return ret.bridgeJSLowerReturn() + Unmanaged.fromOpaque(pointer).release() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyHolder_static_optionalString_get") -@_cdecl("bjs_StaticPropertyHolder_static_optionalString_get") -public func _bjs_StaticPropertyHolder_static_optionalString_get() -> Void { +extension DataProcessorManager: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_DataProcessorManager_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_DataProcessorManager_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessorManager_wrap") +fileprivate func _bjs_DataProcessorManager_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_DataProcessorManager_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_DataProcessorManager_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_DataProcessorManager_wrap_extern(pointer) +} + +@_expose(wasm, "bjs_SwiftDataProcessor_init") +@_cdecl("bjs_SwiftDataProcessor_init") +public func _bjs_SwiftDataProcessor_init() -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = StaticPropertyHolder.optionalString + let ret = SwiftDataProcessor() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyHolder_static_optionalString_set") -@_cdecl("bjs_StaticPropertyHolder_static_optionalString_set") -public func _bjs_StaticPropertyHolder_static_optionalString_set(_ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { +@_expose(wasm, "bjs_SwiftDataProcessor_increment") +@_cdecl("bjs_SwiftDataProcessor_increment") +public func _bjs_SwiftDataProcessor_increment(_ _self: UnsafeMutableRawPointer, _ amount: Int32) -> Void { #if arch(wasm32) - StaticPropertyHolder.optionalString = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) + SwiftDataProcessor.bridgeJSLiftParameter(_self).increment(by: Int.bridgeJSLiftParameter(amount)) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyHolder_static_optionalInt_get") -@_cdecl("bjs_StaticPropertyHolder_static_optionalInt_get") -public func _bjs_StaticPropertyHolder_static_optionalInt_get() -> Void { +@_expose(wasm, "bjs_SwiftDataProcessor_getValue") +@_cdecl("bjs_SwiftDataProcessor_getValue") +public func _bjs_SwiftDataProcessor_getValue(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = StaticPropertyHolder.optionalInt + let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).getValue() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyHolder_static_optionalInt_set") -@_cdecl("bjs_StaticPropertyHolder_static_optionalInt_set") -public func _bjs_StaticPropertyHolder_static_optionalInt_set(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { +@_expose(wasm, "bjs_SwiftDataProcessor_setLabelElements") +@_cdecl("bjs_SwiftDataProcessor_setLabelElements") +public func _bjs_SwiftDataProcessor_setLabelElements(_ _self: UnsafeMutableRawPointer, _ labelPrefixBytes: Int32, _ labelPrefixLength: Int32, _ labelSuffixBytes: Int32, _ labelSuffixLength: Int32) -> Void { #if arch(wasm32) - StaticPropertyHolder.optionalInt = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + SwiftDataProcessor.bridgeJSLiftParameter(_self).setLabelElements(_: String.bridgeJSLiftParameter(labelPrefixBytes, labelPrefixLength), _: String.bridgeJSLiftParameter(labelSuffixBytes, labelSuffixLength)) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyHolder_static_jsObjectProperty_get") -@_cdecl("bjs_StaticPropertyHolder_static_jsObjectProperty_get") -public func _bjs_StaticPropertyHolder_static_jsObjectProperty_get() -> Int32 { +@_expose(wasm, "bjs_SwiftDataProcessor_getLabel") +@_cdecl("bjs_SwiftDataProcessor_getLabel") +public func _bjs_SwiftDataProcessor_getLabel(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = StaticPropertyHolder.jsObjectProperty + let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).getLabel() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyHolder_static_jsObjectProperty_set") -@_cdecl("bjs_StaticPropertyHolder_static_jsObjectProperty_set") -public func _bjs_StaticPropertyHolder_static_jsObjectProperty_set(_ value: Int32) -> Void { +@_expose(wasm, "bjs_SwiftDataProcessor_isEven") +@_cdecl("bjs_SwiftDataProcessor_isEven") +public func _bjs_SwiftDataProcessor_isEven(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - StaticPropertyHolder.jsObjectProperty = JSObject.bridgeJSLiftParameter(value) + let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).isEven() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_StaticPropertyHolder_deinit") -@_cdecl("bjs_StaticPropertyHolder_deinit") -public func _bjs_StaticPropertyHolder_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_SwiftDataProcessor_processGreeter") +@_cdecl("bjs_SwiftDataProcessor_processGreeter") +public func _bjs_SwiftDataProcessor_processGreeter(_ _self: UnsafeMutableRawPointer, _ greeter: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() + let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).processGreeter(_: Greeter.bridgeJSLiftParameter(greeter)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -extension StaticPropertyHolder: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { - var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_StaticPropertyHolder_wrap(Unmanaged.passRetained(self).toOpaque())))) - } - consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { - _bjs_StaticPropertyHolder_wrap(Unmanaged.passRetained(self).toOpaque()) - } +@_expose(wasm, "bjs_SwiftDataProcessor_createGreeter") +@_cdecl("bjs_SwiftDataProcessor_createGreeter") +public func _bjs_SwiftDataProcessor_createGreeter(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).createGreeter() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif } -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_StaticPropertyHolder_wrap") -fileprivate func _bjs_StaticPropertyHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 -#else -fileprivate func _bjs_StaticPropertyHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_SwiftDataProcessor_processOptionalGreeter") +@_cdecl("bjs_SwiftDataProcessor_processOptionalGreeter") +public func _bjs_SwiftDataProcessor_processOptionalGreeter(_ _self: UnsafeMutableRawPointer, _ greeterIsSome: Int32, _ greeterValue: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).processOptionalGreeter(_: Optional.bridgeJSLiftParameter(greeterIsSome, greeterValue)) + return ret.bridgeJSLowerReturn() + #else fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func _bjs_StaticPropertyHolder_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_StaticPropertyHolder_wrap_extern(pointer) + #endif } -@_expose(wasm, "bjs_DataProcessorManager_init") -@_cdecl("bjs_DataProcessorManager_init") -public func _bjs_DataProcessorManager_init(_ processor: Int32) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_SwiftDataProcessor_createOptionalGreeter") +@_cdecl("bjs_SwiftDataProcessor_createOptionalGreeter") +public func _bjs_SwiftDataProcessor_createOptionalGreeter(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = DataProcessorManager(processor: AnyDataProcessor.bridgeJSLiftParameter(processor)) + let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).createOptionalGreeter() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DataProcessorManager_incrementByAmount") -@_cdecl("bjs_DataProcessorManager_incrementByAmount") -public func _bjs_DataProcessorManager_incrementByAmount(_ _self: UnsafeMutableRawPointer, _ amount: Int32) -> Void { +@_expose(wasm, "bjs_SwiftDataProcessor_handleAPIResult") +@_cdecl("bjs_SwiftDataProcessor_handleAPIResult") +public func _bjs_SwiftDataProcessor_handleAPIResult(_ _self: UnsafeMutableRawPointer, _ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { #if arch(wasm32) - DataProcessorManager.bridgeJSLiftParameter(_self).incrementByAmount(_: Int.bridgeJSLiftParameter(amount)) + SwiftDataProcessor.bridgeJSLiftParameter(_self).handleAPIResult(_: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DataProcessorManager_setProcessorLabel") -@_cdecl("bjs_DataProcessorManager_setProcessorLabel") -public func _bjs_DataProcessorManager_setProcessorLabel(_ _self: UnsafeMutableRawPointer, _ prefixBytes: Int32, _ prefixLength: Int32, _ suffixBytes: Int32, _ suffixLength: Int32) -> Void { +@_expose(wasm, "bjs_SwiftDataProcessor_getAPIResult") +@_cdecl("bjs_SwiftDataProcessor_getAPIResult") +public func _bjs_SwiftDataProcessor_getAPIResult(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - DataProcessorManager.bridgeJSLiftParameter(_self).setProcessorLabel(_: String.bridgeJSLiftParameter(prefixBytes, prefixLength), _: String.bridgeJSLiftParameter(suffixBytes, suffixLength)) + let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).getAPIResult() + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DataProcessorManager_isProcessorEven") -@_cdecl("bjs_DataProcessorManager_isProcessorEven") -public func _bjs_DataProcessorManager_isProcessorEven(_ _self: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_SwiftDataProcessor_count_get") +@_cdecl("bjs_SwiftDataProcessor_count_get") +public func _bjs_SwiftDataProcessor_count_get(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = DataProcessorManager.bridgeJSLiftParameter(_self).isProcessorEven() + let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).count return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DataProcessorManager_getProcessorLabel") -@_cdecl("bjs_DataProcessorManager_getProcessorLabel") -public func _bjs_DataProcessorManager_getProcessorLabel(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_SwiftDataProcessor_count_set") +@_cdecl("bjs_SwiftDataProcessor_count_set") +public func _bjs_SwiftDataProcessor_count_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { #if arch(wasm32) - let ret = DataProcessorManager.bridgeJSLiftParameter(_self).getProcessorLabel() + SwiftDataProcessor.bridgeJSLiftParameter(_self).count = Int.bridgeJSLiftParameter(value) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_SwiftDataProcessor_name_get") +@_cdecl("bjs_SwiftDataProcessor_name_get") +public func _bjs_SwiftDataProcessor_name_get(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).name return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DataProcessorManager_getCurrentValue") -@_cdecl("bjs_DataProcessorManager_getCurrentValue") -public func _bjs_DataProcessorManager_getCurrentValue(_ _self: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_SwiftDataProcessor_optionalTag_get") +@_cdecl("bjs_SwiftDataProcessor_optionalTag_get") +public func _bjs_SwiftDataProcessor_optionalTag_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = DataProcessorManager.bridgeJSLiftParameter(_self).getCurrentValue() + let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).optionalTag return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DataProcessorManager_incrementBoth") -@_cdecl("bjs_DataProcessorManager_incrementBoth") -public func _bjs_DataProcessorManager_incrementBoth(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_SwiftDataProcessor_optionalTag_set") +@_cdecl("bjs_SwiftDataProcessor_optionalTag_set") +public func _bjs_SwiftDataProcessor_optionalTag_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - DataProcessorManager.bridgeJSLiftParameter(_self).incrementBoth() + SwiftDataProcessor.bridgeJSLiftParameter(_self).optionalTag = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DataProcessorManager_getBackupValue") -@_cdecl("bjs_DataProcessorManager_getBackupValue") -public func _bjs_DataProcessorManager_getBackupValue(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_SwiftDataProcessor_optionalCount_get") +@_cdecl("bjs_SwiftDataProcessor_optionalCount_get") +public func _bjs_SwiftDataProcessor_optionalCount_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = DataProcessorManager.bridgeJSLiftParameter(_self).getBackupValue() + let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).optionalCount return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DataProcessorManager_hasBackup") -@_cdecl("bjs_DataProcessorManager_hasBackup") -public func _bjs_DataProcessorManager_hasBackup(_ _self: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_SwiftDataProcessor_optionalCount_set") +@_cdecl("bjs_SwiftDataProcessor_optionalCount_set") +public func _bjs_SwiftDataProcessor_optionalCount_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { #if arch(wasm32) - let ret = DataProcessorManager.bridgeJSLiftParameter(_self).hasBackup() - return ret.bridgeJSLowerReturn() + SwiftDataProcessor.bridgeJSLiftParameter(_self).optionalCount = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DataProcessorManager_getProcessorOptionalTag") -@_cdecl("bjs_DataProcessorManager_getProcessorOptionalTag") -public func _bjs_DataProcessorManager_getProcessorOptionalTag(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_SwiftDataProcessor_direction_get") +@_cdecl("bjs_SwiftDataProcessor_direction_get") +public func _bjs_SwiftDataProcessor_direction_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = DataProcessorManager.bridgeJSLiftParameter(_self).getProcessorOptionalTag() + let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).direction return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DataProcessorManager_setProcessorOptionalTag") -@_cdecl("bjs_DataProcessorManager_setProcessorOptionalTag") -public func _bjs_DataProcessorManager_setProcessorOptionalTag(_ _self: UnsafeMutableRawPointer, _ tagIsSome: Int32, _ tagBytes: Int32, _ tagLength: Int32) -> Void { +@_expose(wasm, "bjs_SwiftDataProcessor_direction_set") +@_cdecl("bjs_SwiftDataProcessor_direction_set") +public func _bjs_SwiftDataProcessor_direction_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { #if arch(wasm32) - DataProcessorManager.bridgeJSLiftParameter(_self).setProcessorOptionalTag(_: Optional.bridgeJSLiftParameter(tagIsSome, tagBytes, tagLength)) + SwiftDataProcessor.bridgeJSLiftParameter(_self).direction = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DataProcessorManager_getProcessorOptionalCount") -@_cdecl("bjs_DataProcessorManager_getProcessorOptionalCount") -public func _bjs_DataProcessorManager_getProcessorOptionalCount(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_SwiftDataProcessor_optionalTheme_get") +@_cdecl("bjs_SwiftDataProcessor_optionalTheme_get") +public func _bjs_SwiftDataProcessor_optionalTheme_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = DataProcessorManager.bridgeJSLiftParameter(_self).getProcessorOptionalCount() + let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).optionalTheme return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DataProcessorManager_setProcessorOptionalCount") -@_cdecl("bjs_DataProcessorManager_setProcessorOptionalCount") -public func _bjs_DataProcessorManager_setProcessorOptionalCount(_ _self: UnsafeMutableRawPointer, _ countIsSome: Int32, _ countValue: Int32) -> Void { +@_expose(wasm, "bjs_SwiftDataProcessor_optionalTheme_set") +@_cdecl("bjs_SwiftDataProcessor_optionalTheme_set") +public func _bjs_SwiftDataProcessor_optionalTheme_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - DataProcessorManager.bridgeJSLiftParameter(_self).setProcessorOptionalCount(_: Optional.bridgeJSLiftParameter(countIsSome, countValue)) + SwiftDataProcessor.bridgeJSLiftParameter(_self).optionalTheme = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DataProcessorManager_getProcessorDirection") -@_cdecl("bjs_DataProcessorManager_getProcessorDirection") -public func _bjs_DataProcessorManager_getProcessorDirection(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_SwiftDataProcessor_httpStatus_get") +@_cdecl("bjs_SwiftDataProcessor_httpStatus_get") +public func _bjs_SwiftDataProcessor_httpStatus_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = DataProcessorManager.bridgeJSLiftParameter(_self).getProcessorDirection() + let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).httpStatus return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DataProcessorManager_setProcessorDirection") -@_cdecl("bjs_DataProcessorManager_setProcessorDirection") -public func _bjs_DataProcessorManager_setProcessorDirection(_ _self: UnsafeMutableRawPointer, _ directionIsSome: Int32, _ directionValue: Int32) -> Void { +@_expose(wasm, "bjs_SwiftDataProcessor_httpStatus_set") +@_cdecl("bjs_SwiftDataProcessor_httpStatus_set") +public func _bjs_SwiftDataProcessor_httpStatus_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { #if arch(wasm32) - DataProcessorManager.bridgeJSLiftParameter(_self).setProcessorDirection(_: Optional.bridgeJSLiftParameter(directionIsSome, directionValue)) + SwiftDataProcessor.bridgeJSLiftParameter(_self).httpStatus = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DataProcessorManager_getProcessorTheme") -@_cdecl("bjs_DataProcessorManager_getProcessorTheme") -public func _bjs_DataProcessorManager_getProcessorTheme(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_SwiftDataProcessor_apiResult_get") +@_cdecl("bjs_SwiftDataProcessor_apiResult_get") +public func _bjs_SwiftDataProcessor_apiResult_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = DataProcessorManager.bridgeJSLiftParameter(_self).getProcessorTheme() + let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).apiResult return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DataProcessorManager_setProcessorTheme") -@_cdecl("bjs_DataProcessorManager_setProcessorTheme") -public func _bjs_DataProcessorManager_setProcessorTheme(_ _self: UnsafeMutableRawPointer, _ themeIsSome: Int32, _ themeBytes: Int32, _ themeLength: Int32) -> Void { +@_expose(wasm, "bjs_SwiftDataProcessor_apiResult_set") +@_cdecl("bjs_SwiftDataProcessor_apiResult_set") +public func _bjs_SwiftDataProcessor_apiResult_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueCaseId: Int32) -> Void { #if arch(wasm32) - DataProcessorManager.bridgeJSLiftParameter(_self).setProcessorTheme(_: Optional.bridgeJSLiftParameter(themeIsSome, themeBytes, themeLength)) + SwiftDataProcessor.bridgeJSLiftParameter(_self).apiResult = Optional.bridgeJSLiftParameter(valueIsSome, valueCaseId) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DataProcessorManager_getProcessorHttpStatus") -@_cdecl("bjs_DataProcessorManager_getProcessorHttpStatus") -public func _bjs_DataProcessorManager_getProcessorHttpStatus(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_SwiftDataProcessor_helper_get") +@_cdecl("bjs_SwiftDataProcessor_helper_get") +public func _bjs_SwiftDataProcessor_helper_get(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = DataProcessorManager.bridgeJSLiftParameter(_self).getProcessorHttpStatus() + let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).helper return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DataProcessorManager_setProcessorHttpStatus") -@_cdecl("bjs_DataProcessorManager_setProcessorHttpStatus") -public func _bjs_DataProcessorManager_setProcessorHttpStatus(_ _self: UnsafeMutableRawPointer, _ statusIsSome: Int32, _ statusValue: Int32) -> Void { +@_expose(wasm, "bjs_SwiftDataProcessor_helper_set") +@_cdecl("bjs_SwiftDataProcessor_helper_set") +public func _bjs_SwiftDataProcessor_helper_set(_ _self: UnsafeMutableRawPointer, _ value: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - DataProcessorManager.bridgeJSLiftParameter(_self).setProcessorHttpStatus(_: Optional.bridgeJSLiftParameter(statusIsSome, statusValue)) + SwiftDataProcessor.bridgeJSLiftParameter(_self).helper = Greeter.bridgeJSLiftParameter(value) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DataProcessorManager_getProcessorAPIResult") -@_cdecl("bjs_DataProcessorManager_getProcessorAPIResult") -public func _bjs_DataProcessorManager_getProcessorAPIResult(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_SwiftDataProcessor_optionalHelper_get") +@_cdecl("bjs_SwiftDataProcessor_optionalHelper_get") +public func _bjs_SwiftDataProcessor_optionalHelper_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = DataProcessorManager.bridgeJSLiftParameter(_self).getProcessorAPIResult() + let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).optionalHelper return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DataProcessorManager_setProcessorAPIResult") -@_cdecl("bjs_DataProcessorManager_setProcessorAPIResult") -public func _bjs_DataProcessorManager_setProcessorAPIResult(_ _self: UnsafeMutableRawPointer, _ apiResultIsSome: Int32, _ apiResultCaseId: Int32) -> Void { +@_expose(wasm, "bjs_SwiftDataProcessor_optionalHelper_set") +@_cdecl("bjs_SwiftDataProcessor_optionalHelper_set") +public func _bjs_SwiftDataProcessor_optionalHelper_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - DataProcessorManager.bridgeJSLiftParameter(_self).setProcessorAPIResult(_: Optional.bridgeJSLiftParameter(apiResultIsSome, apiResultCaseId)) + SwiftDataProcessor.bridgeJSLiftParameter(_self).optionalHelper = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DataProcessorManager_processor_get") -@_cdecl("bjs_DataProcessorManager_processor_get") -public func _bjs_DataProcessorManager_processor_get(_ _self: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_SwiftDataProcessor_deinit") +@_cdecl("bjs_SwiftDataProcessor_deinit") +public func _bjs_SwiftDataProcessor_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = DataProcessorManager.bridgeJSLiftParameter(_self).processor as! _BridgedSwiftProtocolExportable + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension SwiftDataProcessor: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_SwiftDataProcessor_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_SwiftDataProcessor_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_SwiftDataProcessor_wrap") +fileprivate func _bjs_SwiftDataProcessor_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_SwiftDataProcessor_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_SwiftDataProcessor_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_SwiftDataProcessor_wrap_extern(pointer) +} + +@_expose(wasm, "bjs_ProtocolReturnTests_static_createNativeProcessor") +@_cdecl("bjs_ProtocolReturnTests_static_createNativeProcessor") +public func _bjs_ProtocolReturnTests_static_createNativeProcessor() -> Int32 { + #if arch(wasm32) + let ret = ProtocolReturnTests.createNativeProcessor() as! _BridgedSwiftProtocolExportable return ret.bridgeJSLowerAsProtocolReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DataProcessorManager_processor_set") -@_cdecl("bjs_DataProcessorManager_processor_set") -public func _bjs_DataProcessorManager_processor_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { +@_expose(wasm, "bjs_ProtocolReturnTests_static_createNativeProcessorOptional") +@_cdecl("bjs_ProtocolReturnTests_static_createNativeProcessorOptional") +public func _bjs_ProtocolReturnTests_static_createNativeProcessorOptional() -> Void { #if arch(wasm32) - DataProcessorManager.bridgeJSLiftParameter(_self).processor = AnyDataProcessor.bridgeJSLiftParameter(value) + let ret = ProtocolReturnTests.createNativeProcessorOptional() + if let ret { + _swift_js_return_optional_object(1, (ret as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()) + } else { + _swift_js_return_optional_object(0, 0) + } #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DataProcessorManager_backupProcessor_get") -@_cdecl("bjs_DataProcessorManager_backupProcessor_get") -public func _bjs_DataProcessorManager_backupProcessor_get(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_ProtocolReturnTests_static_createNativeProcessorNil") +@_cdecl("bjs_ProtocolReturnTests_static_createNativeProcessorNil") +public func _bjs_ProtocolReturnTests_static_createNativeProcessorNil() -> Void { #if arch(wasm32) - let ret = DataProcessorManager.bridgeJSLiftParameter(_self).backupProcessor + let ret = ProtocolReturnTests.createNativeProcessorNil() if let ret { _swift_js_return_optional_object(1, (ret as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()) } else { @@ -10870,1153 +12494,1302 @@ public func _bjs_DataProcessorManager_backupProcessor_get(_ _self: UnsafeMutable #endif } -@_expose(wasm, "bjs_DataProcessorManager_backupProcessor_set") -@_cdecl("bjs_DataProcessorManager_backupProcessor_set") -public func _bjs_DataProcessorManager_backupProcessor_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { +@_expose(wasm, "bjs_ProtocolReturnTests_static_createNativeProcessorArray") +@_cdecl("bjs_ProtocolReturnTests_static_createNativeProcessorArray") +public func _bjs_ProtocolReturnTests_static_createNativeProcessorArray() -> Void { + #if arch(wasm32) + let ret = ProtocolReturnTests.createNativeProcessorArray() + for __bjs_elem_ret in ret { + _swift_js_push_i32((__bjs_elem_ret as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()) + } + _swift_js_push_i32(Int32(ret.count)) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ProtocolReturnTests_static_createNativeProcessorDictionary") +@_cdecl("bjs_ProtocolReturnTests_static_createNativeProcessorDictionary") +public func _bjs_ProtocolReturnTests_static_createNativeProcessorDictionary() -> Void { #if arch(wasm32) - DataProcessorManager.bridgeJSLiftParameter(_self).backupProcessor = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let ret = ProtocolReturnTests.createNativeProcessorDictionary() + for __bjs_kv_ret in ret { + __bjs_kv_ret.key.bridgeJSStackPush() + _swift_js_push_i32((__bjs_kv_ret.value as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()) + } + _swift_js_push_i32(Int32(ret.count)) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_DataProcessorManager_deinit") -@_cdecl("bjs_DataProcessorManager_deinit") -public func _bjs_DataProcessorManager_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_ProtocolReturnTests_deinit") +@_cdecl("bjs_ProtocolReturnTests_deinit") +public func _bjs_ProtocolReturnTests_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() + Unmanaged.fromOpaque(pointer).release() #else fatalError("Only available on WebAssembly") #endif } -extension DataProcessorManager: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { +extension ProtocolReturnTests: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_DataProcessorManager_wrap(Unmanaged.passRetained(self).toOpaque())))) + return .object(JSObject(id: UInt32(bitPattern: _bjs_ProtocolReturnTests_wrap(Unmanaged.passRetained(self).toOpaque())))) } consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { - _bjs_DataProcessorManager_wrap(Unmanaged.passRetained(self).toOpaque()) + _bjs_ProtocolReturnTests_wrap(Unmanaged.passRetained(self).toOpaque()) } } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DataProcessorManager_wrap") -fileprivate func _bjs_DataProcessorManager_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ProtocolReturnTests_wrap") +fileprivate func _bjs_ProtocolReturnTests_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_DataProcessorManager_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_ProtocolReturnTests_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_DataProcessorManager_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_DataProcessorManager_wrap_extern(pointer) +@inline(never) fileprivate func _bjs_ProtocolReturnTests_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_ProtocolReturnTests_wrap_extern(pointer) } -@_expose(wasm, "bjs_SwiftDataProcessor_init") -@_cdecl("bjs_SwiftDataProcessor_init") -public func _bjs_SwiftDataProcessor_init() -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_TextProcessor_init") +@_cdecl("bjs_TextProcessor_init") +public func _bjs_TextProcessor_init(_ transform: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = SwiftDataProcessor() + let ret = TextProcessor(transform: _BJS_Closure_20BridgeJSRuntimeTestsSS_SS.bridgeJSLift(transform)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_SwiftDataProcessor_increment") -@_cdecl("bjs_SwiftDataProcessor_increment") -public func _bjs_SwiftDataProcessor_increment(_ _self: UnsafeMutableRawPointer, _ amount: Int32) -> Void { - #if arch(wasm32) - SwiftDataProcessor.bridgeJSLiftParameter(_self).increment(by: Int.bridgeJSLiftParameter(amount)) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_SwiftDataProcessor_getValue") -@_cdecl("bjs_SwiftDataProcessor_getValue") -public func _bjs_SwiftDataProcessor_getValue(_ _self: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_TextProcessor_process") +@_cdecl("bjs_TextProcessor_process") +public func _bjs_TextProcessor_process(_ _self: UnsafeMutableRawPointer, _ textBytes: Int32, _ textLength: Int32) -> Void { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).getValue() + let ret = TextProcessor.bridgeJSLiftParameter(_self).process(_: String.bridgeJSLiftParameter(textBytes, textLength)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_SwiftDataProcessor_setLabelElements") -@_cdecl("bjs_SwiftDataProcessor_setLabelElements") -public func _bjs_SwiftDataProcessor_setLabelElements(_ _self: UnsafeMutableRawPointer, _ labelPrefixBytes: Int32, _ labelPrefixLength: Int32, _ labelSuffixBytes: Int32, _ labelSuffixLength: Int32) -> Void { - #if arch(wasm32) - SwiftDataProcessor.bridgeJSLiftParameter(_self).setLabelElements(_: String.bridgeJSLiftParameter(labelPrefixBytes, labelPrefixLength), _: String.bridgeJSLiftParameter(labelSuffixBytes, labelSuffixLength)) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_SwiftDataProcessor_getLabel") -@_cdecl("bjs_SwiftDataProcessor_getLabel") -public func _bjs_SwiftDataProcessor_getLabel(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_TextProcessor_processWithCustom") +@_cdecl("bjs_TextProcessor_processWithCustom") +public func _bjs_TextProcessor_processWithCustom(_ _self: UnsafeMutableRawPointer, _ textBytes: Int32, _ textLength: Int32, _ customTransform: Int32) -> Void { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).getLabel() + let ret = TextProcessor.bridgeJSLiftParameter(_self).processWithCustom(_: String.bridgeJSLiftParameter(textBytes, textLength), customTransform: _BJS_Closure_20BridgeJSRuntimeTestsSiSSSd_SS.bridgeJSLift(customTransform)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_SwiftDataProcessor_isEven") -@_cdecl("bjs_SwiftDataProcessor_isEven") -public func _bjs_SwiftDataProcessor_isEven(_ _self: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_TextProcessor_getTransform") +@_cdecl("bjs_TextProcessor_getTransform") +public func _bjs_TextProcessor_getTransform(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).isEven() - return ret.bridgeJSLowerReturn() + let ret = TextProcessor.bridgeJSLiftParameter(_self).getTransform() + return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_SwiftDataProcessor_processGreeter") -@_cdecl("bjs_SwiftDataProcessor_processGreeter") -public func _bjs_SwiftDataProcessor_processGreeter(_ _self: UnsafeMutableRawPointer, _ greeter: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_TextProcessor_processOptionalString") +@_cdecl("bjs_TextProcessor_processOptionalString") +public func _bjs_TextProcessor_processOptionalString(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).processGreeter(_: Greeter.bridgeJSLiftParameter(greeter)) + let ret = TextProcessor.bridgeJSLiftParameter(_self).processOptionalString(_: _BJS_Closure_20BridgeJSRuntimeTestsSqSS_SS.bridgeJSLift(callback)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_SwiftDataProcessor_createGreeter") -@_cdecl("bjs_SwiftDataProcessor_createGreeter") -public func _bjs_SwiftDataProcessor_createGreeter(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_TextProcessor_processOptionalInt") +@_cdecl("bjs_TextProcessor_processOptionalInt") +public func _bjs_TextProcessor_processOptionalInt(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).createGreeter() + let ret = TextProcessor.bridgeJSLiftParameter(_self).processOptionalInt(_: _BJS_Closure_20BridgeJSRuntimeTestsSqSi_SS.bridgeJSLift(callback)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_SwiftDataProcessor_processOptionalGreeter") -@_cdecl("bjs_SwiftDataProcessor_processOptionalGreeter") -public func _bjs_SwiftDataProcessor_processOptionalGreeter(_ _self: UnsafeMutableRawPointer, _ greeterIsSome: Int32, _ greeterValue: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_TextProcessor_processOptionalGreeter") +@_cdecl("bjs_TextProcessor_processOptionalGreeter") +public func _bjs_TextProcessor_processOptionalGreeter(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).processOptionalGreeter(_: Optional.bridgeJSLiftParameter(greeterIsSome, greeterValue)) + let ret = TextProcessor.bridgeJSLiftParameter(_self).processOptionalGreeter(_: _BJS_Closure_20BridgeJSRuntimeTestsSq7GreeterC_SS.bridgeJSLift(callback)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_SwiftDataProcessor_createOptionalGreeter") -@_cdecl("bjs_SwiftDataProcessor_createOptionalGreeter") -public func _bjs_SwiftDataProcessor_createOptionalGreeter(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_TextProcessor_makeOptionalStringFormatter") +@_cdecl("bjs_TextProcessor_makeOptionalStringFormatter") +public func _bjs_TextProcessor_makeOptionalStringFormatter(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).createOptionalGreeter() - return ret.bridgeJSLowerReturn() + let ret = TextProcessor.bridgeJSLiftParameter(_self).makeOptionalStringFormatter() + return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_SwiftDataProcessor_handleAPIResult") -@_cdecl("bjs_SwiftDataProcessor_handleAPIResult") -public func _bjs_SwiftDataProcessor_handleAPIResult(_ _self: UnsafeMutableRawPointer, _ resultIsSome: Int32, _ resultCaseId: Int32) -> Void { +@_expose(wasm, "bjs_TextProcessor_makeOptionalGreeterCreator") +@_cdecl("bjs_TextProcessor_makeOptionalGreeterCreator") +public func _bjs_TextProcessor_makeOptionalGreeterCreator(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - SwiftDataProcessor.bridgeJSLiftParameter(_self).handleAPIResult(_: Optional.bridgeJSLiftParameter(resultIsSome, resultCaseId)) + let ret = TextProcessor.bridgeJSLiftParameter(_self).makeOptionalGreeterCreator() + return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_SwiftDataProcessor_getAPIResult") -@_cdecl("bjs_SwiftDataProcessor_getAPIResult") -public func _bjs_SwiftDataProcessor_getAPIResult(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_TextProcessor_processDirection") +@_cdecl("bjs_TextProcessor_processDirection") +public func _bjs_TextProcessor_processDirection(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).getAPIResult() + let ret = TextProcessor.bridgeJSLiftParameter(_self).processDirection(_: _BJS_Closure_20BridgeJSRuntimeTests9DirectionO_SS.bridgeJSLift(callback)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_SwiftDataProcessor_count_get") -@_cdecl("bjs_SwiftDataProcessor_count_get") -public func _bjs_SwiftDataProcessor_count_get(_ _self: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_TextProcessor_processTheme") +@_cdecl("bjs_TextProcessor_processTheme") +public func _bjs_TextProcessor_processTheme(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).count + let ret = TextProcessor.bridgeJSLiftParameter(_self).processTheme(_: _BJS_Closure_20BridgeJSRuntimeTests5ThemeO_SS.bridgeJSLift(callback)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_SwiftDataProcessor_count_set") -@_cdecl("bjs_SwiftDataProcessor_count_set") -public func _bjs_SwiftDataProcessor_count_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { - #if arch(wasm32) - SwiftDataProcessor.bridgeJSLiftParameter(_self).count = Int.bridgeJSLiftParameter(value) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_SwiftDataProcessor_name_get") -@_cdecl("bjs_SwiftDataProcessor_name_get") -public func _bjs_SwiftDataProcessor_name_get(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_TextProcessor_processHttpStatus") +@_cdecl("bjs_TextProcessor_processHttpStatus") +public func _bjs_TextProcessor_processHttpStatus(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Int32 { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).name + let ret = TextProcessor.bridgeJSLiftParameter(_self).processHttpStatus(_: _BJS_Closure_20BridgeJSRuntimeTests10HttpStatusO_Si.bridgeJSLift(callback)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_SwiftDataProcessor_optionalTag_get") -@_cdecl("bjs_SwiftDataProcessor_optionalTag_get") -public func _bjs_SwiftDataProcessor_optionalTag_get(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_TextProcessor_processAPIResult") +@_cdecl("bjs_TextProcessor_processAPIResult") +public func _bjs_TextProcessor_processAPIResult(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).optionalTag + let ret = TextProcessor.bridgeJSLiftParameter(_self).processAPIResult(_: _BJS_Closure_20BridgeJSRuntimeTests9APIResultO_SS.bridgeJSLift(callback)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_SwiftDataProcessor_optionalTag_set") -@_cdecl("bjs_SwiftDataProcessor_optionalTag_set") -public func _bjs_SwiftDataProcessor_optionalTag_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { - #if arch(wasm32) - SwiftDataProcessor.bridgeJSLiftParameter(_self).optionalTag = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) - #else - fatalError("Only available on WebAssembly") - #endif -} - -@_expose(wasm, "bjs_SwiftDataProcessor_optionalCount_get") -@_cdecl("bjs_SwiftDataProcessor_optionalCount_get") -public func _bjs_SwiftDataProcessor_optionalCount_get(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_TextProcessor_makeDirectionChecker") +@_cdecl("bjs_TextProcessor_makeDirectionChecker") +public func _bjs_TextProcessor_makeDirectionChecker(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).optionalCount - return ret.bridgeJSLowerReturn() + let ret = TextProcessor.bridgeJSLiftParameter(_self).makeDirectionChecker() + return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_SwiftDataProcessor_optionalCount_set") -@_cdecl("bjs_SwiftDataProcessor_optionalCount_set") -public func _bjs_SwiftDataProcessor_optionalCount_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { +@_expose(wasm, "bjs_TextProcessor_makeThemeValidator") +@_cdecl("bjs_TextProcessor_makeThemeValidator") +public func _bjs_TextProcessor_makeThemeValidator(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - SwiftDataProcessor.bridgeJSLiftParameter(_self).optionalCount = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let ret = TextProcessor.bridgeJSLiftParameter(_self).makeThemeValidator() + return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_SwiftDataProcessor_direction_get") -@_cdecl("bjs_SwiftDataProcessor_direction_get") -public func _bjs_SwiftDataProcessor_direction_get(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_TextProcessor_makeStatusCodeExtractor") +@_cdecl("bjs_TextProcessor_makeStatusCodeExtractor") +public func _bjs_TextProcessor_makeStatusCodeExtractor(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).direction - return ret.bridgeJSLowerReturn() + let ret = TextProcessor.bridgeJSLiftParameter(_self).makeStatusCodeExtractor() + return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_SwiftDataProcessor_direction_set") -@_cdecl("bjs_SwiftDataProcessor_direction_set") -public func _bjs_SwiftDataProcessor_direction_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { +@_expose(wasm, "bjs_TextProcessor_makeAPIResultHandler") +@_cdecl("bjs_TextProcessor_makeAPIResultHandler") +public func _bjs_TextProcessor_makeAPIResultHandler(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - SwiftDataProcessor.bridgeJSLiftParameter(_self).direction = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let ret = TextProcessor.bridgeJSLiftParameter(_self).makeAPIResultHandler() + return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_SwiftDataProcessor_optionalTheme_get") -@_cdecl("bjs_SwiftDataProcessor_optionalTheme_get") -public func _bjs_SwiftDataProcessor_optionalTheme_get(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_TextProcessor_processOptionalDirection") +@_cdecl("bjs_TextProcessor_processOptionalDirection") +public func _bjs_TextProcessor_processOptionalDirection(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).optionalTheme + let ret = TextProcessor.bridgeJSLiftParameter(_self).processOptionalDirection(_: _BJS_Closure_20BridgeJSRuntimeTestsSq9DirectionO_SS.bridgeJSLift(callback)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_SwiftDataProcessor_optionalTheme_set") -@_cdecl("bjs_SwiftDataProcessor_optionalTheme_set") -public func _bjs_SwiftDataProcessor_optionalTheme_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { +@_expose(wasm, "bjs_TextProcessor_processOptionalTheme") +@_cdecl("bjs_TextProcessor_processOptionalTheme") +public func _bjs_TextProcessor_processOptionalTheme(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { #if arch(wasm32) - SwiftDataProcessor.bridgeJSLiftParameter(_self).optionalTheme = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) + let ret = TextProcessor.bridgeJSLiftParameter(_self).processOptionalTheme(_: _BJS_Closure_20BridgeJSRuntimeTestsSq5ThemeO_SS.bridgeJSLift(callback)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_SwiftDataProcessor_httpStatus_get") -@_cdecl("bjs_SwiftDataProcessor_httpStatus_get") -public func _bjs_SwiftDataProcessor_httpStatus_get(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_TextProcessor_processOptionalAPIResult") +@_cdecl("bjs_TextProcessor_processOptionalAPIResult") +public func _bjs_TextProcessor_processOptionalAPIResult(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).httpStatus + let ret = TextProcessor.bridgeJSLiftParameter(_self).processOptionalAPIResult(_: _BJS_Closure_20BridgeJSRuntimeTestsSq9APIResultO_SS.bridgeJSLift(callback)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_SwiftDataProcessor_httpStatus_set") -@_cdecl("bjs_SwiftDataProcessor_httpStatus_set") -public func _bjs_SwiftDataProcessor_httpStatus_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { +@_expose(wasm, "bjs_TextProcessor_makeOptionalDirectionFormatter") +@_cdecl("bjs_TextProcessor_makeOptionalDirectionFormatter") +public func _bjs_TextProcessor_makeOptionalDirectionFormatter(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - SwiftDataProcessor.bridgeJSLiftParameter(_self).httpStatus = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let ret = TextProcessor.bridgeJSLiftParameter(_self).makeOptionalDirectionFormatter() + return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_SwiftDataProcessor_apiResult_get") -@_cdecl("bjs_SwiftDataProcessor_apiResult_get") -public func _bjs_SwiftDataProcessor_apiResult_get(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_TextProcessor_processDataProcessor") +@_cdecl("bjs_TextProcessor_processDataProcessor") +public func _bjs_TextProcessor_processDataProcessor(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).apiResult + let ret = TextProcessor.bridgeJSLiftParameter(_self).processDataProcessor(_: _BJS_Closure_20BridgeJSRuntimeTests13DataProcessorP_SS.bridgeJSLift(callback)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_SwiftDataProcessor_apiResult_set") -@_cdecl("bjs_SwiftDataProcessor_apiResult_set") -public func _bjs_SwiftDataProcessor_apiResult_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueCaseId: Int32) -> Void { +@_expose(wasm, "bjs_TextProcessor_makeDataProcessorFactory") +@_cdecl("bjs_TextProcessor_makeDataProcessorFactory") +public func _bjs_TextProcessor_makeDataProcessorFactory(_ _self: UnsafeMutableRawPointer) -> Int32 { #if arch(wasm32) - SwiftDataProcessor.bridgeJSLiftParameter(_self).apiResult = Optional.bridgeJSLiftParameter(valueIsSome, valueCaseId) + let ret = TextProcessor.bridgeJSLiftParameter(_self).makeDataProcessorFactory() + return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_SwiftDataProcessor_helper_get") -@_cdecl("bjs_SwiftDataProcessor_helper_get") -public func _bjs_SwiftDataProcessor_helper_get(_ _self: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_TextProcessor_roundtripDataProcessor") +@_cdecl("bjs_TextProcessor_roundtripDataProcessor") +public func _bjs_TextProcessor_roundtripDataProcessor(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Int32 { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).helper - return ret.bridgeJSLowerReturn() + let ret = TextProcessor.bridgeJSLiftParameter(_self).roundtripDataProcessor(_: _BJS_Closure_20BridgeJSRuntimeTests13DataProcessorP_13DataProcessorP.bridgeJSLift(callback)) + return JSTypedClosure(ret).bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_SwiftDataProcessor_helper_set") -@_cdecl("bjs_SwiftDataProcessor_helper_set") -public func _bjs_SwiftDataProcessor_helper_set(_ _self: UnsafeMutableRawPointer, _ value: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_TextProcessor_processOptionalDataProcessor") +@_cdecl("bjs_TextProcessor_processOptionalDataProcessor") +public func _bjs_TextProcessor_processOptionalDataProcessor(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { #if arch(wasm32) - SwiftDataProcessor.bridgeJSLiftParameter(_self).helper = Greeter.bridgeJSLiftParameter(value) + let ret = TextProcessor.bridgeJSLiftParameter(_self).processOptionalDataProcessor(_: _BJS_Closure_20BridgeJSRuntimeTestsSq13DataProcessorP_SS.bridgeJSLift(callback)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_SwiftDataProcessor_optionalHelper_get") -@_cdecl("bjs_SwiftDataProcessor_optionalHelper_get") -public func _bjs_SwiftDataProcessor_optionalHelper_get(_ _self: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_TextProcessor_processVector") +@_cdecl("bjs_TextProcessor_processVector") +public func _bjs_TextProcessor_processVector(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Float64 { #if arch(wasm32) - let ret = SwiftDataProcessor.bridgeJSLiftParameter(_self).optionalHelper + let ret = TextProcessor.bridgeJSLiftParameter(_self).processVector(_: _BJS_Closure_20BridgeJSRuntimeTestsSd_8Vector2DV.bridgeJSLift(callback)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_SwiftDataProcessor_optionalHelper_set") -@_cdecl("bjs_SwiftDataProcessor_optionalHelper_set") -public func _bjs_SwiftDataProcessor_optionalHelper_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_TextProcessor_processOptionalVector") +@_cdecl("bjs_TextProcessor_processOptionalVector") +public func _bjs_TextProcessor_processOptionalVector(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { #if arch(wasm32) - SwiftDataProcessor.bridgeJSLiftParameter(_self).optionalHelper = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) + let ret = TextProcessor.bridgeJSLiftParameter(_self).processOptionalVector(_: _BJS_Closure_20BridgeJSRuntimeTestsSd_Sq8Vector2DV.bridgeJSLift(callback)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_SwiftDataProcessor_deinit") -@_cdecl("bjs_SwiftDataProcessor_deinit") -public func _bjs_SwiftDataProcessor_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_TextProcessor_deinit") +@_cdecl("bjs_TextProcessor_deinit") +public func _bjs_TextProcessor_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() + Unmanaged.fromOpaque(pointer).release() #else fatalError("Only available on WebAssembly") #endif } -extension SwiftDataProcessor: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { +extension TextProcessor: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_SwiftDataProcessor_wrap(Unmanaged.passRetained(self).toOpaque())))) + return .object(JSObject(id: UInt32(bitPattern: _bjs_TextProcessor_wrap(Unmanaged.passRetained(self).toOpaque())))) } consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { - _bjs_SwiftDataProcessor_wrap(Unmanaged.passRetained(self).toOpaque()) + _bjs_TextProcessor_wrap(Unmanaged.passRetained(self).toOpaque()) } } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_SwiftDataProcessor_wrap") -fileprivate func _bjs_SwiftDataProcessor_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_TextProcessor_wrap") +fileprivate func _bjs_TextProcessor_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_SwiftDataProcessor_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_TextProcessor_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_SwiftDataProcessor_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_SwiftDataProcessor_wrap_extern(pointer) +@inline(never) fileprivate func _bjs_TextProcessor_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_TextProcessor_wrap_extern(pointer) } -@_expose(wasm, "bjs_ProtocolReturnTests_static_createNativeProcessor") -@_cdecl("bjs_ProtocolReturnTests_static_createNativeProcessor") -public func _bjs_ProtocolReturnTests_static_createNativeProcessor() -> Int32 { +@_expose(wasm, "bjs_OptionalHolder_init") +@_cdecl("bjs_OptionalHolder_init") +public func _bjs_OptionalHolder_init(_ nullableGreeterIsSome: Int32, _ nullableGreeterValue: UnsafeMutableRawPointer, _ undefinedNumberIsSome: Int32, _ undefinedNumberValue: Float64) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = ProtocolReturnTests.createNativeProcessor() as! _BridgedSwiftProtocolExportable - return ret.bridgeJSLowerAsProtocolReturn() + let ret = OptionalHolder(nullableGreeter: Optional.bridgeJSLiftParameter(nullableGreeterIsSome, nullableGreeterValue), undefinedNumber: JSUndefinedOr.bridgeJSLiftParameter(undefinedNumberIsSome, undefinedNumberValue)) + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_ProtocolReturnTests_static_createNativeProcessorOptional") -@_cdecl("bjs_ProtocolReturnTests_static_createNativeProcessorOptional") -public func _bjs_ProtocolReturnTests_static_createNativeProcessorOptional() -> Void { +@_expose(wasm, "bjs_OptionalHolder_nullableGreeter_get") +@_cdecl("bjs_OptionalHolder_nullableGreeter_get") +public func _bjs_OptionalHolder_nullableGreeter_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ProtocolReturnTests.createNativeProcessorOptional() - if let ret { - _swift_js_return_optional_object(1, (ret as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()) - } else { - _swift_js_return_optional_object(0, 0) - } + let ret = OptionalHolder.bridgeJSLiftParameter(_self).nullableGreeter + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_ProtocolReturnTests_static_createNativeProcessorNil") -@_cdecl("bjs_ProtocolReturnTests_static_createNativeProcessorNil") -public func _bjs_ProtocolReturnTests_static_createNativeProcessorNil() -> Void { +@_expose(wasm, "bjs_OptionalHolder_nullableGreeter_set") +@_cdecl("bjs_OptionalHolder_nullableGreeter_set") +public func _bjs_OptionalHolder_nullableGreeter_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ProtocolReturnTests.createNativeProcessorNil() - if let ret { - _swift_js_return_optional_object(1, (ret as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()) - } else { - _swift_js_return_optional_object(0, 0) - } + OptionalHolder.bridgeJSLiftParameter(_self).nullableGreeter = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_ProtocolReturnTests_static_createNativeProcessorArray") -@_cdecl("bjs_ProtocolReturnTests_static_createNativeProcessorArray") -public func _bjs_ProtocolReturnTests_static_createNativeProcessorArray() -> Void { +@_expose(wasm, "bjs_OptionalHolder_undefinedNumber_get") +@_cdecl("bjs_OptionalHolder_undefinedNumber_get") +public func _bjs_OptionalHolder_undefinedNumber_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = ProtocolReturnTests.createNativeProcessorArray() - for __bjs_elem_ret in ret { - _swift_js_push_i32((__bjs_elem_ret as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()) - } - _swift_js_push_i32(Int32(ret.count)) + let ret = OptionalHolder.bridgeJSLiftParameter(_self).undefinedNumber + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_ProtocolReturnTests_static_createNativeProcessorDictionary") -@_cdecl("bjs_ProtocolReturnTests_static_createNativeProcessorDictionary") -public func _bjs_ProtocolReturnTests_static_createNativeProcessorDictionary() -> Void { +@_expose(wasm, "bjs_OptionalHolder_undefinedNumber_set") +@_cdecl("bjs_OptionalHolder_undefinedNumber_set") +public func _bjs_OptionalHolder_undefinedNumber_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: Float64) -> Void { #if arch(wasm32) - let ret = ProtocolReturnTests.createNativeProcessorDictionary() - for __bjs_kv_ret in ret { - __bjs_kv_ret.key.bridgeJSStackPush() - _swift_js_push_i32((__bjs_kv_ret.value as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()) - } - _swift_js_push_i32(Int32(ret.count)) + OptionalHolder.bridgeJSLiftParameter(_self).undefinedNumber = JSUndefinedOr.bridgeJSLiftParameter(valueIsSome, valueValue) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_ProtocolReturnTests_deinit") -@_cdecl("bjs_ProtocolReturnTests_deinit") -public func _bjs_ProtocolReturnTests_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { +@_expose(wasm, "bjs_OptionalHolder_deinit") +@_cdecl("bjs_OptionalHolder_deinit") +public func _bjs_OptionalHolder_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() + Unmanaged.fromOpaque(pointer).release() #else fatalError("Only available on WebAssembly") #endif } -extension ProtocolReturnTests: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { +extension OptionalHolder: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_ProtocolReturnTests_wrap(Unmanaged.passRetained(self).toOpaque())))) + return .object(JSObject(id: UInt32(bitPattern: _bjs_OptionalHolder_wrap(Unmanaged.passRetained(self).toOpaque())))) } consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { - _bjs_ProtocolReturnTests_wrap(Unmanaged.passRetained(self).toOpaque()) + _bjs_OptionalHolder_wrap(Unmanaged.passRetained(self).toOpaque()) } } #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ProtocolReturnTests_wrap") -fileprivate func _bjs_ProtocolReturnTests_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_OptionalHolder_wrap") +fileprivate func _bjs_OptionalHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 #else -fileprivate func _bjs_ProtocolReturnTests_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func _bjs_OptionalHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_ProtocolReturnTests_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_ProtocolReturnTests_wrap_extern(pointer) +@inline(never) fileprivate func _bjs_OptionalHolder_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_OptionalHolder_wrap_extern(pointer) } -@_expose(wasm, "bjs_TextProcessor_init") -@_cdecl("bjs_TextProcessor_init") -public func _bjs_TextProcessor_init(_ transform: Int32) -> UnsafeMutableRawPointer { +@_expose(wasm, "bjs_OptionalPropertyHolder_init") +@_cdecl("bjs_OptionalPropertyHolder_init") +public func _bjs_OptionalPropertyHolder_init(_ optionalNameIsSome: Int32, _ optionalNameBytes: Int32, _ optionalNameLength: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = TextProcessor(transform: _BJS_Closure_20BridgeJSRuntimeTestsSS_SS.bridgeJSLift(transform)) + let ret = OptionalPropertyHolder(optionalName: Optional.bridgeJSLiftParameter(optionalNameIsSome, optionalNameBytes, optionalNameLength)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_TextProcessor_process") -@_cdecl("bjs_TextProcessor_process") -public func _bjs_TextProcessor_process(_ _self: UnsafeMutableRawPointer, _ textBytes: Int32, _ textLength: Int32) -> Void { +@_expose(wasm, "bjs_OptionalPropertyHolder_optionalName_get") +@_cdecl("bjs_OptionalPropertyHolder_optionalName_get") +public func _bjs_OptionalPropertyHolder_optionalName_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).process(_: String.bridgeJSLiftParameter(textBytes, textLength)) + let ret = OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalName return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_TextProcessor_processWithCustom") -@_cdecl("bjs_TextProcessor_processWithCustom") -public func _bjs_TextProcessor_processWithCustom(_ _self: UnsafeMutableRawPointer, _ textBytes: Int32, _ textLength: Int32, _ customTransform: Int32) -> Void { +@_expose(wasm, "bjs_OptionalPropertyHolder_optionalName_set") +@_cdecl("bjs_OptionalPropertyHolder_optionalName_set") +public func _bjs_OptionalPropertyHolder_optionalName_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).processWithCustom(_: String.bridgeJSLiftParameter(textBytes, textLength), customTransform: _BJS_Closure_20BridgeJSRuntimeTestsSiSSSd_SS.bridgeJSLift(customTransform)) - return ret.bridgeJSLowerReturn() + OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalName = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_TextProcessor_getTransform") -@_cdecl("bjs_TextProcessor_getTransform") -public func _bjs_TextProcessor_getTransform(_ _self: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_OptionalPropertyHolder_optionalAge_get") +@_cdecl("bjs_OptionalPropertyHolder_optionalAge_get") +public func _bjs_OptionalPropertyHolder_optionalAge_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).getTransform() - return JSTypedClosure(ret).bridgeJSLowerReturn() + let ret = OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalAge + return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_TextProcessor_processOptionalString") -@_cdecl("bjs_TextProcessor_processOptionalString") -public func _bjs_TextProcessor_processOptionalString(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { +@_expose(wasm, "bjs_OptionalPropertyHolder_optionalAge_set") +@_cdecl("bjs_OptionalPropertyHolder_optionalAge_set") +public func _bjs_OptionalPropertyHolder_optionalAge_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).processOptionalString(_: _BJS_Closure_20BridgeJSRuntimeTestsSqSS_SS.bridgeJSLift(callback)) - return ret.bridgeJSLowerReturn() + OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalAge = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_TextProcessor_processOptionalInt") -@_cdecl("bjs_TextProcessor_processOptionalInt") -public func _bjs_TextProcessor_processOptionalInt(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { +@_expose(wasm, "bjs_OptionalPropertyHolder_optionalGreeter_get") +@_cdecl("bjs_OptionalPropertyHolder_optionalGreeter_get") +public func _bjs_OptionalPropertyHolder_optionalGreeter_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).processOptionalInt(_: _BJS_Closure_20BridgeJSRuntimeTestsSqSi_SS.bridgeJSLift(callback)) + let ret = OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalGreeter return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_TextProcessor_processOptionalGreeter") -@_cdecl("bjs_TextProcessor_processOptionalGreeter") -public func _bjs_TextProcessor_processOptionalGreeter(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { +@_expose(wasm, "bjs_OptionalPropertyHolder_optionalGreeter_set") +@_cdecl("bjs_OptionalPropertyHolder_optionalGreeter_set") +public func _bjs_OptionalPropertyHolder_optionalGreeter_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).processOptionalGreeter(_: _BJS_Closure_20BridgeJSRuntimeTestsSq7GreeterC_SS.bridgeJSLift(callback)) - return ret.bridgeJSLowerReturn() + OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalGreeter = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_TextProcessor_makeOptionalStringFormatter") -@_cdecl("bjs_TextProcessor_makeOptionalStringFormatter") -public func _bjs_TextProcessor_makeOptionalStringFormatter(_ _self: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_OptionalPropertyHolder_deinit") +@_cdecl("bjs_OptionalPropertyHolder_deinit") +public func _bjs_OptionalPropertyHolder_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).makeOptionalStringFormatter() - return JSTypedClosure(ret).bridgeJSLowerReturn() + Unmanaged.fromOpaque(pointer).release() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_TextProcessor_makeOptionalGreeterCreator") -@_cdecl("bjs_TextProcessor_makeOptionalGreeterCreator") -public func _bjs_TextProcessor_makeOptionalGreeterCreator(_ _self: UnsafeMutableRawPointer) -> Int32 { - #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).makeOptionalGreeterCreator() - return JSTypedClosure(ret).bridgeJSLowerReturn() - #else +extension OptionalPropertyHolder: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_OptionalPropertyHolder_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_OptionalPropertyHolder_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_OptionalPropertyHolder_wrap") +fileprivate func _bjs_OptionalPropertyHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_OptionalPropertyHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func _bjs_OptionalPropertyHolder_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_OptionalPropertyHolder_wrap_extern(pointer) } -@_expose(wasm, "bjs_TextProcessor_processDirection") -@_cdecl("bjs_TextProcessor_processDirection") -public func _bjs_TextProcessor_processDirection(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { +@_expose(wasm, "bjs_Container_init") +@_cdecl("bjs_Container_init") +public func _bjs_Container_init() -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).processDirection(_: _BJS_Closure_20BridgeJSRuntimeTests9DirectionO_SS.bridgeJSLift(callback)) + let _tmp_config = Optional.bridgeJSLiftParameter() + let _tmp_location = DataPoint.bridgeJSLiftParameter() + let ret = Container(location: _tmp_location, config: _tmp_config) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_TextProcessor_processTheme") -@_cdecl("bjs_TextProcessor_processTheme") -public func _bjs_TextProcessor_processTheme(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { +@_expose(wasm, "bjs_Container_location_get") +@_cdecl("bjs_Container_location_get") +public func _bjs_Container_location_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).processTheme(_: _BJS_Closure_20BridgeJSRuntimeTests5ThemeO_SS.bridgeJSLift(callback)) + let ret = Container.bridgeJSLiftParameter(_self).location return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_TextProcessor_processHttpStatus") -@_cdecl("bjs_TextProcessor_processHttpStatus") -public func _bjs_TextProcessor_processHttpStatus(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Int32 { +@_expose(wasm, "bjs_Container_location_set") +@_cdecl("bjs_Container_location_set") +public func _bjs_Container_location_set(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).processHttpStatus(_: _BJS_Closure_20BridgeJSRuntimeTests10HttpStatusO_Si.bridgeJSLift(callback)) - return ret.bridgeJSLowerReturn() + Container.bridgeJSLiftParameter(_self).location = DataPoint.bridgeJSLiftParameter() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_TextProcessor_processAPIResult") -@_cdecl("bjs_TextProcessor_processAPIResult") -public func _bjs_TextProcessor_processAPIResult(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { +@_expose(wasm, "bjs_Container_config_get") +@_cdecl("bjs_Container_config_get") +public func _bjs_Container_config_get(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).processAPIResult(_: _BJS_Closure_20BridgeJSRuntimeTests9APIResultO_SS.bridgeJSLift(callback)) + let ret = Container.bridgeJSLiftParameter(_self).config return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_TextProcessor_makeDirectionChecker") -@_cdecl("bjs_TextProcessor_makeDirectionChecker") -public func _bjs_TextProcessor_makeDirectionChecker(_ _self: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_Container_config_set") +@_cdecl("bjs_Container_config_set") +public func _bjs_Container_config_set(_ _self: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).makeDirectionChecker() - return JSTypedClosure(ret).bridgeJSLowerReturn() + Container.bridgeJSLiftParameter(_self).config = Optional.bridgeJSLiftParameter() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_TextProcessor_makeThemeValidator") -@_cdecl("bjs_TextProcessor_makeThemeValidator") -public func _bjs_TextProcessor_makeThemeValidator(_ _self: UnsafeMutableRawPointer) -> Int32 { +@_expose(wasm, "bjs_Container_deinit") +@_cdecl("bjs_Container_deinit") +public func _bjs_Container_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).makeThemeValidator() - return JSTypedClosure(ret).bridgeJSLowerReturn() + Unmanaged.fromOpaque(pointer).release() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_TextProcessor_makeStatusCodeExtractor") -@_cdecl("bjs_TextProcessor_makeStatusCodeExtractor") -public func _bjs_TextProcessor_makeStatusCodeExtractor(_ _self: UnsafeMutableRawPointer) -> Int32 { - #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).makeStatusCodeExtractor() - return JSTypedClosure(ret).bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif +extension Container: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_Container_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_Container_wrap(Unmanaged.passRetained(self).toOpaque()) + } } -@_expose(wasm, "bjs_TextProcessor_makeAPIResultHandler") -@_cdecl("bjs_TextProcessor_makeAPIResultHandler") -public func _bjs_TextProcessor_makeAPIResultHandler(_ _self: UnsafeMutableRawPointer) -> Int32 { - #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).makeAPIResultHandler() - return JSTypedClosure(ret).bridgeJSLowerReturn() - #else +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Container_wrap") +fileprivate func _bjs_Container_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_Container_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func _bjs_Container_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Container_wrap_extern(pointer) } -@_expose(wasm, "bjs_TextProcessor_processOptionalDirection") -@_cdecl("bjs_TextProcessor_processOptionalDirection") -public func _bjs_TextProcessor_processOptionalDirection(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { +@_expose(wasm, "bjs_LeakCheck_init") +@_cdecl("bjs_LeakCheck_init") +public func _bjs_LeakCheck_init() -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).processOptionalDirection(_: _BJS_Closure_20BridgeJSRuntimeTestsSq9DirectionO_SS.bridgeJSLift(callback)) + let ret = LeakCheck() return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_TextProcessor_processOptionalTheme") -@_cdecl("bjs_TextProcessor_processOptionalTheme") -public func _bjs_TextProcessor_processOptionalTheme(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { +@_expose(wasm, "bjs_LeakCheck_deinit") +@_cdecl("bjs_LeakCheck_deinit") +public func _bjs_LeakCheck_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).processOptionalTheme(_: _BJS_Closure_20BridgeJSRuntimeTestsSq5ThemeO_SS.bridgeJSLift(callback)) - return ret.bridgeJSLowerReturn() + Unmanaged.fromOpaque(pointer).release() #else fatalError("Only available on WebAssembly") #endif } -@_expose(wasm, "bjs_TextProcessor_processOptionalAPIResult") -@_cdecl("bjs_TextProcessor_processOptionalAPIResult") -public func _bjs_TextProcessor_processOptionalAPIResult(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { - #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).processOptionalAPIResult(_: _BJS_Closure_20BridgeJSRuntimeTestsSq9APIResultO_SS.bridgeJSLift(callback)) - return ret.bridgeJSLowerReturn() - #else +extension LeakCheck: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + public var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_LeakCheck_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + public consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_LeakCheck_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_LeakCheck_wrap") +fileprivate func _bjs_LeakCheck_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_LeakCheck_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func _bjs_LeakCheck_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_LeakCheck_wrap_extern(pointer) } -@_expose(wasm, "bjs_TextProcessor_makeOptionalDirectionFormatter") -@_cdecl("bjs_TextProcessor_makeOptionalDirectionFormatter") -public func _bjs_TextProcessor_makeOptionalDirectionFormatter(_ _self: UnsafeMutableRawPointer) -> Int32 { - #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).makeOptionalDirectionFormatter() - return JSTypedClosure(ret).bridgeJSLowerReturn() - #else +@JSFunction func Promise_reject(_ promise: JSObject, _ value: JSValue) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_reject_BridgeJSRuntimeTests") +fileprivate func promise_reject_BridgeJSRuntimeTests_extern(_ promise: Int32, _ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void +#else +fileprivate func promise_reject_BridgeJSRuntimeTests_extern(_ promise: Int32, _ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func promise_reject_BridgeJSRuntimeTests(_ promise: Int32, _ valueKind: Int32, _ valuePayload1: Int32, _ valuePayload2: Float64) -> Void { + return promise_reject_BridgeJSRuntimeTests_extern(promise, valueKind, valuePayload1, valuePayload2) } -@_expose(wasm, "bjs_TextProcessor_processDataProcessor") -@_cdecl("bjs_TextProcessor_processDataProcessor") -public func _bjs_TextProcessor_processDataProcessor(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { - #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).processDataProcessor(_: _BJS_Closure_20BridgeJSRuntimeTests13DataProcessorP_SS.bridgeJSLift(callback)) - return ret.bridgeJSLowerReturn() - #else +func _$Promise_reject(_ promise: JSObject, _ value: JSValue) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let (valueKind, valuePayload1, valuePayload2) = value.bridgeJSLowerParameter() + promise_reject_BridgeJSRuntimeTests(promiseValue, valueKind, valuePayload1, valuePayload2) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_SS(_ promise: JSObject, _ value: String) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_SS") +fileprivate func promise_resolve_BridgeJSRuntimeTests_SS_extern(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_SS_extern(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_SS(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_SS_extern(promise, valueBytes, valueLength) } -@_expose(wasm, "bjs_TextProcessor_makeDataProcessorFactory") -@_cdecl("bjs_TextProcessor_makeDataProcessorFactory") -public func _bjs_TextProcessor_makeDataProcessorFactory(_ _self: UnsafeMutableRawPointer) -> Int32 { - #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).makeDataProcessorFactory() - return JSTypedClosure(ret).bridgeJSLowerReturn() - #else +func _$Promise_resolve_SS(_ promise: JSObject, _ value: String) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + value.bridgeJSWithLoweredParameter { (valueBytes, valueLength) in + promise_resolve_BridgeJSRuntimeTests_SS(promiseValue, valueBytes, valueLength) + } + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_y(_ promise: JSObject) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_y") +fileprivate func promise_resolve_BridgeJSRuntimeTests_y_extern(_ promise: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_y_extern(_ promise: Int32) -> Void { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_y(_ promise: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_y_extern(promise) } -@_expose(wasm, "bjs_TextProcessor_roundtripDataProcessor") -@_cdecl("bjs_TextProcessor_roundtripDataProcessor") -public func _bjs_TextProcessor_roundtripDataProcessor(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Int32 { - #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).roundtripDataProcessor(_: _BJS_Closure_20BridgeJSRuntimeTests13DataProcessorP_13DataProcessorP.bridgeJSLift(callback)) - return JSTypedClosure(ret).bridgeJSLowerReturn() - #else +func _$Promise_resolve_y(_ promise: JSObject) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_y(promiseValue) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_Si(_ promise: JSObject, _ value: Int) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Si") +fileprivate func promise_resolve_BridgeJSRuntimeTests_Si_extern(_ promise: Int32, _ value: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_Si_extern(_ promise: Int32, _ value: Int32) -> Void { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Si(_ promise: Int32, _ value: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_Si_extern(promise, value) } -@_expose(wasm, "bjs_TextProcessor_processOptionalDataProcessor") -@_cdecl("bjs_TextProcessor_processOptionalDataProcessor") -public func _bjs_TextProcessor_processOptionalDataProcessor(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { - #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).processOptionalDataProcessor(_: _BJS_Closure_20BridgeJSRuntimeTestsSq13DataProcessorP_SS.bridgeJSLift(callback)) - return ret.bridgeJSLowerReturn() - #else +func _$Promise_resolve_Si(_ promise: JSObject, _ value: Int) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueValue = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_Si(promiseValue, valueValue) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_Sf(_ promise: JSObject, _ value: Float) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sf") +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sf_extern(_ promise: Int32, _ value: Float32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sf_extern(_ promise: Int32, _ value: Float32) -> Void { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sf(_ promise: Int32, _ value: Float32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_Sf_extern(promise, value) } -@_expose(wasm, "bjs_TextProcessor_processVector") -@_cdecl("bjs_TextProcessor_processVector") -public func _bjs_TextProcessor_processVector(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Float64 { - #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).processVector(_: _BJS_Closure_20BridgeJSRuntimeTestsSd_8Vector2DV.bridgeJSLift(callback)) - return ret.bridgeJSLowerReturn() - #else +func _$Promise_resolve_Sf(_ promise: JSObject, _ value: Float) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueValue = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_Sf(promiseValue, valueValue) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_Sd(_ promise: JSObject, _ value: Double) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sd") +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sd_extern(_ promise: Int32, _ value: Float64) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sd_extern(_ promise: Int32, _ value: Float64) -> Void { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sd(_ promise: Int32, _ value: Float64) -> Void { + return promise_resolve_BridgeJSRuntimeTests_Sd_extern(promise, value) } -@_expose(wasm, "bjs_TextProcessor_processOptionalVector") -@_cdecl("bjs_TextProcessor_processOptionalVector") -public func _bjs_TextProcessor_processOptionalVector(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { - #if arch(wasm32) - let ret = TextProcessor.bridgeJSLiftParameter(_self).processOptionalVector(_: _BJS_Closure_20BridgeJSRuntimeTestsSd_Sq8Vector2DV.bridgeJSLift(callback)) - return ret.bridgeJSLowerReturn() - #else +func _$Promise_resolve_Sd(_ promise: JSObject, _ value: Double) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueValue = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_Sd(promiseValue, valueValue) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_Sb(_ promise: JSObject, _ value: Bool) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sb") +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sb_extern(_ promise: Int32, _ value: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sb_extern(_ promise: Int32, _ value: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sb(_ promise: Int32, _ value: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_Sb_extern(promise, value) +} + +func _$Promise_resolve_Sb(_ promise: JSObject, _ value: Bool) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueValue = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_Sb(promiseValue, valueValue) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_7GreeterC(_ promise: JSObject, _ value: Greeter) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_7GreeterC") +fileprivate func promise_resolve_BridgeJSRuntimeTests_7GreeterC_extern(_ promise: Int32, _ value: UnsafeMutableRawPointer) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_7GreeterC_extern(_ promise: Int32, _ value: UnsafeMutableRawPointer) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_7GreeterC(_ promise: Int32, _ value: UnsafeMutableRawPointer) -> Void { + return promise_resolve_BridgeJSRuntimeTests_7GreeterC_extern(promise, value) +} + +func _$Promise_resolve_7GreeterC(_ promise: JSObject, _ value: Greeter) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valuePointer = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_7GreeterC(promiseValue, valuePointer) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_8JSObjectC(_ promise: JSObject, _ value: JSObject) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_8JSObjectC") +fileprivate func promise_resolve_BridgeJSRuntimeTests_8JSObjectC_extern(_ promise: Int32, _ value: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_8JSObjectC_extern(_ promise: Int32, _ value: Int32) -> Void { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_8JSObjectC(_ promise: Int32, _ value: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_8JSObjectC_extern(promise, value) } -@_expose(wasm, "bjs_TextProcessor_deinit") -@_cdecl("bjs_TextProcessor_deinit") -public func _bjs_TextProcessor_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() - #else +func _$Promise_resolve_8JSObjectC(_ promise: JSObject, _ value: JSObject) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueValue = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_8JSObjectC(promiseValue, valueValue) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_5ThemeO(_ promise: JSObject, _ value: Theme) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_5ThemeO") +fileprivate func promise_resolve_BridgeJSRuntimeTests_5ThemeO_extern(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_5ThemeO_extern(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_5ThemeO(_ promise: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_5ThemeO_extern(promise, valueBytes, valueLength) } -extension TextProcessor: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { - var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_TextProcessor_wrap(Unmanaged.passRetained(self).toOpaque())))) - } - consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { - _bjs_TextProcessor_wrap(Unmanaged.passRetained(self).toOpaque()) +func _$Promise_resolve_5ThemeO(_ promise: JSObject, _ value: Theme) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + value.bridgeJSWithLoweredParameter { (valueBytes, valueLength) in + promise_resolve_BridgeJSRuntimeTests_5ThemeO(promiseValue, valueBytes, valueLength) } + if let error = _swift_js_take_exception() { throw error } } +@JSFunction func Promise_resolve_9DirectionO(_ promise: JSObject, _ value: Direction) throws(JSException) + #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_TextProcessor_wrap") -fileprivate func _bjs_TextProcessor_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_9DirectionO") +fileprivate func promise_resolve_BridgeJSRuntimeTests_9DirectionO_extern(_ promise: Int32, _ value: Int32) -> Void #else -fileprivate func _bjs_TextProcessor_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func promise_resolve_BridgeJSRuntimeTests_9DirectionO_extern(_ promise: Int32, _ value: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_TextProcessor_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_TextProcessor_wrap_extern(pointer) +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_9DirectionO(_ promise: Int32, _ value: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_9DirectionO_extern(promise, value) } -@_expose(wasm, "bjs_OptionalHolder_init") -@_cdecl("bjs_OptionalHolder_init") -public func _bjs_OptionalHolder_init(_ nullableGreeterIsSome: Int32, _ nullableGreeterValue: UnsafeMutableRawPointer, _ undefinedNumberIsSome: Int32, _ undefinedNumberValue: Float64) -> UnsafeMutableRawPointer { - #if arch(wasm32) - let ret = OptionalHolder(nullableGreeter: Optional.bridgeJSLiftParameter(nullableGreeterIsSome, nullableGreeterValue), undefinedNumber: JSUndefinedOr.bridgeJSLiftParameter(undefinedNumberIsSome, undefinedNumberValue)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif +func _$Promise_resolve_9DirectionO(_ promise: JSObject, _ value: Direction) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueValue = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_9DirectionO(promiseValue, valueValue) + if let error = _swift_js_take_exception() { throw error } } -@_expose(wasm, "bjs_OptionalHolder_nullableGreeter_get") -@_cdecl("bjs_OptionalHolder_nullableGreeter_get") -public func _bjs_OptionalHolder_nullableGreeter_get(_ _self: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let ret = OptionalHolder.bridgeJSLiftParameter(_self).nullableGreeter - return ret.bridgeJSLowerReturn() - #else +@JSFunction func Promise_resolve_Sq5ThemeO(_ promise: JSObject, _ value: Optional) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sq5ThemeO") +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq5ThemeO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq5ThemeO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq5ThemeO(_ promise: Int32, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_Sq5ThemeO_extern(promise, valueIsSome, valueBytes, valueLength) } -@_expose(wasm, "bjs_OptionalHolder_nullableGreeter_set") -@_cdecl("bjs_OptionalHolder_nullableGreeter_set") -public func _bjs_OptionalHolder_nullableGreeter_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - OptionalHolder.bridgeJSLiftParameter(_self).nullableGreeter = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) - #else - fatalError("Only available on WebAssembly") - #endif +func _$Promise_resolve_Sq5ThemeO(_ promise: JSObject, _ value: Optional) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + value.bridgeJSWithLoweredParameter { (valueIsSome, valueBytes, valueLength) in + promise_resolve_BridgeJSRuntimeTests_Sq5ThemeO(promiseValue, valueIsSome, valueBytes, valueLength) + } + if let error = _swift_js_take_exception() { throw error } } -@_expose(wasm, "bjs_OptionalHolder_undefinedNumber_get") -@_cdecl("bjs_OptionalHolder_undefinedNumber_get") -public func _bjs_OptionalHolder_undefinedNumber_get(_ _self: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let ret = OptionalHolder.bridgeJSLiftParameter(_self).undefinedNumber - return ret.bridgeJSLowerReturn() - #else +@JSFunction func Promise_resolve_Sq9DirectionO(_ promise: JSObject, _ value: Optional) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sq9DirectionO") +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq9DirectionO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq9DirectionO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq9DirectionO(_ promise: Int32, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_Sq9DirectionO_extern(promise, valueIsSome, valueValue) } -@_expose(wasm, "bjs_OptionalHolder_undefinedNumber_set") -@_cdecl("bjs_OptionalHolder_undefinedNumber_set") -public func _bjs_OptionalHolder_undefinedNumber_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: Float64) -> Void { - #if arch(wasm32) - OptionalHolder.bridgeJSLiftParameter(_self).undefinedNumber = JSUndefinedOr.bridgeJSLiftParameter(valueIsSome, valueValue) - #else - fatalError("Only available on WebAssembly") - #endif +func _$Promise_resolve_Sq9DirectionO(_ promise: JSObject, _ value: Optional) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let (valueIsSome, valueValue) = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_Sq9DirectionO(promiseValue, valueIsSome, valueValue) + if let error = _swift_js_take_exception() { throw error } } -@_expose(wasm, "bjs_OptionalHolder_deinit") -@_cdecl("bjs_OptionalHolder_deinit") -public func _bjs_OptionalHolder_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() - #else +@JSFunction func Promise_resolve_Sa9DirectionO(_ promise: JSObject, _ value: [Direction]) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sa9DirectionO") +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sa9DirectionO_extern(_ promise: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sa9DirectionO_extern(_ promise: Int32) -> Void { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sa9DirectionO(_ promise: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_Sa9DirectionO_extern(promise) } -extension OptionalHolder: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { - var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_OptionalHolder_wrap(Unmanaged.passRetained(self).toOpaque())))) - } - consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { - _bjs_OptionalHolder_wrap(Unmanaged.passRetained(self).toOpaque()) - } +func _$Promise_resolve_Sa9DirectionO(_ promise: JSObject, _ value: [Direction]) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let _ = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_Sa9DirectionO(promiseValue) + if let error = _swift_js_take_exception() { throw error } } +@JSFunction func Promise_resolve_SD9DirectionO(_ promise: JSObject, _ value: [String: Direction]) throws(JSException) + #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_OptionalHolder_wrap") -fileprivate func _bjs_OptionalHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_SD9DirectionO") +fileprivate func promise_resolve_BridgeJSRuntimeTests_SD9DirectionO_extern(_ promise: Int32) -> Void #else -fileprivate func _bjs_OptionalHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func promise_resolve_BridgeJSRuntimeTests_SD9DirectionO_extern(_ promise: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_OptionalHolder_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_OptionalHolder_wrap_extern(pointer) +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_SD9DirectionO(_ promise: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_SD9DirectionO_extern(promise) } -@_expose(wasm, "bjs_OptionalPropertyHolder_init") -@_cdecl("bjs_OptionalPropertyHolder_init") -public func _bjs_OptionalPropertyHolder_init(_ optionalNameIsSome: Int32, _ optionalNameBytes: Int32, _ optionalNameLength: Int32) -> UnsafeMutableRawPointer { - #if arch(wasm32) - let ret = OptionalPropertyHolder(optionalName: Optional.bridgeJSLiftParameter(optionalNameIsSome, optionalNameBytes, optionalNameLength)) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif +func _$Promise_resolve_SD9DirectionO(_ promise: JSObject, _ value: [String: Direction]) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let _ = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_SD9DirectionO(promiseValue) + if let error = _swift_js_take_exception() { throw error } } -@_expose(wasm, "bjs_OptionalPropertyHolder_optionalName_get") -@_cdecl("bjs_OptionalPropertyHolder_optionalName_get") -public func _bjs_OptionalPropertyHolder_optionalName_get(_ _self: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let ret = OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalName - return ret.bridgeJSLowerReturn() - #else +@JSFunction func Promise_resolve_Sa5ThemeO(_ promise: JSObject, _ value: [Theme]) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sa5ThemeO") +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sa5ThemeO_extern(_ promise: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sa5ThemeO_extern(_ promise: Int32) -> Void { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sa5ThemeO(_ promise: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_Sa5ThemeO_extern(promise) } -@_expose(wasm, "bjs_OptionalPropertyHolder_optionalName_set") -@_cdecl("bjs_OptionalPropertyHolder_optionalName_set") -public func _bjs_OptionalPropertyHolder_optionalName_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueBytes: Int32, _ valueLength: Int32) -> Void { - #if arch(wasm32) - OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalName = Optional.bridgeJSLiftParameter(valueIsSome, valueBytes, valueLength) - #else - fatalError("Only available on WebAssembly") - #endif +func _$Promise_resolve_Sa5ThemeO(_ promise: JSObject, _ value: [Theme]) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let _ = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_Sa5ThemeO(promiseValue) + if let error = _swift_js_take_exception() { throw error } } -@_expose(wasm, "bjs_OptionalPropertyHolder_optionalAge_get") -@_cdecl("bjs_OptionalPropertyHolder_optionalAge_get") -public func _bjs_OptionalPropertyHolder_optionalAge_get(_ _self: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let ret = OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalAge - return ret.bridgeJSLowerReturn() - #else +@JSFunction func Promise_resolve_SD5ThemeO(_ promise: JSObject, _ value: [String: Theme]) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_SD5ThemeO") +fileprivate func promise_resolve_BridgeJSRuntimeTests_SD5ThemeO_extern(_ promise: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_SD5ThemeO_extern(_ promise: Int32) -> Void { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_SD5ThemeO(_ promise: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_SD5ThemeO_extern(promise) } -@_expose(wasm, "bjs_OptionalPropertyHolder_optionalAge_set") -@_cdecl("bjs_OptionalPropertyHolder_optionalAge_set") -public func _bjs_OptionalPropertyHolder_optionalAge_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: Int32) -> Void { - #if arch(wasm32) - OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalAge = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) - #else - fatalError("Only available on WebAssembly") - #endif +func _$Promise_resolve_SD5ThemeO(_ promise: JSObject, _ value: [String: Theme]) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let _ = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_SD5ThemeO(promiseValue) + if let error = _swift_js_take_exception() { throw error } } -@_expose(wasm, "bjs_OptionalPropertyHolder_optionalGreeter_get") -@_cdecl("bjs_OptionalPropertyHolder_optionalGreeter_get") -public func _bjs_OptionalPropertyHolder_optionalGreeter_get(_ _self: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let ret = OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalGreeter - return ret.bridgeJSLowerReturn() - #else +@JSFunction func Promise_resolve_8FileSizeO(_ promise: JSObject, _ value: FileSize) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_8FileSizeO") +fileprivate func promise_resolve_BridgeJSRuntimeTests_8FileSizeO_extern(_ promise: Int32, _ value: Int64) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_8FileSizeO_extern(_ promise: Int32, _ value: Int64) -> Void { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_8FileSizeO(_ promise: Int32, _ value: Int64) -> Void { + return promise_resolve_BridgeJSRuntimeTests_8FileSizeO_extern(promise, value) } -@_expose(wasm, "bjs_OptionalPropertyHolder_optionalGreeter_set") -@_cdecl("bjs_OptionalPropertyHolder_optionalGreeter_set") -public func _bjs_OptionalPropertyHolder_optionalGreeter_set(_ _self: UnsafeMutableRawPointer, _ valueIsSome: Int32, _ valueValue: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - OptionalPropertyHolder.bridgeJSLiftParameter(_self).optionalGreeter = Optional.bridgeJSLiftParameter(valueIsSome, valueValue) - #else - fatalError("Only available on WebAssembly") - #endif +func _$Promise_resolve_8FileSizeO(_ promise: JSObject, _ value: FileSize) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueValue = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_8FileSizeO(promiseValue, valueValue) + if let error = _swift_js_take_exception() { throw error } } -@_expose(wasm, "bjs_OptionalPropertyHolder_deinit") -@_cdecl("bjs_OptionalPropertyHolder_deinit") -public func _bjs_OptionalPropertyHolder_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() - #else +@JSFunction func Promise_resolve_Sq8FileSizeO(_ promise: JSObject, _ value: Optional) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sq8FileSizeO") +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq8FileSizeO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueValue: Int64) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq8FileSizeO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueValue: Int64) -> Void { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq8FileSizeO(_ promise: Int32, _ valueIsSome: Int32, _ valueValue: Int64) -> Void { + return promise_resolve_BridgeJSRuntimeTests_Sq8FileSizeO_extern(promise, valueIsSome, valueValue) } -extension OptionalPropertyHolder: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { - var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_OptionalPropertyHolder_wrap(Unmanaged.passRetained(self).toOpaque())))) - } - consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { - _bjs_OptionalPropertyHolder_wrap(Unmanaged.passRetained(self).toOpaque()) - } +func _$Promise_resolve_Sq8FileSizeO(_ promise: JSObject, _ value: Optional) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let (valueIsSome, valueValue) = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_Sq8FileSizeO(promiseValue, valueIsSome, valueValue) + if let error = _swift_js_take_exception() { throw error } } +@JSFunction func Promise_resolve_18AsyncPayloadResultO(_ promise: JSObject, _ value: AsyncPayloadResult) throws(JSException) + #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_OptionalPropertyHolder_wrap") -fileprivate func _bjs_OptionalPropertyHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_18AsyncPayloadResultO") +fileprivate func promise_resolve_BridgeJSRuntimeTests_18AsyncPayloadResultO_extern(_ promise: Int32, _ value: Int32) -> Void #else -fileprivate func _bjs_OptionalPropertyHolder_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func promise_resolve_BridgeJSRuntimeTests_18AsyncPayloadResultO_extern(_ promise: Int32, _ value: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_OptionalPropertyHolder_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_OptionalPropertyHolder_wrap_extern(pointer) +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_18AsyncPayloadResultO(_ promise: Int32, _ value: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_18AsyncPayloadResultO_extern(promise, value) } -@_expose(wasm, "bjs_Container_init") -@_cdecl("bjs_Container_init") -public func _bjs_Container_init() -> UnsafeMutableRawPointer { - #if arch(wasm32) - let _tmp_config = Optional.bridgeJSLiftParameter() - let _tmp_location = DataPoint.bridgeJSLiftParameter() - let ret = Container(location: _tmp_location, config: _tmp_config) - return ret.bridgeJSLowerReturn() - #else - fatalError("Only available on WebAssembly") - #endif +func _$Promise_resolve_18AsyncPayloadResultO(_ promise: JSObject, _ value: AsyncPayloadResult) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueCaseId = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_18AsyncPayloadResultO(promiseValue, valueCaseId) + if let error = _swift_js_take_exception() { throw error } } -@_expose(wasm, "bjs_Container_location_get") -@_cdecl("bjs_Container_location_get") -public func _bjs_Container_location_get(_ _self: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let ret = Container.bridgeJSLiftParameter(_self).location - return ret.bridgeJSLowerReturn() - #else +@JSFunction func Promise_resolve_Sq18AsyncPayloadResultO(_ promise: JSObject, _ value: Optional) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sq18AsyncPayloadResultO") +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq18AsyncPayloadResultO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueCaseId: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq18AsyncPayloadResultO_extern(_ promise: Int32, _ valueIsSome: Int32, _ valueCaseId: Int32) -> Void { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq18AsyncPayloadResultO(_ promise: Int32, _ valueIsSome: Int32, _ valueCaseId: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_Sq18AsyncPayloadResultO_extern(promise, valueIsSome, valueCaseId) } -@_expose(wasm, "bjs_Container_location_set") -@_cdecl("bjs_Container_location_set") -public func _bjs_Container_location_set(_ _self: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - Container.bridgeJSLiftParameter(_self).location = DataPoint.bridgeJSLiftParameter() - #else - fatalError("Only available on WebAssembly") - #endif +func _$Promise_resolve_Sq18AsyncPayloadResultO(_ promise: JSObject, _ value: Optional) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let (valueIsSome, valueCaseId) = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_Sq18AsyncPayloadResultO(promiseValue, valueIsSome, valueCaseId) + if let error = _swift_js_take_exception() { throw error } } -@_expose(wasm, "bjs_Container_config_get") -@_cdecl("bjs_Container_config_get") -public func _bjs_Container_config_get(_ _self: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - let ret = Container.bridgeJSLiftParameter(_self).config - return ret.bridgeJSLowerReturn() - #else +@JSFunction func Promise_resolve_11PublicPointV(_ promise: JSObject, _ value: PublicPoint) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_11PublicPointV") +fileprivate func promise_resolve_BridgeJSRuntimeTests_11PublicPointV_extern(_ promise: Int32, _ value: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_11PublicPointV_extern(_ promise: Int32, _ value: Int32) -> Void { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_11PublicPointV(_ promise: Int32, _ value: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_11PublicPointV_extern(promise, value) } -@_expose(wasm, "bjs_Container_config_set") -@_cdecl("bjs_Container_config_set") -public func _bjs_Container_config_set(_ _self: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - Container.bridgeJSLiftParameter(_self).config = Optional.bridgeJSLiftParameter() - #else - fatalError("Only available on WebAssembly") - #endif +func _$Promise_resolve_11PublicPointV(_ promise: JSObject, _ value: PublicPoint) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueObjectId = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_11PublicPointV(promiseValue, valueObjectId) + if let error = _swift_js_take_exception() { throw error } } -@_expose(wasm, "bjs_Container_deinit") -@_cdecl("bjs_Container_deinit") -public func _bjs_Container_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() - #else +@JSFunction func Promise_resolve_7ContactV(_ promise: JSObject, _ value: Contact) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_7ContactV") +fileprivate func promise_resolve_BridgeJSRuntimeTests_7ContactV_extern(_ promise: Int32, _ value: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_7ContactV_extern(_ promise: Int32, _ value: Int32) -> Void { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_7ContactV(_ promise: Int32, _ value: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_7ContactV_extern(promise, value) } -extension Container: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { - var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_Container_wrap(Unmanaged.passRetained(self).toOpaque())))) - } - consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { - _bjs_Container_wrap(Unmanaged.passRetained(self).toOpaque()) - } +func _$Promise_resolve_7ContactV(_ promise: JSObject, _ value: Contact) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueObjectId = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_7ContactV(promiseValue, valueObjectId) + if let error = _swift_js_take_exception() { throw error } } +@JSFunction func Promise_resolve_Sa11PublicPointV(_ promise: JSObject, _ value: [PublicPoint]) throws(JSException) + #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Container_wrap") -fileprivate func _bjs_Container_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sa11PublicPointV") +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sa11PublicPointV_extern(_ promise: Int32) -> Void #else -fileprivate func _bjs_Container_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sa11PublicPointV_extern(_ promise: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_Container_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_Container_wrap_extern(pointer) +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sa11PublicPointV(_ promise: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_Sa11PublicPointV_extern(promise) } -@_expose(wasm, "bjs_LeakCheck_init") -@_cdecl("bjs_LeakCheck_init") -public func _bjs_LeakCheck_init() -> UnsafeMutableRawPointer { - #if arch(wasm32) - let ret = LeakCheck() - return ret.bridgeJSLowerReturn() - #else +func _$Promise_resolve_Sa11PublicPointV(_ promise: JSObject, _ value: [PublicPoint]) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let _ = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_Sa11PublicPointV(promiseValue) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_Sq11PublicPointV(_ promise: JSObject, _ value: Optional) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sq11PublicPointV") +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq11PublicPointV_extern(_ promise: Int32, _ value: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq11PublicPointV_extern(_ promise: Int32, _ value: Int32) -> Void { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq11PublicPointV(_ promise: Int32, _ value: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_Sq11PublicPointV_extern(promise, value) } -@_expose(wasm, "bjs_LeakCheck_deinit") -@_cdecl("bjs_LeakCheck_deinit") -public func _bjs_LeakCheck_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { - #if arch(wasm32) - Unmanaged.fromOpaque(pointer).release() - #else +func _$Promise_resolve_Sq11PublicPointV(_ promise: JSObject, _ value: Optional) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueIsSome = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_Sq11PublicPointV(promiseValue, valueIsSome) + if let error = _swift_js_take_exception() { throw error } +} + +@JSFunction func Promise_resolve_SD11PublicPointV(_ promise: JSObject, _ value: [String: PublicPoint]) throws(JSException) + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_SD11PublicPointV") +fileprivate func promise_resolve_BridgeJSRuntimeTests_SD11PublicPointV_extern(_ promise: Int32) -> Void +#else +fileprivate func promise_resolve_BridgeJSRuntimeTests_SD11PublicPointV_extern(_ promise: Int32) -> Void { fatalError("Only available on WebAssembly") - #endif +} +#endif +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_SD11PublicPointV(_ promise: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_SD11PublicPointV_extern(promise) } -extension LeakCheck: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { - public var jsValue: JSValue { - return .object(JSObject(id: UInt32(bitPattern: _bjs_LeakCheck_wrap(Unmanaged.passRetained(self).toOpaque())))) - } - public consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { - _bjs_LeakCheck_wrap(Unmanaged.passRetained(self).toOpaque()) - } +func _$Promise_resolve_SD11PublicPointV(_ promise: JSObject, _ value: [String: PublicPoint]) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let _ = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_SD11PublicPointV(promiseValue) + if let error = _swift_js_take_exception() { throw error } } +@JSFunction func Promise_resolve_9DataPointV(_ promise: JSObject, _ value: DataPoint) throws(JSException) + #if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_LeakCheck_wrap") -fileprivate func _bjs_LeakCheck_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +@_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_9DataPointV") +fileprivate func promise_resolve_BridgeJSRuntimeTests_9DataPointV_extern(_ promise: Int32, _ value: Int32) -> Void #else -fileprivate func _bjs_LeakCheck_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { +fileprivate func promise_resolve_BridgeJSRuntimeTests_9DataPointV_extern(_ promise: Int32, _ value: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func _bjs_LeakCheck_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { - return _bjs_LeakCheck_wrap_extern(pointer) +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_9DataPointV(_ promise: Int32, _ value: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_9DataPointV_extern(promise, value) +} + +func _$Promise_resolve_9DataPointV(_ promise: JSObject, _ value: DataPoint) throws(JSException) -> Void { + let promiseValue = promise.bridgeJSLowerParameter() + let valueObjectId = value.bridgeJSLowerParameter() + promise_resolve_BridgeJSRuntimeTests_9DataPointV(promiseValue, valueObjectId) + if let error = _swift_js_take_exception() { throw error } } +extension Polygon: _BridgedSwiftAlias, _BridgedSwiftStackType {} + +extension Tag: _BridgedSwiftAlias, _BridgedSwiftStackType {} + +extension TagHolder: _BridgedSwiftAlias, _BridgedSwiftStackType {} + +extension Coordinate: _BridgedSwiftAlias, _BridgedSwiftStruct {} + +extension Priority: _BridgedSwiftAlias, _BridgedSwiftStackType {} + +extension Alert: _BridgedSwiftAlias, _BridgedSwiftCaseEnum {} + +extension UserId: _BridgedSwiftAlias, _BridgedSwiftStackType {} + +extension Tagged: _BridgedSwiftAlias, _BridgedSwiftStackType {} + +extension Canvas: _BridgedSwiftAlias, _BridgedSwiftStackType {} + +extension AliasedTag: _BridgedSwiftAlias, _BridgedSwiftAssociatedValueEnum {} + +extension Boxed: _BridgedSwiftAlias, _BridgedSwiftStackType {} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Surface_init") fileprivate func bjs_Surface_init_extern(_ labelBytes: Int32, _ labelLength: Int32) -> Int32 @@ -12134,8 +13907,32 @@ fileprivate func bjs_AliasImports_jsRoundTripCoordinate_static_extern(_ value: I return bjs_AliasImports_jsRoundTripCoordinate_static_extern(value) } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_AliasImports_jsRoundTripUserId_static") +fileprivate func bjs_AliasImports_jsRoundTripUserId_static_extern(_ value: Int32) -> Int32 +#else +fileprivate func bjs_AliasImports_jsRoundTripUserId_static_extern(_ value: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_AliasImports_jsRoundTripUserId_static(_ value: Int32) -> Int32 { + return bjs_AliasImports_jsRoundTripUserId_static_extern(value) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_AliasImports_jsRoundTripOptionalUserId_static") +fileprivate func bjs_AliasImports_jsRoundTripOptionalUserId_static_extern(_ valueIsSome: Int32, _ valueValue: Int32) -> Void +#else +fileprivate func bjs_AliasImports_jsRoundTripOptionalUserId_static_extern(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_AliasImports_jsRoundTripOptionalUserId_static(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { + return bjs_AliasImports_jsRoundTripOptionalUserId_static_extern(valueIsSome, valueValue) +} + func _$AliasImports_jsRoundTripTagged(_ value: Tagged) throws(JSException) -> Tagged { - let ret0 = value.bridgeToJS().bridgeJSWithLoweredParameter { (valueBytes, valueLength) in + let ret0 = value.bridgeJSWithLoweredParameter { (valueBytes, valueLength) in let ret = bjs_AliasImports_jsRoundTripTagged_static(valueBytes, valueLength) return ret } @@ -12143,21 +13940,17 @@ func _$AliasImports_jsRoundTripTagged(_ value: Tagged) throws(JSException) -> Ta if let error = _swift_js_take_exception() { throw error } - return Tagged.bridgeFromJS(String.bridgeJSLiftReturn(ret)) + return Tagged.bridgeJSLiftReturn(ret) } func _$AliasImports_jsRoundTripOptionalTagged(_ value: Optional) throws(JSException) -> Optional { - value.map { - $0.bridgeToJS() - } .bridgeJSWithLoweredParameter { (valueIsSome, valueBytes, valueLength) in + value.bridgeJSWithLoweredParameter { (valueIsSome, valueBytes, valueLength) in bjs_AliasImports_jsRoundTripOptionalTagged_static(valueIsSome, valueBytes, valueLength) } if let error = _swift_js_take_exception() { throw error } - return Optional.bridgeJSLiftReturnFromSideChannel().map { - Tagged.bridgeFromJS($0) - } + return Optional.bridgeJSLiftReturnFromSideChannel() } func _$AliasImports_jsProduceOptionalCanvas(_ label: Optional) throws(JSException) -> Optional { @@ -12167,44 +13960,52 @@ func _$AliasImports_jsProduceOptionalCanvas(_ label: Optional) throws(JS if let error = _swift_js_take_exception() { throw error } - return Optional.bridgeJSLiftReturn().map { - Canvas.bridgeFromJS($0) - } + return Optional.bridgeJSLiftReturn() } func _$AliasImports_jsRoundTripAliasedTags(_ values: [Optional]) throws(JSException) -> [Optional] { - let _ = values.map { - $0.map { - $0.bridgeToJS() - } - } .bridgeJSLowerParameter() + let _ = values.bridgeJSLowerParameter() bjs_AliasImports_jsRoundTripAliasedTags_static() if let error = _swift_js_take_exception() { throw error } - return [Optional].bridgeJSLiftReturn().map { - $0.map { - AliasedTag.bridgeFromJS($0) - } - } + return [Optional].bridgeJSLiftReturn() } func _$AliasImports_jsRoundTripPolygon(_ value: Polygon) throws(JSException) -> Polygon { - let valuePointer = value.bridgeToJS().bridgeJSLowerParameter() + let valuePointer = value.bridgeJSLowerParameter() let ret = bjs_AliasImports_jsRoundTripPolygon_static(valuePointer) if let error = _swift_js_take_exception() { throw error } - return Polygon.bridgeFromJS(PolygonReference.bridgeJSLiftReturn(ret)) + return Polygon.bridgeJSLiftReturn(ret) } func _$AliasImports_jsRoundTripCoordinate(_ value: Coordinate) throws(JSException) -> Coordinate { - let valueObjectId = value.bridgeToJS().bridgeJSLowerParameter() + let valueObjectId = value.bridgeJSLowerParameter() let ret = bjs_AliasImports_jsRoundTripCoordinate_static(valueObjectId) if let error = _swift_js_take_exception() { throw error } - return Coordinate.bridgeFromJS(JSCoordinate.bridgeJSLiftReturn(ret)) + return Coordinate.bridgeJSLiftReturn(ret) +} + +func _$AliasImports_jsRoundTripUserId(_ value: UserId) throws(JSException) -> UserId { + let valueValue = value.bridgeJSLowerParameter() + let ret = bjs_AliasImports_jsRoundTripUserId_static(valueValue) + if let error = _swift_js_take_exception() { + throw error + } + return UserId.bridgeJSLiftReturn(ret) +} + +func _$AliasImports_jsRoundTripOptionalUserId(_ value: Optional) throws(JSException) -> Optional { + let (valueIsSome, valueValue) = value.bridgeJSLowerParameter() + bjs_AliasImports_jsRoundTripOptionalUserId_static(valueIsSome, valueValue) + if let error = _swift_js_take_exception() { + throw error + } + return Optional.bridgeJSLiftReturnFromSideChannel() } #if arch(wasm32) @@ -12726,6 +14527,30 @@ fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripFeatureFlag_static_exter return bjs_AsyncImportImports_jsAsyncRoundTripFeatureFlag_static_extern(resolveRef, rejectRef, vBytes, vLength) } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_AsyncImportImports_jsAsyncRoundTripAssociatedValueEnum_static") +fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripAssociatedValueEnum_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ v: Int32) -> Void +#else +fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripAssociatedValueEnum_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ v: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripAssociatedValueEnum_static(_ resolveRef: Int32, _ rejectRef: Int32, _ v: Int32) -> Void { + return bjs_AsyncImportImports_jsAsyncRoundTripAssociatedValueEnum_static_extern(resolveRef, rejectRef, v) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_AsyncImportImports_jsAsyncRoundTripOptionalAssociatedValueEnum_static") +fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripOptionalAssociatedValueEnum_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ vIsSome: Int32, _ vCaseId: Int32) -> Void +#else +fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripOptionalAssociatedValueEnum_static_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ vIsSome: Int32, _ vCaseId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_AsyncImportImports_jsAsyncRoundTripOptionalAssociatedValueEnum_static(_ resolveRef: Int32, _ rejectRef: Int32, _ vIsSome: Int32, _ vCaseId: Int32) -> Void { + return bjs_AsyncImportImports_jsAsyncRoundTripOptionalAssociatedValueEnum_static_extern(resolveRef, rejectRef, vIsSome, vCaseId) +} + func _$AsyncImportImports_jsAsyncRoundTripVoid() async throws(JSException) -> Void { try await _bjs_awaitPromise(makeResolveClosure: { JSTypedClosure<() -> Void>($0) @@ -12847,6 +14672,52 @@ func _$AsyncImportImports_jsAsyncRoundTripFeatureFlag(_ v: FeatureFlag) async th return resolved } +func _$AsyncImportImports_jsAsyncRoundTripAssociatedValueEnum(_ v: AsyncImportedPayloadResult) async throws(JSException) -> AsyncImportedPayloadResult { + let resolved = try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending AsyncImportedPayloadResult) -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + let vCaseId = v.bridgeJSLowerParameter() + bjs_AsyncImportImports_jsAsyncRoundTripAssociatedValueEnum_static(resolveRef, rejectRef, vCaseId) + } + return resolved +} + +func _$AsyncImportImports_jsAsyncRoundTripOptionalAssociatedValueEnum(_ v: Optional) async throws(JSException) -> Optional { + let resolved = try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<(sending Optional) -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + let (vIsSome, vCaseId) = v.bridgeJSLowerParameter() + bjs_AsyncImportImports_jsAsyncRoundTripOptionalAssociatedValueEnum_static(resolveRef, rejectRef, vIsSome, vCaseId) + } + return resolved +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureAsyncImports_runJsClosureAsyncTests_static") +fileprivate func bjs_ClosureAsyncImports_runJsClosureAsyncTests_static_extern(_ resolveRef: Int32, _ rejectRef: Int32) -> Void +#else +fileprivate func bjs_ClosureAsyncImports_runJsClosureAsyncTests_static_extern(_ resolveRef: Int32, _ rejectRef: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ClosureAsyncImports_runJsClosureAsyncTests_static(_ resolveRef: Int32, _ rejectRef: Int32) -> Void { + return bjs_ClosureAsyncImports_runJsClosureAsyncTests_static_extern(resolveRef, rejectRef) +} + +func _$ClosureAsyncImports_runJsClosureAsyncTests() async throws(JSException) -> Void { + try await _bjs_awaitPromise(makeResolveClosure: { + JSTypedClosure<() -> Void>($0) + }, makeRejectClosure: { + JSTypedClosure<(sending JSValue) -> Void>($0) + }) { resolveRef, rejectRef in + bjs_ClosureAsyncImports_runJsClosureAsyncTests_static(resolveRef, rejectRef) + } +} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureSupportImports_jsApplyVoid_static") fileprivate func bjs_ClosureSupportImports_jsApplyVoid_static_extern(_ callback: Int32) -> Void @@ -13229,6 +15100,25 @@ func _$ClosureSupportImports_runJsClosureSupportTests() throws(JSException) -> V } } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ClosureThrowsImports_runJsClosureThrowsTests_static") +fileprivate func bjs_ClosureThrowsImports_runJsClosureThrowsTests_static_extern() -> Void +#else +fileprivate func bjs_ClosureThrowsImports_runJsClosureThrowsTests_static_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ClosureThrowsImports_runJsClosureThrowsTests_static() -> Void { + return bjs_ClosureThrowsImports_runJsClosureThrowsTests_static_extern() +} + +func _$ClosureThrowsImports_runJsClosureThrowsTests() throws(JSException) -> Void { + bjs_ClosureThrowsImports_runJsClosureThrowsTests_static() + if let error = _swift_js_take_exception() { + throw error + } +} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_DefaultArgumentImports_runJsDefaultArgumentTests_static") fileprivate func bjs_DefaultArgumentImports_runJsDefaultArgumentTests_static_extern() -> Void @@ -13674,28 +15564,6 @@ func _$runAsyncWorks() async throws(JSException) -> Void { } } -#if arch(wasm32) -@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_runAliasAsyncWorks") -fileprivate func bjs_runAliasAsyncWorks_extern(_ resolveRef: Int32, _ rejectRef: Int32) -> Void -#else -fileprivate func bjs_runAliasAsyncWorks_extern(_ resolveRef: Int32, _ rejectRef: Int32) -> Void { - fatalError("Only available on WebAssembly") -} -#endif -@inline(never) fileprivate func bjs_runAliasAsyncWorks(_ resolveRef: Int32, _ rejectRef: Int32) -> Void { - return bjs_runAliasAsyncWorks_extern(resolveRef, rejectRef) -} - -func _$runAliasAsyncWorks() async throws(JSException) -> Void { - try await _bjs_awaitPromise(makeResolveClosure: { - JSTypedClosure<() -> Void>($0) - }, makeRejectClosure: { - JSTypedClosure<(sending JSValue) -> Void>($0) - }) { resolveRef, rejectRef in - bjs_runAliasAsyncWorks(resolveRef, rejectRef) - } -} - #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_fetchWeatherData") fileprivate func bjs_fetchWeatherData_extern(_ resolveRef: Int32, _ rejectRef: Int32, _ cityBytes: Int32, _ cityLength: Int32) -> Void @@ -14385,6 +16253,69 @@ func _$Animal_getIsCat(_ self: JSObject) throws(JSException) -> Bool { return Bool.bridgeJSLiftReturn(ret) } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripLightColor") +fileprivate func bjs_jsRoundTripLightColor_extern(_ value: Int32) -> Int32 +#else +fileprivate func bjs_jsRoundTripLightColor_extern(_ value: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsRoundTripLightColor(_ value: Int32) -> Int32 { + return bjs_jsRoundTripLightColor_extern(value) +} + +func _$jsRoundTripLightColor(_ value: LightColor) throws(JSException) -> LightColor { + let valueValue = value.bridgeJSLowerParameter() + let ret = bjs_jsRoundTripLightColor(valueValue) + if let error = _swift_js_take_exception() { + throw error + } + return LightColor.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripImportedPayloadSignal") +fileprivate func bjs_jsRoundTripImportedPayloadSignal_extern(_ value: Int32) -> Int32 +#else +fileprivate func bjs_jsRoundTripImportedPayloadSignal_extern(_ value: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsRoundTripImportedPayloadSignal(_ value: Int32) -> Int32 { + return bjs_jsRoundTripImportedPayloadSignal_extern(value) +} + +func _$jsRoundTripImportedPayloadSignal(_ value: ImportedPayloadSignal) throws(JSException) -> ImportedPayloadSignal { + let valueCaseId = value.bridgeJSLowerParameter() + let ret = bjs_jsRoundTripImportedPayloadSignal(valueCaseId) + if let error = _swift_js_take_exception() { + throw error + } + return ImportedPayloadSignal.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripOptionalImportedPayloadSignal") +fileprivate func bjs_jsRoundTripOptionalImportedPayloadSignal_extern(_ valueIsSome: Int32, _ valueCaseId: Int32) -> Int32 +#else +fileprivate func bjs_jsRoundTripOptionalImportedPayloadSignal_extern(_ valueIsSome: Int32, _ valueCaseId: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsRoundTripOptionalImportedPayloadSignal(_ valueIsSome: Int32, _ valueCaseId: Int32) -> Int32 { + return bjs_jsRoundTripOptionalImportedPayloadSignal_extern(valueIsSome, valueCaseId) +} + +func _$jsRoundTripOptionalImportedPayloadSignal(_ value: Optional) throws(JSException) -> Optional { + let (valueIsSome, valueCaseId) = value.bridgeJSLowerParameter() + let ret = bjs_jsRoundTripOptionalImportedPayloadSignal(valueIsSome, valueCaseId) + if let error = _swift_js_take_exception() { + throw error + } + return Optional.bridgeJSLiftReturn(ret) +} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsTranslatePoint") fileprivate func bjs_jsTranslatePoint_extern(_ point: Int32, _ dx: Int32, _ dy: Int32) -> Int32 @@ -14408,6 +16339,27 @@ func _$jsTranslatePoint(_ point: Point, _ dx: Int, _ dy: Int) throws(JSException return Point.bridgeJSLiftReturn(ret) } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripOptionalPoint") +fileprivate func bjs_jsRoundTripOptionalPoint_extern(_ point: Int32) -> Void +#else +fileprivate func bjs_jsRoundTripOptionalPoint_extern(_ point: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsRoundTripOptionalPoint(_ point: Int32) -> Void { + return bjs_jsRoundTripOptionalPoint_extern(point) +} + +func _$jsRoundTripOptionalPoint(_ point: Optional) throws(JSException) -> Optional { + let pointIsSome = point.bridgeJSLowerParameter() + bjs_jsRoundTripOptionalPoint(pointIsSome) + if let error = _swift_js_take_exception() { + throw error + } + return Optional.bridgeJSLiftReturn() +} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_IntegerTypesSupportImports_jsRoundTripInt_static") fileprivate func bjs_IntegerTypesSupportImports_jsRoundTripInt_static_extern(_ v: Int32) -> Int32 @@ -15205,6 +17157,18 @@ fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDic return bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryUndefined_static_extern(v) } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_OptionalSupportImports_jsRoundTripOptionalJSObjectNull_static") +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalJSObjectNull_static_extern(_ valueIsSome: Int32, _ valueValue: Int32) -> Void +#else +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalJSObjectNull_static_extern(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalJSObjectNull_static(_ valueIsSome: Int32, _ valueValue: Int32) -> Void { + return bjs_OptionalSupportImports_jsRoundTripOptionalJSObjectNull_static_extern(valueIsSome, valueValue) +} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_OptionalSupportImports_runJsOptionalSupportTests_static") fileprivate func bjs_OptionalSupportImports_runJsOptionalSupportTests_static_extern() -> Void @@ -15291,6 +17255,15 @@ func _$OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryUndefin return JSUndefinedOr<[String: String]>.bridgeJSLiftReturn() } +func _$OptionalSupportImports_jsRoundTripOptionalJSObjectNull(_ value: Optional) throws(JSException) -> Optional { + let (valueIsSome, valueValue) = value.bridgeJSLowerParameter() + bjs_OptionalSupportImports_jsRoundTripOptionalJSObjectNull_static(valueIsSome, valueValue) + if let error = _swift_js_take_exception() { + throw error + } + return Optional.bridgeJSLiftReturn() +} + func _$OptionalSupportImports_runJsOptionalSupportTests() throws(JSException) -> Void { bjs_OptionalSupportImports_runJsOptionalSupportTests_static() if let error = _swift_js_take_exception() { diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index fb6286e97..25fd27d9f 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -17,14 +17,6 @@ } } }, - { - "swiftCallName" : "Token", - "underlying" : { - "swiftHeapObject" : { - "_0" : "TokenReference" - } - } - }, { "swiftCallName" : "TagHolder", "underlying" : { @@ -58,10 +50,13 @@ } }, { - "swiftCallName" : "Session", + "swiftCallName" : "UserId", "underlying" : { - "swiftStruct" : { - "_0" : "SessionState" + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, @@ -88,6 +83,14 @@ "_0" : "InnerTag" } } + }, + { + "swiftCallName" : "Boxed", + "underlying" : { + "jsValue" : { + + } + } } ], "classes" : [ @@ -287,57 +290,6 @@ ], "swiftCallName" : "TagReference" }, - { - "constructor" : { - "abiName" : "bjs_TokenReference_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - { - "label" : "value", - "name" : "value", - "type" : { - "integer" : { - "_0" : { - "isSigned" : true, - "width" : "word" - } - } - } - } - ] - }, - "methods" : [ - { - "abiName" : "bjs_TokenReference_read", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "read", - "parameters" : [ - - ], - "returnType" : { - "integer" : { - "_0" : { - "isSigned" : true, - "width" : "word" - } - } - } - } - ], - "name" : "TokenReference", - "properties" : [ - - ], - "swiftCallName" : "TokenReference" - }, { "constructor" : { "abiName" : "bjs_TagHolderReference_init", @@ -1461,6 +1413,46 @@ } } } + }, + { + "abiName" : "bjs_Calculator_asyncMakePoint", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncMakePoint", + "parameters" : [ + { + "label" : "x", + "name" : "x", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "label" : "y", + "name" : "y", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "PublicPoint" + } + } } ], "name" : "Calculator", @@ -7167,6 +7159,53 @@ "swiftCallName" : "ArraySupportExports", "tsFullPath" : "ArraySupportExports" }, + { + "cases" : [ + { + "associatedValues" : [ + { + "type" : { + "string" : { + + } + } + } + ], + "name" : "success" + }, + { + "associatedValues" : [ + { + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "name" : "failure" + }, + { + "associatedValues" : [ + + ], + "name" : "idle" + } + ], + "emitStyle" : "const", + "name" : "AsyncImportedPayloadResult", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "AsyncImportedPayloadResult", + "tsFullPath" : "AsyncImportedPayloadResult" + }, { "cases" : [ @@ -8332,6 +8371,53 @@ "swiftCallName" : "TSTheme", "tsFullPath" : "TSTheme" }, + { + "cases" : [ + { + "associatedValues" : [ + { + "type" : { + "string" : { + + } + } + } + ], + "name" : "success" + }, + { + "associatedValues" : [ + { + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "name" : "failure" + }, + { + "associatedValues" : [ + + ], + "name" : "idle" + } + ], + "emitStyle" : "const", + "name" : "AsyncPayloadResult", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "AsyncPayloadResult", + "tsFullPath" : "AsyncPayloadResult" + }, { "cases" : [ @@ -9911,6 +9997,85 @@ "swiftCallName" : "NestedStructGroupB", "tsFullPath" : "NestedStructGroupB" }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "red" + }, + { + "associatedValues" : [ + + ], + "name" : "yellow" + }, + { + "associatedValues" : [ + + ], + "name" : "green" + } + ], + "emitStyle" : "const", + "name" : "LightColor", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "LightColor", + "tsFullPath" : "LightColor" + }, + { + "cases" : [ + { + "associatedValues" : [ + { + "type" : { + "string" : { + + } + } + } + ], + "name" : "start" + }, + { + "associatedValues" : [ + { + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "name" : "stop" + }, + { + "associatedValues" : [ + + ], + "name" : "idle" + } + ], + "emitStyle" : "const", + "name" : "ImportedPayloadSignal", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "ImportedPayloadSignal", + "tsFullPath" : "ImportedPayloadSignal" + }, { "cases" : [ @@ -12392,81 +12557,13 @@ } }, { - "abiName" : "bjs_incrementToken", + "abiName" : "bjs_makePolygonInspector", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "incrementToken", - "parameters" : [ - { - "label" : "_", - "name" : "token", - "type" : { - "alias" : { - "name" : "Token", - "underlying" : { - "swiftHeapObject" : { - "_0" : "TokenReference" - } - } - } - } - } - ], - "returnType" : { - "alias" : { - "name" : "Token", - "underlying" : { - "swiftHeapObject" : { - "_0" : "TokenReference" - } - } - } - } - }, - { - "abiName" : "bjs_makeToken", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "makeToken", - "parameters" : [ - { - "label" : "_", - "name" : "value", - "type" : { - "integer" : { - "_0" : { - "isSigned" : true, - "width" : "word" - } - } - } - } - ], - "returnType" : { - "alias" : { - "name" : "Token", - "underlying" : { - "swiftHeapObject" : { - "_0" : "TokenReference" - } - } - } - } - }, - { - "abiName" : "bjs_makePolygonInspector", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "makePolygonInspector", + "name" : "makePolygonInspector", "parameters" : [ ], @@ -12503,36 +12600,6 @@ } } }, - { - "abiName" : "bjs_asyncMakePolygon", - "effects" : { - "isAsync" : true, - "isStatic" : false, - "isThrows" : false - }, - "name" : "asyncMakePolygon", - "parameters" : [ - { - "label" : "_", - "name" : "label", - "type" : { - "string" : { - - } - } - } - ], - "returnType" : { - "alias" : { - "name" : "Polygon", - "underlying" : { - "swiftHeapObject" : { - "_0" : "PolygonReference" - } - } - } - } - }, { "abiName" : "bjs_roundTripOptionalPolygonArray", "effects" : { @@ -12763,71 +12830,6 @@ } } }, - { - "abiName" : "bjs_roundTripSession", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "roundTripSession", - "parameters" : [ - { - "label" : "_", - "name" : "session", - "type" : { - "alias" : { - "name" : "Session", - "underlying" : { - "swiftStruct" : { - "_0" : "SessionState" - } - } - } - } - } - ], - "returnType" : { - "alias" : { - "name" : "Session", - "underlying" : { - "swiftStruct" : { - "_0" : "SessionState" - } - } - } - } - }, - { - "abiName" : "bjs_makeSession", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "makeSession", - "parameters" : [ - { - "label" : "_", - "name" : "token", - "type" : { - "string" : { - - } - } - } - ], - "returnType" : { - "alias" : { - "name" : "Session", - "underlying" : { - "swiftStruct" : { - "_0" : "SessionState" - } - } - } - } - }, { "abiName" : "bjs_roundTripShape", "effects" : { @@ -12901,314 +12903,1295 @@ } }, { - "abiName" : "bjs_roundTripVoid", + "abiName" : "bjs_roundTripUserId", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripVoid", + "name" : "roundTripUserId", "parameters" : [ - + { + "label" : "_", + "name" : "id", + "type" : { + "alias" : { + "name" : "UserId", + "underlying" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + } + } ], "returnType" : { - "void" : { - + "alias" : { + "name" : "UserId", + "underlying" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } } } }, { - "abiName" : "bjs_roundTripFloat", + "abiName" : "bjs_roundTripOptionalUserId", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripFloat", + "name" : "roundTripOptionalUserId", "parameters" : [ { - "label" : "v", - "name" : "v", + "label" : "_", + "name" : "id", "type" : { - "float" : { - + "nullable" : { + "_0" : { + "alias" : { + "name" : "UserId", + "underlying" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + }, + "_1" : "null" } } } ], "returnType" : { - "float" : { - + "nullable" : { + "_0" : { + "alias" : { + "name" : "UserId", + "underlying" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_roundTripDouble", + "abiName" : "bjs_roundTripUserIdArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripDouble", + "name" : "roundTripUserIdArray", "parameters" : [ { - "label" : "v", - "name" : "v", + "label" : "_", + "name" : "ids", "type" : { - "double" : { - + "array" : { + "_0" : { + "alias" : { + "name" : "UserId", + "underlying" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + } } } } ], "returnType" : { - "double" : { - + "array" : { + "_0" : { + "alias" : { + "name" : "UserId", + "underlying" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + } } } }, { - "abiName" : "bjs_roundTripBool", + "abiName" : "bjs_roundTripBoxed", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripBool", + "name" : "roundTripBoxed", "parameters" : [ { - "label" : "v", - "name" : "v", + "label" : "_", + "name" : "boxed", "type" : { - "bool" : { + "alias" : { + "name" : "Boxed", + "underlying" : { + "jsValue" : { + } + } } } } ], "returnType" : { - "bool" : { - - } + "alias" : { + "name" : "Boxed", + "underlying" : { + "jsValue" : { + + } + } + } + } + }, + { + "abiName" : "bjs_roundTripOptionalBoxed", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalBoxed", + "parameters" : [ + { + "label" : "_", + "name" : "boxed", + "type" : { + "nullable" : { + "_0" : { + "alias" : { + "name" : "Boxed", + "underlying" : { + "jsValue" : { + + } + } + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "alias" : { + "name" : "Boxed", + "underlying" : { + "jsValue" : { + + } + } + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_awaitAsyncCallback", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "awaitAsyncCallback", + "parameters" : [ + { + "label" : "_", + "name" : "fetch", + "type" : { + "closure" : { + "_0" : { + "isAsync" : true, + "isThrows" : true, + "mangleName" : "20BridgeJSRuntimeTestsYaKSS_SS", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "string" : { + + } + } + ], + "returnType" : { + "string" : { + + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_makeAsyncParser", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "makeAsyncParser", + "parameters" : [ + + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : true, + "isThrows" : true, + "mangleName" : "20BridgeJSRuntimeTestsYaKSS_SS", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "string" : { + + } + } + ], + "returnType" : { + "string" : { + + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : true + } + } + }, + { + "abiName" : "bjs_makeAsyncEcho", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "makeAsyncEcho", + "parameters" : [ + + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : true, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsYaSS_SS", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "string" : { + + } + } + ], + "returnType" : { + "string" : { + + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : true + } + } + }, + { + "abiName" : "bjs_makeAsyncRecorder", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "makeAsyncRecorder", + "parameters" : [ + + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : true, + "isThrows" : true, + "mangleName" : "20BridgeJSRuntimeTestsYaKSS_y", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "string" : { + + } + } + ], + "returnType" : { + "void" : { + + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : true + } + } + }, + { + "abiName" : "bjs_lastRecordedValue", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "lastRecordedValue", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_makeAsyncPayloadLoader", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "makeAsyncPayloadLoader", + "parameters" : [ + + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : true, + "isThrows" : true, + "mangleName" : "20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "bool" : { + + } + } + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "AsyncPayloadResult" + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : true + } + } + }, + { + "abiName" : "bjs_awaitPayloadCallback", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "awaitPayloadCallback", + "parameters" : [ + { + "label" : "_", + "name" : "load", + "type" : { + "closure" : { + "_0" : { + "isAsync" : true, + "isThrows" : true, + "mangleName" : "20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "bool" : { + + } + } + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "AsyncPayloadResult" + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_makeAsyncPointMaker", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "makeAsyncPointMaker", + "parameters" : [ + + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : true, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTestsYaSd_9DataPointV", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "double" : { + + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "DataPoint" + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : true + } + } + }, + { + "abiName" : "bjs_makeThrowingParser", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "makeThrowingParser", + "parameters" : [ + + ], + "returnType" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : true, + "mangleName" : "20BridgeJSRuntimeTestsKSS_Si", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "string" : { + + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : true + } + } + }, + { + "abiName" : "bjs_runValidator", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "runValidator", + "parameters" : [ + { + "label" : "_", + "name" : "validate", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : true, + "mangleName" : "20BridgeJSRuntimeTestsKSS_Sb", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "string" : { + + } + } + ], + "returnType" : { + "bool" : { + + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "bool" : { + + } + } + }, + { + "abiName" : "bjs_roundTripVoid", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripVoid", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_roundTripFloat", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripFloat", + "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "float" : { + + } + } + } + ], + "returnType" : { + "float" : { + + } + } + }, + { + "abiName" : "bjs_roundTripDouble", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripDouble", + "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "double" : { + + } + } + } + ], + "returnType" : { + "double" : { + + } + } + }, + { + "abiName" : "bjs_roundTripBool", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripBool", + "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "bool" : { + + } + } + } + ], + "returnType" : { + "bool" : { + + } + } + }, + { + "abiName" : "bjs_roundTripString", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripString", + "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_roundTripSwiftHeapObject", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripSwiftHeapObject", + "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } + } + ], + "returnType" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } + }, + { + "abiName" : "bjs_roundTripUnsafeRawPointer", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripUnsafeRawPointer", + "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeRawPointer" + } + } + } + } + ], + "returnType" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeRawPointer" + } + } + } + }, + { + "abiName" : "bjs_roundTripUnsafeMutableRawPointer", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripUnsafeMutableRawPointer", + "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutableRawPointer" + } + } + } + } + ], + "returnType" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutableRawPointer" + } + } + } + }, + { + "abiName" : "bjs_roundTripOpaquePointer", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOpaquePointer", + "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "opaquePointer" + } + } + } + } + ], + "returnType" : { + "unsafePointer" : { + "_0" : { + "kind" : "opaquePointer" + } + } + } + }, + { + "abiName" : "bjs_roundTripUnsafePointer", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripUnsafePointer", + "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafePointer", + "pointee" : "UInt8" + } + } + } + } + ], + "returnType" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafePointer", + "pointee" : "UInt8" + } + } + } + }, + { + "abiName" : "bjs_roundTripUnsafeMutablePointer", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripUnsafeMutablePointer", + "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutablePointer", + "pointee" : "UInt8" + } + } + } + } + ], + "returnType" : { + "unsafePointer" : { + "_0" : { + "kind" : "unsafeMutablePointer", + "pointee" : "UInt8" + } + } + } + }, + { + "abiName" : "bjs_roundTripJSObject", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripJSObject", + "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "jsObject" : { + + } + } + } + ], + "returnType" : { + "jsObject" : { + + } + } + }, + { + "abiName" : "bjs_roundTripDictionaryExport", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripDictionaryExport", + "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "dictionary" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + } + } + ], + "returnType" : { + "dictionary" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } } }, { - "abiName" : "bjs_roundTripString", + "abiName" : "bjs_roundTripOptionalDictionaryExport", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripString", + "name" : "roundTripOptionalDictionaryExport", "parameters" : [ { "label" : "v", "name" : "v", "type" : { - "string" : { + "nullable" : { + "_0" : { + "dictionary" : { + "_0" : { + "string" : { + } + } + } + }, + "_1" : "null" } } } ], "returnType" : { - "string" : { + "nullable" : { + "_0" : { + "dictionary" : { + "_0" : { + "string" : { + } + } + } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_roundTripSwiftHeapObject", + "abiName" : "bjs_roundTripJSValue", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripSwiftHeapObject", + "name" : "roundTripJSValue", "parameters" : [ { "label" : "v", "name" : "v", "type" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "jsValue" : { + } } } ], "returnType" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "jsValue" : { + } } }, { - "abiName" : "bjs_roundTripUnsafeRawPointer", + "abiName" : "bjs_roundTripOptionalJSValue", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripUnsafeRawPointer", + "name" : "roundTripOptionalJSValue", "parameters" : [ { "label" : "v", "name" : "v", "type" : { - "unsafePointer" : { + "nullable" : { "_0" : { - "kind" : "unsafeRawPointer" - } + "jsValue" : { + + } + }, + "_1" : "null" } } } ], "returnType" : { - "unsafePointer" : { + "nullable" : { "_0" : { - "kind" : "unsafeRawPointer" - } + "jsValue" : { + + } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_roundTripUnsafeMutableRawPointer", + "abiName" : "bjs_roundTripOptionalJSValueArray", "effects" : { "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripUnsafeMutableRawPointer", + "name" : "roundTripOptionalJSValueArray", "parameters" : [ { "label" : "v", "name" : "v", "type" : { - "unsafePointer" : { + "nullable" : { "_0" : { - "kind" : "unsafeMutableRawPointer" + "array" : { + "_0" : { + "jsValue" : { + + } + } + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "jsValue" : { + + } } } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_makeImportedFoo", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "makeImportedFoo", + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "string" : { + + } } } ], "returnType" : { - "unsafePointer" : { + "jsObject" : { + "_0" : "Foo" + } + } + }, + { + "abiName" : "bjs_roundTripOptionalImportedClass", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripOptionalImportedClass", + "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "jsObject" : { + "_0" : "Foo" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { "_0" : { - "kind" : "unsafeMutableRawPointer" + "jsObject" : { + "_0" : "Foo" + } + }, + "_1" : "null" + } + } + }, + { + "abiName" : "bjs_throwsSwiftError", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "throwsSwiftError", + "parameters" : [ + { + "label" : "shouldThrow", + "name" : "shouldThrow", + "type" : { + "bool" : { + + } } } + ], + "returnType" : { + "void" : { + + } } }, { - "abiName" : "bjs_roundTripOpaquePointer", + "abiName" : "bjs_throwsWithIntResult", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "throwsWithIntResult", + "parameters" : [ + + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "abiName" : "bjs_throwsWithStringResult", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "throwsWithStringResult", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_throwsWithBoolResult", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "throwsWithBoolResult", + "parameters" : [ + + ], + "returnType" : { + "bool" : { + + } + } + }, + { + "abiName" : "bjs_throwsWithFloatResult", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "roundTripOpaquePointer", + "name" : "throwsWithFloatResult", "parameters" : [ - { - "label" : "v", - "name" : "v", - "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "opaquePointer" - } - } - } - } + ], "returnType" : { - "unsafePointer" : { - "_0" : { - "kind" : "opaquePointer" - } + "float" : { + } } }, { - "abiName" : "bjs_roundTripUnsafePointer", + "abiName" : "bjs_throwsWithDoubleResult", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "roundTripUnsafePointer", + "name" : "throwsWithDoubleResult", "parameters" : [ - { - "label" : "v", - "name" : "v", - "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafePointer", - "pointee" : "UInt8" - } - } - } - } + ], "returnType" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafePointer", - "pointee" : "UInt8" - } + "double" : { + } } }, { - "abiName" : "bjs_roundTripUnsafeMutablePointer", + "abiName" : "bjs_throwsWithSwiftHeapObjectResult", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "roundTripUnsafeMutablePointer", + "name" : "throwsWithSwiftHeapObjectResult", "parameters" : [ - { - "label" : "v", - "name" : "v", - "type" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutablePointer", - "pointee" : "UInt8" - } - } - } - } + ], "returnType" : { - "unsafePointer" : { - "_0" : { - "kind" : "unsafeMutablePointer", - "pointee" : "UInt8" - } + "swiftHeapObject" : { + "_0" : "Greeter" } } }, { - "abiName" : "bjs_roundTripJSObject", + "abiName" : "bjs_throwsWithJSObjectResult", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "roundTripJSObject", + "name" : "throwsWithJSObjectResult", "parameters" : [ - { - "label" : "v", - "name" : "v", - "type" : { - "jsObject" : { - } - } - } ], "returnType" : { "jsObject" : { @@ -13217,353 +14200,348 @@ } }, { - "abiName" : "bjs_roundTripDictionaryExport", + "abiName" : "bjs_zeroArgAsyncThrows", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, - "isThrows" : false + "isThrows" : true }, - "name" : "roundTripDictionaryExport", + "name" : "zeroArgAsyncThrows", "parameters" : [ - { - "label" : "v", - "name" : "v", - "type" : { - "dictionary" : { - "_0" : { - "integer" : { - "_0" : { - "isSigned" : true, - "width" : "word" - } - } - } - } - } - } + ], "returnType" : { - "dictionary" : { - "_0" : { - "integer" : { - "_0" : { - "isSigned" : true, - "width" : "word" - } - } - } + "string" : { + } } }, { - "abiName" : "bjs_roundTripOptionalDictionaryExport", + "abiName" : "bjs_asyncRoundTripVoid", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalDictionaryExport", + "name" : "asyncRoundTripVoid", "parameters" : [ - { - "label" : "v", - "name" : "v", - "type" : { - "nullable" : { - "_0" : { - "dictionary" : { - "_0" : { - "string" : { - } - } - } - }, - "_1" : "null" - } - } - } ], "returnType" : { - "nullable" : { - "_0" : { - "dictionary" : { - "_0" : { - "string" : { + "void" : { - } - } - } - }, - "_1" : "null" } } }, { - "abiName" : "bjs_roundTripJSValue", + "abiName" : "bjs_asyncRoundTripInt", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripJSValue", + "name" : "asyncRoundTripInt", "parameters" : [ { "label" : "v", "name" : "v", "type" : { - "jsValue" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } } ], "returnType" : { - "jsValue" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, { - "abiName" : "bjs_roundTripOptionalJSValue", + "abiName" : "bjs_asyncRoundTripFloat", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalJSValue", + "name" : "asyncRoundTripFloat", "parameters" : [ { "label" : "v", "name" : "v", "type" : { - "nullable" : { - "_0" : { - "jsValue" : { + "float" : { - } - }, - "_1" : "null" } } } ], "returnType" : { - "nullable" : { - "_0" : { - "jsValue" : { + "float" : { - } - }, - "_1" : "null" } } }, { - "abiName" : "bjs_roundTripOptionalJSValueArray", + "abiName" : "bjs_asyncRoundTripDouble", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripOptionalJSValueArray", + "name" : "asyncRoundTripDouble", "parameters" : [ { "label" : "v", "name" : "v", "type" : { - "nullable" : { - "_0" : { - "array" : { - "_0" : { - "jsValue" : { + "double" : { - } - } - } - }, - "_1" : "null" } } } ], "returnType" : { - "nullable" : { - "_0" : { - "array" : { - "_0" : { - "jsValue" : { + "double" : { - } - } - } - }, - "_1" : "null" } } }, { - "abiName" : "bjs_makeImportedFoo", + "abiName" : "bjs_asyncRoundTripBool", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, - "isThrows" : true + "isThrows" : false }, - "name" : "makeImportedFoo", + "name" : "asyncRoundTripBool", "parameters" : [ { - "label" : "value", - "name" : "value", + "label" : "v", + "name" : "v", "type" : { - "string" : { + "bool" : { } } } ], "returnType" : { - "jsObject" : { - "_0" : "Foo" + "bool" : { + } } }, { - "abiName" : "bjs_throwsSwiftError", + "abiName" : "bjs_asyncRoundTripString", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, - "isThrows" : true + "isThrows" : false }, - "name" : "throwsSwiftError", + "name" : "asyncRoundTripString", "parameters" : [ { - "label" : "shouldThrow", - "name" : "shouldThrow", + "label" : "v", + "name" : "v", "type" : { - "bool" : { + "string" : { } } } ], "returnType" : { - "void" : { + "string" : { } } }, { - "abiName" : "bjs_throwsWithIntResult", + "abiName" : "bjs_asyncRoundTripSwiftHeapObject", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, - "isThrows" : true + "isThrows" : false }, - "name" : "throwsWithIntResult", + "name" : "asyncRoundTripSwiftHeapObject", "parameters" : [ - + { + "label" : "v", + "name" : "v", + "type" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } + } ], "returnType" : { - "integer" : { - "_0" : { - "isSigned" : true, - "width" : "word" - } + "swiftHeapObject" : { + "_0" : "Greeter" } } }, { - "abiName" : "bjs_throwsWithStringResult", + "abiName" : "bjs_asyncRoundTripJSObject", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, - "isThrows" : true + "isThrows" : false }, - "name" : "throwsWithStringResult", + "name" : "asyncRoundTripJSObject", "parameters" : [ + { + "label" : "v", + "name" : "v", + "type" : { + "jsObject" : { + } + } + } ], "returnType" : { - "string" : { + "jsObject" : { } } }, { - "abiName" : "bjs_throwsWithBoolResult", + "abiName" : "bjs_takeGreeter", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : true + "isThrows" : false }, - "name" : "throwsWithBoolResult", + "name" : "takeGreeter", "parameters" : [ + { + "label" : "g", + "name" : "g", + "type" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } + }, + { + "label" : "name", + "name" : "name", + "type" : { + "string" : { + } + } + } ], "returnType" : { - "bool" : { + "void" : { } } }, { - "abiName" : "bjs_throwsWithFloatResult", + "abiName" : "bjs_createCalculator", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : true + "isThrows" : false }, - "name" : "throwsWithFloatResult", + "name" : "createCalculator", "parameters" : [ ], "returnType" : { - "float" : { - + "swiftHeapObject" : { + "_0" : "Calculator" } } }, { - "abiName" : "bjs_throwsWithDoubleResult", + "abiName" : "bjs_useCalculator", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : true + "isThrows" : false }, - "name" : "throwsWithDoubleResult", + "name" : "useCalculator", "parameters" : [ - + { + "label" : "calc", + "name" : "calc", + "type" : { + "swiftHeapObject" : { + "_0" : "Calculator" + } + } + }, + { + "label" : "x", + "name" : "x", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "label" : "y", + "name" : "y", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } ], "returnType" : { - "double" : { - + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } } } }, { - "abiName" : "bjs_throwsWithSwiftHeapObjectResult", + "abiName" : "bjs_testGreeterToJSValue", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : true + "isThrows" : false }, - "name" : "throwsWithSwiftHeapObjectResult", + "name" : "testGreeterToJSValue", "parameters" : [ ], "returnType" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "jsObject" : { + } } }, { - "abiName" : "bjs_throwsWithJSObjectResult", + "abiName" : "bjs_testCalculatorToJSValue", "effects" : { "isAsync" : false, "isStatic" : false, - "isThrows" : true + "isThrows" : false }, - "name" : "throwsWithJSObjectResult", + "name" : "testCalculatorToJSValue", "parameters" : [ ], @@ -13574,474 +14552,523 @@ } }, { - "abiName" : "bjs_asyncRoundTripVoid", + "abiName" : "bjs_testSwiftClassAsJSValue", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripVoid", + "name" : "testSwiftClassAsJSValue", "parameters" : [ - + { + "label" : "greeter", + "name" : "greeter", + "type" : { + "swiftHeapObject" : { + "_0" : "Greeter" + } + } + } ], "returnType" : { - "void" : { + "jsObject" : { } } }, { - "abiName" : "bjs_asyncRoundTripInt", + "abiName" : "bjs_setDirection", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripInt", + "name" : "setDirection", "parameters" : [ { - "label" : "v", - "name" : "v", + "label" : "_", + "name" : "direction", "type" : { - "integer" : { - "_0" : { - "isSigned" : true, - "width" : "word" - } + "caseEnum" : { + "_0" : "Direction" } } } ], "returnType" : { - "integer" : { - "_0" : { - "isSigned" : true, - "width" : "word" - } + "caseEnum" : { + "_0" : "Direction" } } }, { - "abiName" : "bjs_asyncRoundTripFloat", + "abiName" : "bjs_getDirection", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripFloat", + "name" : "getDirection", "parameters" : [ - { - "label" : "v", - "name" : "v", - "type" : { - "float" : { - } - } - } ], "returnType" : { - "float" : { - + "caseEnum" : { + "_0" : "Direction" } } }, { - "abiName" : "bjs_asyncRoundTripDouble", + "abiName" : "bjs_processDirection", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripDouble", + "name" : "processDirection", "parameters" : [ { - "label" : "v", - "name" : "v", + "label" : "_", + "name" : "input", "type" : { - "double" : { - + "caseEnum" : { + "_0" : "Direction" } } } ], "returnType" : { - "double" : { - + "caseEnum" : { + "_0" : "Status" } } }, { - "abiName" : "bjs_asyncRoundTripBool", + "abiName" : "bjs_setTheme", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripBool", + "name" : "setTheme", "parameters" : [ { - "label" : "v", - "name" : "v", + "label" : "_", + "name" : "theme", "type" : { - "bool" : { - + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" } } } ], "returnType" : { - "bool" : { - + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" } } }, { - "abiName" : "bjs_asyncRoundTripString", + "abiName" : "bjs_getTheme", "effects" : { - "isAsync" : true, + "isAsync" : false, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripString", + "name" : "getTheme", "parameters" : [ - { - "label" : "v", - "name" : "v", - "type" : { - "string" : { - } - } - } ], "returnType" : { - "string" : { - + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" } } }, { - "abiName" : "bjs_asyncRoundTripSwiftHeapObject", + "abiName" : "bjs_asyncRoundTripTheme", "effects" : { "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripSwiftHeapObject", + "name" : "asyncRoundTripTheme", "parameters" : [ { - "label" : "v", + "label" : "_", "name" : "v", "type" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" } } } ], "returnType" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" } } }, { - "abiName" : "bjs_asyncRoundTripJSObject", + "abiName" : "bjs_asyncRoundTripDirection", "effects" : { "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "asyncRoundTripJSObject", + "name" : "asyncRoundTripDirection", "parameters" : [ { - "label" : "v", + "label" : "_", "name" : "v", "type" : { - "jsObject" : { - + "caseEnum" : { + "_0" : "Direction" } } } ], "returnType" : { - "jsObject" : { - + "caseEnum" : { + "_0" : "Direction" } } }, { - "abiName" : "bjs_takeGreeter", + "abiName" : "bjs_asyncRoundTripOptionalTheme", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "takeGreeter", + "name" : "asyncRoundTripOptionalTheme", "parameters" : [ { - "label" : "g", - "name" : "g", - "type" : { - "swiftHeapObject" : { - "_0" : "Greeter" - } - } - }, - { - "label" : "name", - "name" : "name", + "label" : "_", + "name" : "v", "type" : { - "string" : { - + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + }, + "_1" : "null" } } } ], "returnType" : { - "void" : { - + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_createCalculator", + "abiName" : "bjs_asyncRoundTripOptionalDirection", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "createCalculator", + "name" : "asyncRoundTripOptionalDirection", "parameters" : [ - + { + "label" : "_", + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + }, + "_1" : "null" + } + } + } ], "returnType" : { - "swiftHeapObject" : { - "_0" : "Calculator" + "nullable" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_useCalculator", + "abiName" : "bjs_asyncRoundTripDirectionArray", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "useCalculator", + "name" : "asyncRoundTripDirectionArray", "parameters" : [ { - "label" : "calc", - "name" : "calc", - "type" : { - "swiftHeapObject" : { - "_0" : "Calculator" - } - } - }, - { - "label" : "x", - "name" : "x", - "type" : { - "integer" : { - "_0" : { - "isSigned" : true, - "width" : "word" - } - } - } - }, - { - "label" : "y", - "name" : "y", + "label" : "_", + "name" : "v", "type" : { - "integer" : { + "array" : { "_0" : { - "isSigned" : true, - "width" : "word" + "caseEnum" : { + "_0" : "Direction" + } } } } } ], "returnType" : { - "integer" : { + "array" : { "_0" : { - "isSigned" : true, - "width" : "word" + "caseEnum" : { + "_0" : "Direction" + } } } } }, { - "abiName" : "bjs_testGreeterToJSValue", + "abiName" : "bjs_asyncRoundTripDirectionDict", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "testGreeterToJSValue", + "name" : "asyncRoundTripDirectionDict", "parameters" : [ - - ], - "returnType" : { - "jsObject" : { - + { + "label" : "_", + "name" : "v", + "type" : { + "dictionary" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + } + } + } } - } - }, - { - "abiName" : "bjs_testCalculatorToJSValue", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "name" : "testCalculatorToJSValue", - "parameters" : [ - ], "returnType" : { - "jsObject" : { - + "dictionary" : { + "_0" : { + "caseEnum" : { + "_0" : "Direction" + } + } } } }, { - "abiName" : "bjs_testSwiftClassAsJSValue", + "abiName" : "bjs_asyncRoundTripThemeArray", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "testSwiftClassAsJSValue", + "name" : "asyncRoundTripThemeArray", "parameters" : [ { - "label" : "greeter", - "name" : "greeter", + "label" : "_", + "name" : "v", "type" : { - "swiftHeapObject" : { - "_0" : "Greeter" + "array" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + } } } } ], "returnType" : { - "jsObject" : { - + "array" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + } } } }, { - "abiName" : "bjs_setDirection", + "abiName" : "bjs_asyncRoundTripThemeDict", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "setDirection", + "name" : "asyncRoundTripThemeDict", "parameters" : [ { "label" : "_", - "name" : "direction", + "name" : "v", "type" : { - "caseEnum" : { - "_0" : "Direction" + "dictionary" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + } } } } ], "returnType" : { - "caseEnum" : { - "_0" : "Direction" + "dictionary" : { + "_0" : { + "rawValueEnum" : { + "_0" : "Theme", + "_1" : "String" + } + } } } }, { - "abiName" : "bjs_getDirection", + "abiName" : "bjs_asyncRoundTripFileSize", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "getDirection", + "name" : "asyncRoundTripFileSize", "parameters" : [ - + { + "label" : "_", + "name" : "v", + "type" : { + "rawValueEnum" : { + "_0" : "FileSize", + "_1" : "Int64" + } + } + } ], "returnType" : { - "caseEnum" : { - "_0" : "Direction" + "rawValueEnum" : { + "_0" : "FileSize", + "_1" : "Int64" } } }, { - "abiName" : "bjs_processDirection", + "abiName" : "bjs_asyncRoundTripOptionalFileSize", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "processDirection", + "name" : "asyncRoundTripOptionalFileSize", "parameters" : [ { "label" : "_", - "name" : "input", + "name" : "v", "type" : { - "caseEnum" : { - "_0" : "Direction" + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "FileSize", + "_1" : "Int64" + } + }, + "_1" : "null" } } } ], "returnType" : { - "caseEnum" : { - "_0" : "Status" + "nullable" : { + "_0" : { + "rawValueEnum" : { + "_0" : "FileSize", + "_1" : "Int64" + } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_setTheme", + "abiName" : "bjs_asyncRoundTripAssociatedValueEnum", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "setTheme", + "name" : "asyncRoundTripAssociatedValueEnum", "parameters" : [ { "label" : "_", - "name" : "theme", + "name" : "v", "type" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" + "associatedValueEnum" : { + "_0" : "AsyncPayloadResult" } } } ], "returnType" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" + "associatedValueEnum" : { + "_0" : "AsyncPayloadResult" } } }, { - "abiName" : "bjs_getTheme", + "abiName" : "bjs_asyncRoundTripOptionalAssociatedValueEnum", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "getTheme", + "name" : "asyncRoundTripOptionalAssociatedValueEnum", "parameters" : [ - + { + "label" : "_", + "name" : "v", + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "AsyncPayloadResult" + } + }, + "_1" : "null" + } + } + } ], "returnType" : { - "rawValueEnum" : { - "_0" : "Theme", - "_1" : "String" + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "AsyncPayloadResult" + } + }, + "_1" : "null" } } }, @@ -15769,71 +16796,306 @@ "isStatic" : false, "isThrows" : false }, - "name" : "nestedCartToJSObject", + "name" : "nestedCartToJSObject", + "parameters" : [ + { + "label" : "_", + "name" : "cart", + "type" : { + "swiftStruct" : { + "_0" : "CopyableNestedCart" + } + } + } + ], + "returnType" : { + "jsObject" : { + + } + } + }, + { + "abiName" : "bjs_roundTripDataPoint", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripDataPoint", + "parameters" : [ + { + "label" : "_", + "name" : "data", + "type" : { + "swiftStruct" : { + "_0" : "DataPoint" + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "DataPoint" + } + } + }, + { + "abiName" : "bjs_roundTripPublicPoint", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripPublicPoint", + "parameters" : [ + { + "label" : "_", + "name" : "point", + "type" : { + "swiftStruct" : { + "_0" : "PublicPoint" + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "PublicPoint" + } + } + }, + { + "abiName" : "bjs_asyncRoundTripPublicPoint", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncRoundTripPublicPoint", + "parameters" : [ + { + "label" : "_", + "name" : "point", + "type" : { + "swiftStruct" : { + "_0" : "PublicPoint" + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "PublicPoint" + } + } + }, + { + "abiName" : "bjs_asyncRoundTripPublicPointThrows", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "asyncRoundTripPublicPointThrows", + "parameters" : [ + { + "label" : "_", + "name" : "point", + "type" : { + "swiftStruct" : { + "_0" : "PublicPoint" + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "PublicPoint" + } + } + }, + { + "abiName" : "bjs_asyncStructOrThrow", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "asyncStructOrThrow", + "parameters" : [ + { + "label" : "_", + "name" : "shouldThrow", + "type" : { + "bool" : { + + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "PublicPoint" + } + } + }, + { + "abiName" : "bjs_asyncCombinePublicPoints", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncCombinePublicPoints", + "parameters" : [ + { + "label" : "_", + "name" : "a", + "type" : { + "swiftStruct" : { + "_0" : "PublicPoint" + } + } + }, + { + "label" : "_", + "name" : "b", + "type" : { + "swiftStruct" : { + "_0" : "PublicPoint" + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "PublicPoint" + } + } + }, + { + "abiName" : "bjs_asyncRoundTripContact", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncRoundTripContact", + "parameters" : [ + { + "label" : "_", + "name" : "contact", + "type" : { + "swiftStruct" : { + "_0" : "Contact" + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "Contact" + } + } + }, + { + "abiName" : "bjs_asyncRoundTripPublicPointArray", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : false + }, + "name" : "asyncRoundTripPublicPointArray", "parameters" : [ { "label" : "_", - "name" : "cart", + "name" : "points", "type" : { - "swiftStruct" : { - "_0" : "CopyableNestedCart" + "array" : { + "_0" : { + "swiftStruct" : { + "_0" : "PublicPoint" + } + } } } } ], "returnType" : { - "jsObject" : { - + "array" : { + "_0" : { + "swiftStruct" : { + "_0" : "PublicPoint" + } + } } } }, { - "abiName" : "bjs_roundTripDataPoint", + "abiName" : "bjs_asyncRoundTripOptionalPublicPoint", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripDataPoint", + "name" : "asyncRoundTripOptionalPublicPoint", "parameters" : [ { "label" : "_", - "name" : "data", + "name" : "point", "type" : { - "swiftStruct" : { - "_0" : "DataPoint" + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "PublicPoint" + } + }, + "_1" : "null" } } } ], "returnType" : { - "swiftStruct" : { - "_0" : "DataPoint" + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "PublicPoint" + } + }, + "_1" : "null" } } }, { - "abiName" : "bjs_roundTripPublicPoint", + "abiName" : "bjs_asyncRoundTripPublicPointDict", "effects" : { - "isAsync" : false, + "isAsync" : true, "isStatic" : false, "isThrows" : false }, - "name" : "roundTripPublicPoint", + "name" : "asyncRoundTripPublicPointDict", "parameters" : [ { "label" : "_", - "name" : "point", + "name" : "points", "type" : { - "swiftStruct" : { - "_0" : "PublicPoint" + "dictionary" : { + "_0" : { + "swiftStruct" : { + "_0" : "PublicPoint" + } + } } } } ], "returnType" : { - "swiftStruct" : { - "_0" : "PublicPoint" + "dictionary" : { + "_0" : { + "swiftStruct" : { + "_0" : "PublicPoint" + } + } } } }, @@ -16696,44 +17958,6 @@ ], "swiftCallName" : "JSCoordinate" }, - { - "constructor" : { - "abiName" : "bjs_SessionState_init", - "effects" : { - "isAsync" : false, - "isStatic" : false, - "isThrows" : false - }, - "parameters" : [ - { - "label" : "token", - "name" : "token", - "type" : { - "string" : { - - } - } - } - ] - }, - "methods" : [ - - ], - "name" : "SessionState", - "properties" : [ - { - "isReadonly" : true, - "isStatic" : false, - "name" : "token", - "type" : { - "string" : { - - } - } - } - ], - "swiftCallName" : "SessionState" - }, { "methods" : [ @@ -18711,6 +19935,96 @@ } } } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsRoundTripUserId", + "parameters" : [ + { + "name" : "value", + "type" : { + "alias" : { + "name" : "UserId", + "underlying" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + } + } + ], + "returnType" : { + "alias" : { + "name" : "UserId", + "underlying" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsRoundTripOptionalUserId", + "parameters" : [ + { + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "alias" : { + "name" : "UserId", + "underlying" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "alias" : { + "name" : "UserId", + "underlying" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + }, + "_1" : "null" + } + } } ] } @@ -19609,31 +20923,137 @@ "isStatic" : false, "isThrows" : true }, - "name" : "jsAsyncRoundTripStringArray", + "name" : "jsAsyncRoundTripStringArray", + "parameters" : [ + { + "name" : "values", + "type" : { + "array" : { + "_0" : { + "string" : { + + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "string" : { + + } + } + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsAsyncRoundTripFeatureFlag", + "parameters" : [ + { + "name" : "v", + "type" : { + "rawValueEnum" : { + "_0" : "FeatureFlag", + "_1" : "String" + } + } + } + ], + "returnType" : { + "rawValueEnum" : { + "_0" : "FeatureFlag", + "_1" : "String" + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsAsyncRoundTripAssociatedValueEnum", + "parameters" : [ + { + "name" : "v", + "type" : { + "associatedValueEnum" : { + "_0" : "AsyncImportedPayloadResult" + } + } + } + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "AsyncImportedPayloadResult" + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : true, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsAsyncRoundTripOptionalAssociatedValueEnum", "parameters" : [ { - "name" : "values", + "name" : "v", "type" : { - "array" : { + "nullable" : { "_0" : { - "string" : { - + "associatedValueEnum" : { + "_0" : "AsyncImportedPayloadResult" } - } + }, + "_1" : "null" } } } ], "returnType" : { - "array" : { + "nullable" : { "_0" : { - "string" : { - + "associatedValueEnum" : { + "_0" : "AsyncImportedPayloadResult" } - } + }, + "_1" : "null" } } - }, + } + ] + } + ] + }, + { + "functions" : [ + + ], + "types" : [ + { + "accessLevel" : "internal", + "getters" : [ + + ], + "methods" : [ + + ], + "name" : "ClosureAsyncImports", + "setters" : [ + + ], + "staticMethods" : [ { "accessLevel" : "internal", "effects" : { @@ -19641,22 +21061,13 @@ "isStatic" : false, "isThrows" : true }, - "name" : "jsAsyncRoundTripFeatureFlag", + "name" : "runJsClosureAsyncTests", "parameters" : [ - { - "name" : "v", - "type" : { - "rawValueEnum" : { - "_0" : "FeatureFlag", - "_1" : "String" - } - } - } + ], "returnType" : { - "rawValueEnum" : { - "_0" : "FeatureFlag", - "_1" : "String" + "void" : { + } } } @@ -20485,6 +21896,45 @@ { "functions" : [ + ], + "types" : [ + { + "accessLevel" : "internal", + "getters" : [ + + ], + "methods" : [ + + ], + "name" : "ClosureThrowsImports", + "setters" : [ + + ], + "staticMethods" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "runJsClosureThrowsTests", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + } + ] + } + ] + }, + { + "functions" : [ + ], "types" : [ { @@ -21047,23 +22497,6 @@ } } }, - { - "accessLevel" : "internal", - "effects" : { - "isAsync" : true, - "isStatic" : false, - "isThrows" : true - }, - "name" : "runAliasAsyncWorks", - "parameters" : [ - - ], - "returnType" : { - "void" : { - - } - } - }, { "accessLevel" : "internal", "effects" : { @@ -21615,6 +23048,95 @@ } ] }, + { + "functions" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsRoundTripLightColor", + "parameters" : [ + { + "name" : "value", + "type" : { + "caseEnum" : { + "_0" : "LightColor" + } + } + } + ], + "returnType" : { + "caseEnum" : { + "_0" : "LightColor" + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsRoundTripImportedPayloadSignal", + "parameters" : [ + { + "name" : "value", + "type" : { + "associatedValueEnum" : { + "_0" : "ImportedPayloadSignal" + } + } + } + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "ImportedPayloadSignal" + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsRoundTripOptionalImportedPayloadSignal", + "parameters" : [ + { + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "ImportedPayloadSignal" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "associatedValueEnum" : { + "_0" : "ImportedPayloadSignal" + } + }, + "_1" : "null" + } + } + } + ], + "types" : [ + + ] + }, { "functions" : [ { @@ -21662,6 +23184,40 @@ "_0" : "Point" } } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsRoundTripOptionalPoint", + "parameters" : [ + { + "name" : "point", + "type" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "Point" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "Point" + } + }, + "_1" : "null" + } + } } ], "types" : [ @@ -22929,6 +24485,40 @@ } } }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsRoundTripOptionalJSObjectNull", + "parameters" : [ + { + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "jsObject" : { + + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "jsObject" : { + + } + }, + "_1" : "null" + } + } + }, { "accessLevel" : "internal", "effects" : { diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/AliasTests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/AliasTests.mjs index db6225b21..af5fe8cc8 100644 --- a/Tests/BridgeJSRuntimeTests/JavaScript/AliasTests.mjs +++ b/Tests/BridgeJSRuntimeTests/JavaScript/AliasTests.mjs @@ -31,6 +31,12 @@ export function getImports(importsContext) { jsRoundTripCoordinate: (value) => { return { ...value }; }, + jsRoundTripUserId: (value) => { + return value; + }, + jsRoundTripOptionalUserId: (value) => { + return value ?? null; + }, }; } @@ -45,21 +51,17 @@ export function runAliasWorks(exports) { runMultipleAliases(exports); runArrays(exports); runThrows(exports); - runNonCopyable(exports); + runJSValueAlias(exports); + runScalarAlias(exports); runClosureWithAliasParameter(exports); runOptionalInArray(exports); runClassPropertyAndInitWithAlias(exports); runAssociatedValueEnumPayload(exports); runStructToStructAlias(exports); runStructToEnumAlias(exports); - runClassToStructAlias(exports); runEnumToClassAlias(exports); } -export async function runAliasAsyncWorks(exports) { - await runAsyncReturningAlias(exports); -} - /** * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports */ @@ -194,15 +196,28 @@ function runThrows(exports) { /** * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports */ -function runNonCopyable(exports) { - const seed = exports.makeToken(7); - assert.equal(seed.read(), 7); +function runJSValueAlias(exports) { + assert.equal(exports.roundTripBoxed(42), 42); + assert.equal(exports.roundTripBoxed("hello"), "hello"); + assert.deepStrictEqual(exports.roundTripBoxed({ a: 1 }), { a: 1 }); - const next = exports.incrementToken(seed); - assert.equal(next.read(), 8); + assert.equal(exports.roundTripOptionalBoxed(null), null); + assert.equal(exports.roundTripOptionalBoxed("present"), "present"); +} - next.release(); - seed.release(); +/** + * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports + */ +function runScalarAlias(exports) { + assert.equal(exports.roundTripUserId(42), 42); + assert.equal(exports.roundTripUserId(-1), -1); + + assert.equal(exports.roundTripOptionalUserId(null), null); + assert.equal(exports.roundTripOptionalUserId(0), 0); + assert.equal(exports.roundTripOptionalUserId(7), 7); + + assert.deepStrictEqual(exports.roundTripUserIdArray([]), []); + assert.deepStrictEqual(exports.roundTripUserIdArray([1, 2, 3]), [1, 2, 3]); } /** @@ -319,17 +334,6 @@ function runStructToEnumAlias(exports) { assert.equal(echoed, exports.Severity.Error); } -/** - * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports - */ -function runClassToStructAlias(exports) { - const made = exports.makeSession("hello"); - assert.deepStrictEqual(made, { token: "hello" }); - - const echoed = exports.roundTripSession({ token: "world" }); - assert.deepStrictEqual(echoed, { token: "world" }); -} - /** * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports */ @@ -345,13 +349,3 @@ function runEnumToClassAlias(exports) { seed.release(); echoed.release(); } - -/** - * @param {import('../../../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.d.ts').Exports} exports - */ -async function runAsyncReturningAlias(exports) { - const result = await exports.asyncMakePolygon("async"); - assert.equal(result.vertexCount(), 2); - assert.equal(result.summary(), "async(2)"); - result.release(); -} diff --git a/Tests/BridgeJSRuntimeTests/bridge-js.d.ts b/Tests/BridgeJSRuntimeTests/bridge-js.d.ts index 582113df1..9fef391c1 100644 --- a/Tests/BridgeJSRuntimeTests/bridge-js.d.ts +++ b/Tests/BridgeJSRuntimeTests/bridge-js.d.ts @@ -26,8 +26,6 @@ export class JsGreeter { export function runAsyncWorks(): Promise; -export function runAliasAsyncWorks(): Promise; - export interface WeatherData { temperature: number; description: string; diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index 5b6f8b39f..f431209dd 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -5,7 +5,7 @@ import { } from '../.build/plugins/PackageToJS/outputs/PackageTests/bridge-js.js'; import { ImportedFoo } from './BridgeJSRuntimeTests/JavaScript/Types.mjs'; import { runJsOptionalSupportTests } from './BridgeJSRuntimeTests/JavaScript/OptionalSupportTests.mjs'; -import { runAliasWorks, runAliasAsyncWorks, getImports as getAliasImports, Surface } from './BridgeJSRuntimeTests/JavaScript/AliasTests.mjs'; +import { runAliasWorks, getImports as getAliasImports, Surface } from './BridgeJSRuntimeTests/JavaScript/AliasTests.mjs'; import { getImports as getClosureSupportImports } from './BridgeJSRuntimeTests/JavaScript/ClosureSupportTests.mjs'; import { getImports as getClosureThrowsImports } from './BridgeJSRuntimeTests/JavaScript/ClosureThrowsTests.mjs'; import { getImports as getClosureAsyncImports } from './BridgeJSRuntimeTests/JavaScript/ClosureAsyncTests.mjs'; @@ -143,14 +143,6 @@ export async function setupOptions(options, context) { await runAsyncWorksTests(exports); return; }, - runAliasAsyncWorks: async () => { - const exports = importsContext.getExports(); - if (!exports) { - throw new Error("No exports!?"); - } - await runAliasAsyncWorks(exports); - return; - }, AsyncImportImports: getAsyncImportImports(importsContext), fetchWeatherData: (city) => { return Promise.resolve({ From 76d11c0738f2abe8d15cff981e910d32b9c0845e Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Wed, 24 Jun 2026 11:51:57 +0200 Subject: [PATCH 23/50] BridgeJS: Address @JS(as:) review feedback Follow-up to the review on #750: - ImportTS: give the unreachable `.alias` cases in loweringParameterInfo / liftingReturnInfo a message stating the `.unaliased` invariant, so a future change that breaks it fails loudly instead of trapping silently. - JSGlueGen: in `optionalConvention` and `wasmParams`, delegate `.alias` to its underlying type rather than `preconditionFailure()`. These switch on `self` (not `.unaliased`), so this removes a latent crash for alias-wrapped values and matches how abiReturnType / mangleTypeName already handle `.alias`. - SwiftToSkeleton: diagnose `@JS(as:)` combined with `namespace:` instead of silently dropping the namespace; an alias adopts its representation's placement. Adds a diagnostics test. - BridgeJSSkeleton: note why alias mangling uses the (unique) swiftCallName only. - Docs: add an "Exporting a Type With a Custom JS Representation" article and link it from the exporting topics. --- .../Sources/BridgeJSCore/ImportTS.swift | 4 +- .../BridgeJSCore/SwiftToSkeleton.swift | 17 ++- .../Sources/BridgeJSLink/JSGlueGen.swift | 8 +- .../BridgeJSSkeleton/BridgeJSSkeleton.swift | 2 + .../BridgeJSToolTests/DiagnosticsTests.swift | 21 ++++ .../BridgeJSCodegenTests/DocComments.json | 3 + .../__Snapshots__/BridgeJSLinkTests/Alias.js | 5 +- .../BridgeJSLinkTests/AliasInClosure.js | 7 +- .../BridgeJSLinkTests/EnumAlias.js | 5 +- .../BridgeJS/Exporting-Swift-to-JavaScript.md | 1 + .../Exporting-Swift-Custom-Representation.md | 114 ++++++++++++++++++ 11 files changed, 171 insertions(+), 16 deletions(-) create mode 100644 Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Custom-Representation.md diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift index c15d974f8..7a37b17f0 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift @@ -958,7 +958,7 @@ extension BridgeType { case .array, .dictionary: return LoweringParameterInfo(loweredParameters: []) case .alias: - preconditionFailure() + preconditionFailure("`.alias` must be resolved by `.unaliased` before reaching loweringParameterInfo") } } @@ -1032,7 +1032,7 @@ extension BridgeType { case .array, .dictionary: return LiftingReturnInfo(valueToLift: nil) case .alias: - preconditionFailure() + preconditionFailure("`.alias` must be resolved by `.unaliased` before reaching liftingReturnInfo") } } } diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index 36ff44cbc..5b5155fdc 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -1635,7 +1635,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { } if let aliasTarget = parent.extractAliasTarget(from: jsAttribute) { - recordAlias(node: node, aliasTarget: aliasTarget) + recordAlias(node: node, jsAttribute: jsAttribute, aliasTarget: aliasTarget) return .skipChildren } @@ -1739,9 +1739,20 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { private func recordAlias( node: some SyntaxProtocol & NamedDeclSyntax, + jsAttribute: AttributeSyntax, aliasTarget: TypeSyntax ) { let swiftCallName = SwiftToSkeleton.computeSwiftCallName(for: node, itemName: node.name.text) + if extractNamespace(from: jsAttribute) != nil { + errors.append( + DiagnosticError( + node: node, + message: "`namespace` is not supported on `@JS(as:)` types", + hint: "Remove the `namespace:` argument; an alias adopts its target's representation" + ) + ) + return + } var lookupErrors: [DiagnosticError] = [] guard let aliasBridgeType = parent.aliasType( @@ -1774,7 +1785,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { } if let aliasTarget = parent.extractAliasTarget(from: jsAttribute) { - recordAlias(node: node, aliasTarget: aliasTarget) + recordAlias(node: node, jsAttribute: jsAttribute, aliasTarget: aliasTarget) return .skipChildren } @@ -1962,7 +1973,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { } if let aliasTarget = parent.extractAliasTarget(from: jsAttribute) { - recordAlias(node: node, aliasTarget: aliasTarget) + recordAlias(node: node, jsAttribute: jsAttribute, aliasTarget: aliasTarget) return .skipChildren } diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift index a94c780ed..6e7bd7628 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift @@ -2685,8 +2685,8 @@ private extension BridgeType { return .stackABI case .nullable(let wrapped, _): return wrapped.optionalConvention - case .alias: - preconditionFailure() + case .alias(_, let underlying): + return underlying.optionalConvention } } @@ -2783,8 +2783,8 @@ private extension BridgeType { return [] case .nullable(let wrapped, _): return wrapped.wasmParams - case .alias: - preconditionFailure() + case .alias(_, let underlying): + return underlying.wasmParams } } diff --git a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift index d2c506e6a..7f45b6c39 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift @@ -1770,6 +1770,8 @@ extension BridgeType { // Dictionary mangling: "SD" prefix followed by value type (key is always String) return "SD\(valueType.mangleTypeName)" case .alias(let name, _): + // `name` is the namespace-qualified swiftCallName (unique), so the underlying + // representation isn't mangled in - aliases bridge via their JS type's ABI. return "Al\(name.count)\(name)" } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift index 2db9ac2d7..79ea47ebd 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift @@ -426,6 +426,27 @@ import Testing } } + @Test + func jsAsWithNamespaceDiagnostic() throws { + let source = """ + @JS final class Box { @JS init() {} } + @JS(as: Box.self, namespace: "Foo") struct Wrapped { + consuming func bridgeToJS() -> Box { fatalError() } + static func bridgeFromJS(_ value: consuming Box) -> Wrapped { fatalError() } + } + """ + let swiftAPI = SwiftToSkeleton( + progress: .silent, + moduleName: "TestModule", + exposeToGlobal: false, + externalModuleIndex: .empty + ) + swiftAPI.addSourceFile(Parser.parse(source: source), inputFilePath: "test.swift") + #expect(throws: BridgeJSCoreDiagnosticError.self) { + _ = try swiftAPI.finalize() + } + } + @Test func omitsNextLineWhenErrorIsOnLastLine() throws { let source = """ diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DocComments.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DocComments.json index c69fca509..ce4a2190a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DocComments.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DocComments.json @@ -1,5 +1,8 @@ { "exported" : { + "aliases" : [ + + ], "classes" : [ { "constructor" : { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js index a24c0754b..8f9511e86 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js @@ -78,14 +78,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } @@ -345,6 +345,7 @@ export async function createInstantiator(options, swift) { /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; const makeFresh = (identityMap) => { const obj = Object.create(prototype); const state = { pointer, deinit, hasReleased: false, identityMap }; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js index dc6e6ccd3..bc7575fbc 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js @@ -39,7 +39,7 @@ export async function createInstantiator(options, swift) { const state = { pointer, file, line, unregistered: false }; const real = (...args) => { if (state.unregistered) { - const bytes = new Uint8Array(memory.buffer, state.file); + const bytes = new Uint8Array(memory.buffer, state.file >>> 0); let length = 0; while (bytes[length] !== 0) { length += 1; } const fileID = decodeString(state.file, length); @@ -70,14 +70,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } @@ -312,6 +312,7 @@ export async function createInstantiator(options, swift) { /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; const makeFresh = (identityMap) => { const obj = Object.create(prototype); const state = { pointer, deinit, hasReleased: false, identityMap }; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js index 2a2e89f8c..ccf57601b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js @@ -45,14 +45,14 @@ export async function createInstantiator(options, swift) { bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { const source = swift.memory.getObject(sourceId); swift.memory.release(sourceId); - const bytes = new Uint8Array(memory.buffer, bytesPtr); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); bytes.set(source); } bjs["swift_js_make_js_string"] = function(ptr, len) { return swift.memory.retain(decodeString(ptr, len)); } bjs["swift_js_init_memory_with_result"] = function(ptr, len) { - const target = new Uint8Array(memory.buffer, ptr, len); + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); target.set(tmpRetBytes); tmpRetBytes = undefined; } @@ -237,6 +237,7 @@ export async function createInstantiator(options, swift) { /// Represents a Swift heap object like a class instance or an actor instance. class SwiftHeapObject { static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; const makeFresh = (identityMap) => { const obj = Object.create(prototype); const state = { pointer, deinit, hasReleased: false, identityMap }; diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift-to-JavaScript.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift-to-JavaScript.md index b14d2eebe..38a47ffdc 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift-to-JavaScript.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift-to-JavaScript.md @@ -22,6 +22,7 @@ Configure your package and build for JavaScript as described in - - +- - - - diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Custom-Representation.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Custom-Representation.md new file mode 100644 index 000000000..7d3826e01 --- /dev/null +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Custom-Representation.md @@ -0,0 +1,114 @@ +# Exporting a Type With a Custom JS Representation + +Learn how to give a Swift type a different representation on the JavaScript side using `@JS(as:)`. + +## Overview + +> Tip: You can quickly preview what interfaces will be exposed on the Swift/JavaScript/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). + +BridgeJS picks a sensible default representation for each exported type - structs cross by copy, classes by reference, and so on. Sometimes that default is a poor fit: + +- A struct copied at the boundary is expensive when it holds a large payload (for example a polygon with thousands of vertices). +- A type uses a feature BridgeJS does not export directly (for example a dictionary with integer keys). + +`@JS(as:)` is the escape hatch. It lets a Swift type keep its idiomatic shape while being bridged to JavaScript through a different `@JS` type that you control, without duplicating the surrounding API. + +Mark the type with `@JS(as: OtherType.self)` and provide two conversions: + +```swift +import JavaScriptKit + +@JS(as: JSPolygon.self) struct Polygon { + var vertices: [Point] + + consuming func bridgeToJS() -> JSPolygon { + JSPolygon(underlying: self) + } + + static func bridgeFromJS(_ value: consuming JSPolygon) -> Polygon { + value.underlying + } +} + +@JS final class JSPolygon { + var underlying: Polygon + + @JS init(underlying: Polygon) { + self.underlying = underlying + } + + @JS var vertexCount: Int { underlying.vertices.count } +} + +@JS func merge(_ a: Polygon, _ b: Polygon) -> Polygon +``` + +Existing Swift code keeps using the idiomatic `Polygon`. Anywhere `Polygon` crosses the boundary - parameters, return values, optionals, arrays - BridgeJS substitutes `JSPolygon`, so JavaScript sees the reference type and avoids copying. + +The generated TypeScript declarations refer to the representation type: + +```typescript +export interface JSPolygon extends SwiftHeapObject { + readonly vertexCount: number; +} + +export type Exports = { + JSPolygon: { + new(underlying: JSPolygon): JSPolygon; + } + merge(a: JSPolygon, b: JSPolygon): JSPolygon; +} +``` + +## The Bridging Contract + +A type marked `@JS(as: R.self)` must provide both halves of the conversion to and from its representation `R`: + +```swift +consuming func bridgeToJS() -> R +static func bridgeFromJS(_ value: consuming R) -> Self +``` + +BridgeJS inserts a call to `bridgeToJS()` at the first opportunity when a value leaves Swift, and `bridgeFromJS(_:)` at the last opportunity when one enters. The rest of the generated glue just uses `R`'s ABI, so the conversions are the only code you write. + +## Wrapping a Primitive + +The representation does not have to be a class. A small wrapper over a primitive is a common case - for example exposing a strongly-typed identifier as a plain string: + +```swift +@JS(as: String.self) struct UUID { + var rawValue: String + + consuming func bridgeToJS() -> String { rawValue } + static func bridgeFromJS(_ value: consuming String) -> UUID { UUID(rawValue: value) } +} + +@JS func currentUser() -> UUID +``` + +JavaScript sees a `string`, while Swift keeps the distinct `UUID` type. + +## Supported Representations + +The representation type (the `as:` target) must itself be a type BridgeJS can export by value or reference: + +| Representation | Status | +|:---------------|:-------| +| `@JS class` | ✅ | +| `@JSClass` (imported) | ✅ | +| `@JS struct` | ✅ | +| Primitives (`Int`, `Double`, `Float`, `Bool`, `String`) | ✅ | +| `JSValue` | ✅ | +| Case enums and associated-value enums | ✅ | +| Raw-value enums | ❌ | +| `@JS protocol` | ❌ | +| Another `@JS(as:)` type (chained aliases) | ❌ | +| Closures, arrays, dictionaries, optionals as the direct target | ❌ | + +`@JS(as:)` cannot be combined with `namespace:` - an aliased type adopts its representation's placement. + +## See Also + +- +- +- From 84624af11aa737e607a0ae1369865f76925a0167 Mon Sep 17 00:00:00 2001 From: William Taylor Date: Tue, 30 Jun 2026 09:55:30 +1000 Subject: [PATCH 24/50] BridgeJS: Merge nested types correctly --- .../Sources/BridgeJSLink/BridgeJSLink.swift | 565 ++++++++++-------- .../MacroSwift/ClassWithNestedTypes.swift | 34 ++ .../MacroSwift/StructWithNestedTypes.swift | 52 ++ .../ClassWithNestedTypes.json | 218 +++++++ .../ClassWithNestedTypes.swift | 177 ++++++ .../StructWithNestedTypes.json | 337 +++++++++++ .../StructWithNestedTypes.swift | 249 ++++++++ .../BridgeJSLinkTests/Alias.d.ts | 14 +- .../__Snapshots__/BridgeJSLinkTests/Alias.js | 4 +- .../BridgeJSLinkTests/AliasInClosure.d.ts | 6 +- .../BridgeJSLinkTests/AliasInClosure.js | 2 +- .../BridgeJSLinkTests/ArrayTypes.d.ts | 10 +- .../BridgeJSLinkTests/ArrayTypes.js | 4 +- .../ClassWithNestedTypes.d.ts | 51 ++ .../BridgeJSLinkTests/ClassWithNestedTypes.js | 375 ++++++++++++ .../BridgeJSLinkTests/DefaultParameters.d.ts | 34 +- .../BridgeJSLinkTests/DefaultParameters.js | 6 +- .../BridgeJSLinkTests/DictionaryTypes.d.ts | 4 +- .../BridgeJSLinkTests/DictionaryTypes.js | 2 +- .../BridgeJSLinkTests/DocComments.d.ts | 14 +- .../BridgeJSLinkTests/DocComments.js | 2 +- .../BridgeJSLinkTests/EnumAlias.d.ts | 4 +- .../BridgeJSLinkTests/EnumAlias.js | 2 +- .../EnumAssociatedValue.d.ts | 4 +- .../BridgeJSLinkTests/EnumAssociatedValue.js | 2 +- .../EnumNamespace.Global.d.ts | 32 +- .../BridgeJSLinkTests/EnumNamespace.Global.js | 4 +- .../BridgeJSLinkTests/EnumNamespace.d.ts | 12 +- .../BridgeJSLinkTests/EnumNamespace.js | 4 +- .../IdentityModeClass.ConfigPointer.d.ts | 10 +- .../IdentityModeClass.ConfigPointer.js | 2 +- .../IdentityModeClass.PerClass.d.ts | 10 +- .../IdentityModeClass.PerClass.js | 2 +- .../BridgeJSLinkTests/IdentityModeClass.d.ts | 10 +- .../BridgeJSLinkTests/IdentityModeClass.js | 2 +- .../BridgeJSLinkTests/JSValue.d.ts | 6 +- .../BridgeJSLinkTests/JSValue.js | 2 +- .../BridgeJSLinkTests/MixedGlobal.d.ts | 4 +- .../BridgeJSLinkTests/MixedGlobal.js | 2 +- .../BridgeJSLinkTests/MixedModules.d.ts | 10 +- .../BridgeJSLinkTests/MixedModules.js | 4 +- .../BridgeJSLinkTests/MixedPrivate.d.ts | 4 +- .../BridgeJSLinkTests/MixedPrivate.js | 2 +- .../BridgeJSLinkTests/Namespaces.Global.d.ts | 8 +- .../BridgeJSLinkTests/Namespaces.d.ts | 8 +- .../BridgeJSLinkTests/NestedType.d.ts | 6 +- .../BridgeJSLinkTests/NestedType.js | 6 +- .../BridgeJSLinkTests/Optionals.d.ts | 12 +- .../BridgeJSLinkTests/Optionals.js | 4 +- .../BridgeJSLinkTests/PropertyTypes.d.ts | 6 +- .../BridgeJSLinkTests/PropertyTypes.js | 2 +- .../BridgeJSLinkTests/Protocol.d.ts | 18 +- .../BridgeJSLinkTests/Protocol.js | 6 +- .../BridgeJSLinkTests/ProtocolInClosure.d.ts | 6 +- .../BridgeJSLinkTests/ProtocolInClosure.js | 2 +- .../StaticFunctions.Global.d.ts | 6 +- .../StaticFunctions.Global.js | 2 +- .../BridgeJSLinkTests/StaticFunctions.d.ts | 6 +- .../BridgeJSLinkTests/StaticFunctions.js | 2 +- .../StaticProperties.Global.d.ts | 4 +- .../StaticProperties.Global.js | 2 +- .../BridgeJSLinkTests/StaticProperties.d.ts | 4 +- .../BridgeJSLinkTests/StaticProperties.js | 2 +- .../StructWithNestedTypes.d.ts | 73 +++ .../StructWithNestedTypes.js | 364 +++++++++++ .../BridgeJSLinkTests/SwiftClass.d.ts | 10 +- .../BridgeJSLinkTests/SwiftClass.js | 6 +- .../BridgeJSLinkTests/SwiftClosure.d.ts | 14 +- .../BridgeJSLinkTests/SwiftClosure.js | 4 +- .../BridgeJSLinkTests/SwiftStruct.d.ts | 18 +- .../BridgeJSLinkTests/SwiftStruct.js | 42 +- .../BridgeJSLinkTests/UnsafePointer.d.ts | 2 +- .../BridgeJSRuntimeTests/ExportAPITests.swift | 21 + .../Generated/BridgeJS.swift | 113 ++++ .../Generated/JavaScript/BridgeJS.json | 111 ++++ Tests/prelude.mjs | 8 + 76 files changed, 2706 insertions(+), 486 deletions(-) create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ClassWithNestedTypes.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/StructWithNestedTypes.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ClassWithNestedTypes.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ClassWithNestedTypes.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StructWithNestedTypes.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StructWithNestedTypes.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.d.ts create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.js create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.d.ts create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.js diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index ed9eb950f..4706b14a4 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -168,7 +168,6 @@ public struct BridgeJSLink { var classLines: [String] = [] var dtsExportLines: [String] = [] var dtsClassLines: [String] = [] - var namespacedClassDtsExportEntries: [String: [String]] = [:] var topLevelTypeLines: [String] = [] var topLevelDtsTypeLines: [String] = [] var importObjectBuilders: [ImportObjectBuilder] = [] @@ -198,16 +197,9 @@ public struct BridgeJSLink { guard let skeleton = unified.exported else { continue } // Process classes for klass in skeleton.classes { - let (jsType, dtsType, dtsExportEntry) = try renderExportedClass(klass) + let (jsType, dtsType) = try renderExportedClass(klass) data.classLines.append(contentsOf: jsType) data.dtsClassLines.append(contentsOf: dtsType) - - if klass.namespace == nil { - data.exportsLines.append("\(klass.name),") - data.dtsExportLines.append(contentsOf: dtsExportEntry) - } else { - data.namespacedClassDtsExportEntries[klass.name] = dtsExportEntry - } } // Process enums - collect top-level definitions and export entries @@ -230,16 +222,10 @@ public struct BridgeJSLink { } } - var structExportEntries: [(js: [String], dts: [String])] = [] - for structDefinition in skeleton.structs { - let (jsStruct, dtsType, dtsExportEntry) = try renderExportedStruct(structDefinition) - if structDefinition.namespace == nil { - data.topLevelDtsTypeLines.append(contentsOf: dtsType) - } - - if structDefinition.namespace == nil && (!jsStruct.isEmpty || !dtsExportEntry.isEmpty) { - structExportEntries.append((js: jsStruct, dts: dtsExportEntry)) - } + for structDefinition in skeleton.structs where structDefinition.namespace == nil { + data.topLevelDtsTypeLines.append( + contentsOf: renderExportedStructInterface(structDefinition) + ) } // Process functions @@ -257,11 +243,6 @@ public struct BridgeJSLink { data.exportsLines.append(contentsOf: entry.js) data.dtsExportLines.append(contentsOf: entry.dts) } - - for entry in structExportEntries { - data.exportsLines.append(contentsOf: entry.js) - data.dtsExportLines.append(contentsOf: entry.dts) - } } // Process imported skeletons @@ -1014,6 +995,12 @@ public struct BridgeJSLink { }, renderDocCallback: { documentation, parameters in self.renderJSDoc(documentation: documentation, parameters: parameters) + }, + renderStructInterface: { structDef in + self.renderExportedStructInterface(structDef) + }, + renderClassDeclaration: { klass in + self.renderExportedClassDeclaration(klass) } ) printer.write(lines: namespaceDeclarationsLines) @@ -1027,7 +1014,10 @@ public struct BridgeJSLink { let hierarchicalExportLines = namespaceBuilder.buildHierarchicalExportsType( exportedSkeletons: exportedSkeletons, renderClassEntry: { klass in - data.namespacedClassDtsExportEntries[klass.name] ?? [] + self.renderExportedClassExportEntryBody(klass) + }, + renderStructEntry: { structDef in + self.renderExportedStructExportEntry(structDef) }, renderFunctionEntry: { function in self.renderJSDoc(documentation: function.documentation, parameters: function.parameters) @@ -1341,6 +1331,9 @@ public struct BridgeJSLink { renderFunctionImpl: { function in let (js, _) = try self.renderExportedFunction(function: function) return js + }, + renderStructImpl: { structDef in + try self.renderExportedStructJsBody(structDef) } ) printer.write(lines: hierarchicalLines) @@ -1599,22 +1592,16 @@ public struct BridgeJSLink { .replacingOccurrences(of: "\"", with: "\\\"") } - func renderExportedStruct( + func renderExportedStructInterface( _ structDefinition: ExportedStruct - ) throws -> (js: [String], dtsType: [String], dtsExportEntry: [String]) { - let structName = structDefinition.name - let hasConstructor = structDefinition.constructor != nil - let staticMethods = structDefinition.methods.filter { $0.effects.isStatic } - let staticProperties = structDefinition.properties.filter { $0.isStatic } - + ) -> [String] { let dtsTypePrinter = CodeFragmentPrinter() for line in renderJSDoc(documentation: structDefinition.documentation, parameters: []) { dtsTypePrinter.write(line) } - dtsTypePrinter.write("export interface \(structName) {") - let instanceProps = structDefinition.properties.filter { !$0.isStatic } + dtsTypePrinter.write("export interface \(structDefinition.name) {") dtsTypePrinter.indent { - for property in instanceProps { + for property in structDefinition.properties where !property.isStatic { let tsType = resolveTypeScriptType(property.type) for line in renderJSDoc(documentation: property.documentation, parameters: []) { dtsTypePrinter.write(line) @@ -1636,87 +1623,78 @@ public struct BridgeJSLink { } } dtsTypePrinter.write("}") + return dtsTypePrinter.lines + } - guard hasConstructor || !staticMethods.isEmpty || !staticProperties.isEmpty else { - return (js: [], dtsType: dtsTypePrinter.lines, dtsExportEntry: []) + func renderExportedStructExportEntry( + _ structDefinition: ExportedStruct + ) -> [String] { + let dtsExportEntryPrinter = CodeFragmentPrinter() + if let constructor = structDefinition.constructor { + let jsDocLines = renderJSDoc(documentation: constructor.documentation, parameters: constructor.parameters) + dtsExportEntryPrinter.write(lines: jsDocLines) + dtsExportEntryPrinter.write( + "init\(renderTSSignature(parameters: constructor.parameters, returnType: .swiftStruct(structDefinition.swiftCallName), effects: constructor.effects));" + ) + } + for property in structDefinition.properties where property.isStatic { + let readonly = property.isReadonly ? "readonly " : "" + dtsExportEntryPrinter.write(lines: renderJSDoc(documentation: property.documentation, parameters: [])) + dtsExportEntryPrinter.write("\(readonly)\(property.name): \(resolveTypeScriptType(property.type));") + } + for method in structDefinition.methods where method.effects.isStatic { + let jsDocLines = renderJSDoc(documentation: method.documentation, parameters: method.parameters) + dtsExportEntryPrinter.write(lines: jsDocLines) + dtsExportEntryPrinter.write( + "\(method.name)\(renderTSSignature(parameters: method.parameters, returnType: method.returnType, effects: method.effects));" + ) } - let jsPrinter = CodeFragmentPrinter() - jsPrinter.write("\(structName): {") - try jsPrinter.indent { - // Constructor as 'init' function - if let constructor = structDefinition.constructor { - let thunkBuilder = ExportedThunkBuilder( - effects: constructor.effects, - intrinsicRegistry: intrinsicRegistry - ) - for param in constructor.parameters { - try thunkBuilder.lowerParameter(param: param) - } - let returnExpr = try thunkBuilder.call( - abiName: constructor.abiName, - returnType: .swiftStruct(structDefinition.swiftCallName) - ) + return dtsExportEntryPrinter.lines + } - let constructorPrinter = CodeFragmentPrinter() - let paramList = DefaultValueUtils.formatParameterList(constructor.parameters) - constructorPrinter.write("init: function(\(paramList)) {") - constructorPrinter.indent { - thunkBuilder.renderFunctionBody(into: constructorPrinter, returnExpr: returnExpr) - } - constructorPrinter.write("},") - jsPrinter.write(lines: constructorPrinter.lines) + func renderExportedStructJsBody( + _ structDefinition: ExportedStruct + ) throws -> [String] { + let jsPrinter = CodeFragmentPrinter() + // Constructor as 'init' function + if let constructor = structDefinition.constructor { + let thunkBuilder = ExportedThunkBuilder( + effects: constructor.effects, + intrinsicRegistry: intrinsicRegistry + ) + for param in constructor.parameters { + try thunkBuilder.lowerParameter(param: param) } + let returnExpr = try thunkBuilder.call( + abiName: constructor.abiName, + returnType: .swiftStruct(structDefinition.swiftCallName) + ) - for property in staticProperties { - let propertyLines = try renderStaticPropertyForExportObject( - property: property, - className: structName - ) - jsPrinter.write(lines: propertyLines) + let constructorPrinter = CodeFragmentPrinter() + let paramList = DefaultValueUtils.formatParameterList(constructor.parameters) + constructorPrinter.write("init: function(\(paramList)) {") + constructorPrinter.indent { + thunkBuilder.renderFunctionBody(into: constructorPrinter, returnExpr: returnExpr) } + constructorPrinter.write("},") + jsPrinter.write(lines: constructorPrinter.lines) + } - for method in staticMethods { - let methodLines = try renderStaticMethodForExportObject(method: method) - jsPrinter.write(lines: methodLines) - } + for property in structDefinition.properties where property.isStatic { + let propertyLines = try renderStaticPropertyForExportObject( + property: property, + className: structDefinition.name + ) + jsPrinter.write(lines: propertyLines) } - jsPrinter.write("},") - let dtsExportEntryPrinter = CodeFragmentPrinter() - dtsExportEntryPrinter.write("\(structName): {") - dtsExportEntryPrinter.indent { - if let constructor = structDefinition.constructor { - let jsDocLines = renderJSDoc( - documentation: constructor.documentation, - parameters: constructor.parameters - ) - dtsExportEntryPrinter.write(lines: jsDocLines) - dtsExportEntryPrinter.write( - "init\(renderTSSignature(parameters: constructor.parameters, returnType: .swiftStruct(structDefinition.swiftCallName), effects: constructor.effects));" - ) - } - for property in staticProperties { - let readonly = property.isReadonly ? "readonly " : "" - for line in renderJSDoc(documentation: property.documentation, parameters: []) { - dtsExportEntryPrinter.write(line) - } - dtsExportEntryPrinter.write("\(readonly)\(property.name): \(resolveTypeScriptType(property.type));") - } - for method in staticMethods { - let jsDocLines = renderJSDoc( - documentation: method.documentation, - parameters: method.parameters - ) - dtsExportEntryPrinter.write(lines: jsDocLines) - dtsExportEntryPrinter.write( - "\(method.name)\(renderTSSignature(parameters: method.parameters, returnType: method.returnType, effects: method.effects));" - ) - } + for method in structDefinition.methods where method.effects.isStatic { + let methodLines = try renderStaticMethodForExportObject(method: method) + jsPrinter.write(lines: methodLines) } - dtsExportEntryPrinter.write("}") - return (js: jsPrinter.lines, dtsType: dtsTypePrinter.lines, dtsExportEntry: dtsExportEntryPrinter.lines) + return jsPrinter.lines } func renderExportedEnum( @@ -2118,16 +2096,14 @@ extension BridgeJSLink { func renderExportedClass( _ klass: ExportedClass - ) throws -> (js: [String], dtsType: [String], dtsExportEntry: [String]) { + ) throws -> (js: [String], dtsType: [String]) { let jsPrinter = CodeFragmentPrinter() let dtsTypePrinter = CodeFragmentPrinter() - let dtsExportEntryPrinter = CodeFragmentPrinter() for line in renderJSDoc(documentation: klass.documentation, parameters: []) { dtsTypePrinter.write(line) } dtsTypePrinter.write("export interface \(klass.name) extends SwiftHeapObject {") - dtsExportEntryPrinter.write("\(klass.name): {") jsPrinter.write("class \(klass.name) extends SwiftHeapObject {") // Per-class identity mode: determine at codegen time whether this class uses identity caching @@ -2176,19 +2152,6 @@ extension BridgeJSLink { } jsPrinter.write("}") } - - dtsExportEntryPrinter.indent { - let jsDocLines = renderJSDoc( - documentation: constructor.documentation, - parameters: constructor.parameters - ) - for line in jsDocLines { - dtsExportEntryPrinter.write(line) - } - dtsExportEntryPrinter.write( - "new\(renderTSSignature(parameters: constructor.parameters, returnType: .swiftHeapObject(klass.name), effects: constructor.effects));" - ) - } } for method in klass.methods { @@ -2212,18 +2175,6 @@ extension BridgeJSLink { ) ) } - - dtsExportEntryPrinter.indent { - for line in renderJSDoc( - documentation: method.documentation, - parameters: method.parameters - ) { - dtsExportEntryPrinter.write(line) - } - dtsExportEntryPrinter.write( - "\(method.name)\(renderTSSignature(parameters: method.parameters, returnType: method.returnType, effects: method.effects));" - ) - } } else { let thunkBuilder = ExportedThunkBuilder( effects: method.effects, @@ -2267,15 +2218,76 @@ extension BridgeJSLink { className: klass.abiName, isStatic: property.isStatic, jsPrinter: jsPrinter, - dtsPrinter: property.isStatic ? dtsExportEntryPrinter : dtsTypePrinter + dtsPrinter: dtsTypePrinter ) } jsPrinter.write("}") dtsTypePrinter.write("}") - dtsExportEntryPrinter.write("}") - return (jsPrinter.lines, dtsTypePrinter.lines, dtsExportEntryPrinter.lines) + return (jsPrinter.lines, dtsTypePrinter.lines) + } + + func renderExportedClassExportEntryBody( + _ klass: ExportedClass + ) -> [String] { + let printer = CodeFragmentPrinter() + if let constructor = klass.constructor { + printer.write( + lines: renderJSDoc(documentation: constructor.documentation, parameters: constructor.parameters) + ) + printer.write( + "new\(renderTSSignature(parameters: constructor.parameters, returnType: .swiftHeapObject(klass.name), effects: constructor.effects));" + ) + } + for method in klass.methods where method.effects.isStatic { + printer.write(lines: renderJSDoc(documentation: method.documentation, parameters: method.parameters)) + printer.write( + "\(method.name)\(renderTSSignature(parameters: method.parameters, returnType: method.returnType, effects: method.effects));" + ) + } + for property in klass.properties where property.isStatic { + let readonly = property.isReadonly ? "readonly " : "" + printer.write(lines: renderJSDoc(documentation: property.documentation, parameters: [])) + printer.write("\(readonly)\(property.name): \(resolveTypeScriptType(property.type));") + } + return printer.lines + } + + func renderExportedClassDeclaration( + _ klass: ExportedClass + ) -> [String] { + let printer = CodeFragmentPrinter() + printer.write(lines: renderJSDoc(documentation: klass.documentation, parameters: [])) + printer.write("class \(klass.name) {") + printer.indent { + if let constructor = klass.constructor { + let paramSignatures = constructor.parameters.map { param in + let optional = param.hasDefault ? "?" : "" + return "\(param.name)\(optional): \(param.type.tsType)" + } + printer.write( + lines: renderJSDoc(documentation: constructor.documentation, parameters: constructor.parameters) + ) + printer.write("constructor(\(paramSignatures.joined(separator: ", ")));") + } + for method in klass.methods.sorted(by: { $0.name < $1.name }) { + let staticKeyword = method.effects.isStatic ? "static " : "" + printer.write(lines: renderJSDoc(documentation: method.documentation, parameters: method.parameters)) + printer.write( + "\(staticKeyword)\(method.name)\(renderTSSignature(parameters: method.parameters, returnType: method.returnType, effects: method.effects));" + ) + } + for property in klass.properties.sorted(by: { $0.name < $1.name }) { + let staticKeyword = property.isStatic ? "static " : "" + let readonly = property.isReadonly ? "readonly " : "" + printer.write(lines: renderJSDoc(documentation: property.documentation, parameters: [])) + printer.write("\(staticKeyword)\(readonly)\(property.name): \(resolveTypeScriptType(property.type));") + } + printer.write("release(): void;") + } + printer.write("}") + return printer.lines } private func renderClassProperty( @@ -2338,12 +2350,14 @@ extension BridgeJSLink { } // Add instance property to TypeScript interface definition - let readonly = property.isReadonly ? "readonly " : "" - dtsPrinter.indent { - for line in renderJSDoc(documentation: property.documentation, parameters: []) { - dtsPrinter.write(line) + if !isStatic { + let readonly = property.isReadonly ? "readonly " : "" + dtsPrinter.indent { + for line in renderJSDoc(documentation: property.documentation, parameters: []) { + dtsPrinter.write(line) + } + dtsPrinter.write("\(readonly)\(property.name): \(resolveTypeScriptType(property.type));") } - dtsPrinter.write("\(readonly)\(property.name): \(property.type.tsType);") } } @@ -2760,17 +2774,27 @@ extension BridgeJSLink { return printer.lines } + private enum NodeDeclaration { + case classType(ExportedClass) + case structType(ExportedStruct) + } + private struct NamespaceContent { + // The declaration this node represents + var declaration: NodeDeclaration? + + // Contents var functions: [ExportedFunction] = [] - var classes: [ExportedClass] = [] var enums: [ExportedEnum] = [] - var structs: [ExportedStruct] = [] var staticProperties: [ExportedProperty] = [] + + // Output var functionJsLines: [(name: String, lines: [String])] = [] var functionDtsLines: [(name: String, lines: [String])] = [] - var classDtsLines: [(name: String, lines: [String])] = [] + var declarationDtsLines: [String] = [] var enumDtsLines: [(name: String, line: String)] = [] var staticPropertyDtsLines: [(name: String, lines: [String])] = [] + var structJsLines: [String] = [] var propertyJsLines: [String] = [] } @@ -2791,6 +2815,16 @@ extension BridgeJSLink { children[childName] = newChild return newChild } + + var classDeclaration: ExportedClass? { + if case .classType(let klass) = content.declaration { return klass } + return nil + } + + var structDeclaration: ExportedStruct? { + if case .structType(let structDef) = content.declaration { return structDef } + return nil + } } private func buildExportsTree( @@ -2806,20 +2840,20 @@ extension BridgeJSLink { currentNode.content.functions.append(function) } - for klass in skeleton.classes where klass.namespace != nil { + for klass in skeleton.classes { var currentNode = rootNode - for part in klass.namespace! { + for part in (klass.namespace ?? []) + [klass.name] { currentNode = currentNode.addChild(part) } - currentNode.content.classes.append(klass) + currentNode.content.declaration = .classType(klass) } - for structDef in skeleton.structs where structDef.namespace != nil { + for structDef in skeleton.structs { var currentNode = rootNode - for part in structDef.namespace! { + for part in (structDef.namespace ?? []) + [structDef.name] { currentNode = currentNode.addChild(part) } - currentNode.content.structs.append(structDef) + currentNode.content.declaration = .structType(structDef) } for enumDef in skeleton.enums where enumDef.namespace != nil && enumDef.enumType != .namespace { @@ -2854,6 +2888,7 @@ extension BridgeJSLink { fileprivate func buildHierarchicalExportsType( exportedSkeletons: [ExportedSkeleton], renderClassEntry: (ExportedClass) -> [String], + renderStructEntry: (ExportedStruct) -> [String], renderFunctionEntry: (ExportedFunction) -> [String], renderPropertyEntry: (ExportedProperty) -> [String] ) -> [String] { @@ -2866,6 +2901,7 @@ extension BridgeJSLink { populateTypeScriptExportLines( node: node, renderClassEntry: renderClassEntry, + renderStructEntry: renderStructEntry, renderFunctionEntry: renderFunctionEntry, renderPropertyEntry: renderPropertyEntry ) @@ -2879,6 +2915,7 @@ extension BridgeJSLink { private func populateTypeScriptExportLines( node: NamespaceNode, renderClassEntry: (ExportedClass) -> [String], + renderStructEntry: (ExportedStruct) -> [String], renderFunctionEntry: (ExportedFunction) -> [String], renderPropertyEntry: (ExportedProperty) -> [String] ) { @@ -2886,9 +2923,13 @@ extension BridgeJSLink { node.content.functionDtsLines.append((function.name, renderFunctionEntry(function))) } - for klass in node.content.classes { - let entry = renderClassEntry(klass) - node.content.classDtsLines.append((klass.name, entry)) + switch node.content.declaration { + case .classType(let klass): + node.content.declarationDtsLines = renderClassEntry(klass) + case .structType(let structDef): + node.content.declarationDtsLines = renderStructEntry(structDef) + case nil: + break } for property in node.content.staticProperties { @@ -2903,6 +2944,7 @@ extension BridgeJSLink { populateTypeScriptExportLines( node: childNode, renderClassEntry: renderClassEntry, + renderStructEntry: renderStructEntry, renderFunctionEntry: renderFunctionEntry, renderPropertyEntry: renderPropertyEntry ) @@ -2912,36 +2954,52 @@ extension BridgeJSLink { fileprivate func buildHierarchicalExportsObject( exportedSkeletons: [ExportedSkeleton], intrinsicRegistry: JSIntrinsicRegistry, - renderFunctionImpl: (ExportedFunction) throws -> [String] + renderFunctionImpl: (ExportedFunction) throws -> [String], + renderStructImpl: (ExportedStruct) throws -> [String] ) throws -> [String] { let printer = CodeFragmentPrinter() let rootNode = NamespaceNode(name: "") buildExportsTree(rootNode: rootNode, exportedSkeletons: exportedSkeletons) - try populateJavaScriptExportLines(node: rootNode, renderFunctionImpl: renderFunctionImpl) + try populateJavaScriptExportLines( + node: rootNode, + renderFunctionImpl: renderFunctionImpl, + renderStructImpl: renderStructImpl + ) try populatePropertyImplementations( node: rootNode, intrinsicRegistry: intrinsicRegistry ) - printExportsObjectHierarchy(node: rootNode, printer: printer, currentPath: []) + printExportsObjectHierarchy(node: rootNode, printer: printer) return printer.lines } private func populateJavaScriptExportLines( node: NamespaceNode, - renderFunctionImpl: (ExportedFunction) throws -> [String] + renderFunctionImpl: (ExportedFunction) throws -> [String], + renderStructImpl: (ExportedStruct) throws -> [String] ) throws { for function in node.content.functions { let impl = try renderFunctionImpl(function) node.content.functionJsLines.append((function.name, impl)) } + switch node.content.declaration { + case .structType(let structDef): + node.content.structJsLines = try renderStructImpl(structDef) + case .classType, nil: break + } + for (_, childNode) in node.children { - try populateJavaScriptExportLines(node: childNode, renderFunctionImpl: renderFunctionImpl) + try populateJavaScriptExportLines( + node: childNode, + renderFunctionImpl: renderFunctionImpl, + renderStructImpl: renderStructImpl + ) } } @@ -3011,9 +3069,21 @@ extension BridgeJSLink { } private func hasExportContent(node: NamespaceNode) -> Bool { - if !node.content.classDtsLines.isEmpty || !node.content.enumDtsLines.isEmpty - || !node.content.functionDtsLines.isEmpty || !node.content.staticProperties.isEmpty - { + let content = node.content + switch content.declaration { + case .classType: + return true + case .structType(let structDef): + if structDef.constructor != nil + || structDef.properties.contains(where: \.isStatic) + || structDef.methods.contains(where: \.effects.isStatic) + { + return true + } + case nil: + break + } + if !content.enums.isEmpty || !content.functions.isEmpty || !content.staticProperties.isEmpty { return true } return node.children.values.contains(where: { hasExportContent(node: $0) }) @@ -3024,9 +3094,7 @@ extension BridgeJSLink { guard hasExportContent(node: childNode) else { continue } printer.write("\(childName): {") printer.indent { - for (_, lines) in childNode.content.classDtsLines.sorted(by: { $0.name < $1.name }) { - printer.write(lines: lines) - } + printer.write(lines: childNode.content.declarationDtsLines) for (_, line) in childNode.content.enumDtsLines.sorted(by: { $0.name < $1.name }) { printer.write(line) @@ -3050,36 +3118,51 @@ extension BridgeJSLink { private func printExportsObjectHierarchy( node: NamespaceNode, - printer: CodeFragmentPrinter, - currentPath: [String] = [] + printer: CodeFragmentPrinter ) { for (childName, childNode) in node.children.sorted(by: { $0.key < $1.key }) { - let newPath = currentPath + [childName] - printer.write("\(childName): {") - printer.indent { - for klass in childNode.content.classes.sorted(by: { $0.name < $1.name }) { - printer.write("\(klass.name),") + guard hasExportContent(node: childNode) else { continue } + if case .classType = childNode.content.declaration { + let body = CodeFragmentPrinter() + writeExportsObjectBody(node: childNode, into: body) + if body.lines.isEmpty { + printer.write("\(childName),") + } else { + printer.write("\(childName): Object.assign(\(childName), {") + printer.indent { + printer.write(lines: body.lines) + } + printer.write("}),") } - - for enumDef in childNode.content.enums.sorted(by: { $0.name < $1.name }) { - printer.write("\(enumDef.name): \(enumDef.valuesName),") + } else { + printer.write("\(childName): {") + printer.indent { + writeExportsObjectBody(node: childNode, into: printer) } + printer.write("},") + } + } + } - // Print function and property implementations - printer.write(lines: childNode.content.propertyJsLines) - for (name, lines) in childNode.content.functionJsLines.sorted(by: { $0.name < $1.name }) { - var modifiedLines = lines - if !modifiedLines.isEmpty { - modifiedLines[0] = "\(name): " + modifiedLines[0] - modifiedLines[modifiedLines.count - 1] += "," - } - printer.write(lines: modifiedLines) - } + private func writeExportsObjectBody(node: NamespaceNode, into printer: CodeFragmentPrinter) { + printer.write(lines: node.content.structJsLines) + + for enumDef in node.content.enums.sorted(by: { $0.name < $1.name }) { + printer.write("\(enumDef.name): \(enumDef.valuesName),") + } - printExportsObjectHierarchy(node: childNode, printer: printer, currentPath: newPath) + // Print function and property implementations + printer.write(lines: node.content.propertyJsLines) + for (name, lines) in node.content.functionJsLines.sorted(by: { $0.name < $1.name }) { + var modifiedLines = lines + if !modifiedLines.isEmpty { + modifiedLines[0] = "\(name): " + modifiedLines[0] + modifiedLines[modifiedLines.count - 1] += "," } - printer.write("},") + printer.write(lines: modifiedLines) } + + printExportsObjectHierarchy(node: node, printer: printer) } /// Generates TypeScript declarations for all namespaces @@ -3100,7 +3183,9 @@ extension BridgeJSLink { func namespaceDeclarations( exportedSkeletons: [ExportedSkeleton], renderTSSignatureCallback: @escaping ([Parameter], BridgeType, Effects) -> String, - renderDocCallback: @escaping (String?, [Parameter]) -> [String] + renderDocCallback: @escaping (String?, [Parameter]) -> [String], + renderStructInterface: @escaping (ExportedStruct) -> [String], + renderClassDeclaration: @escaping (ExportedClass) -> [String] ) -> [String] { let printer = CodeFragmentPrinter() @@ -3118,12 +3203,14 @@ extension BridgeJSLink { printer.indent() generateNamespaceDeclarationsForNode( node: globalRootNode, - depth: 1, + inNamespaceScope: false, printer: printer, exposeToGlobal: true, exportedSkeletons: exportedSkeletons, renderTSSignatureCallback: renderTSSignatureCallback, - renderDocCallback: renderDocCallback + renderDocCallback: renderDocCallback, + renderStructInterface: renderStructInterface, + renderClassDeclaration: renderClassDeclaration ) printer.unindent() printer.write("}") @@ -3138,12 +3225,14 @@ extension BridgeJSLink { if !localRootNode.children.isEmpty { generateNamespaceDeclarationsForNode( node: localRootNode, - depth: 1, + inNamespaceScope: false, printer: printer, exposeToGlobal: false, exportedSkeletons: exportedSkeletons, renderTSSignatureCallback: renderTSSignatureCallback, - renderDocCallback: renderDocCallback + renderDocCallback: renderDocCallback, + renderStructInterface: renderStructInterface, + renderClassDeclaration: renderClassDeclaration ) } } @@ -3153,22 +3242,27 @@ extension BridgeJSLink { private func generateNamespaceDeclarationsForNode( node: NamespaceNode, - depth: Int, + inNamespaceScope: Bool, printer: CodeFragmentPrinter, exposeToGlobal: Bool, exportedSkeletons: [ExportedSkeleton], renderTSSignatureCallback: @escaping ([Parameter], BridgeType, Effects) -> String, - renderDocCallback: @escaping (String?, [Parameter]) -> [String] + renderDocCallback: @escaping (String?, [Parameter]) -> [String], + renderStructInterface: @escaping (ExportedStruct) -> [String], + renderClassDeclaration: @escaping (ExportedClass) -> [String] ) { func hasContent(node: NamespaceNode) -> Bool { // Enums and structs are always included - if !node.content.enums.isEmpty || !node.content.structs.isEmpty { + if !node.content.enums.isEmpty + || node.children.values.contains(where: { $0.structDeclaration != nil }) + { return true } // When exposeToGlobal is true, classes, functions, and properties are included if exposeToGlobal { - if !node.content.classes.isEmpty || !node.content.functions.isEmpty + if node.children.values.contains(where: { $0.classDeclaration != nil }) + || !node.content.functions.isEmpty || !node.content.staticProperties.isEmpty { return true @@ -3185,10 +3279,19 @@ extension BridgeJSLink { return false } - func generateNamespaceDeclarations(node: NamespaceNode, depth: Int) { + func generateNamespaceDeclarations(node: NamespaceNode) { let sortedChildren = node.children.sorted { $0.key < $1.key } for (childName, childNode) in sortedChildren { + if inNamespaceScope { + if exposeToGlobal, let klass = childNode.classDeclaration { + printer.write(lines: renderClassDeclaration(klass)) + } + if let structDef = childNode.structDeclaration { + printer.write(lines: renderStructInterface(structDef)) + } + } + // Skip empty namespaces guard hasContent(node: childNode) else { continue @@ -3198,51 +3301,6 @@ extension BridgeJSLink { printer.write("\(exportKeyword)namespace \(childName) {") printer.indent() - // Only include classes when exposeToGlobal is true - if exposeToGlobal { - let sortedClasses = childNode.content.classes.sorted { $0.name < $1.name } - for klass in sortedClasses { - printer.write(lines: renderDocCallback(klass.documentation, [])) - printer.write("class \(klass.name) {") - printer.indent { - if let constructor = klass.constructor { - let paramSignatures = constructor.parameters.map { param in - let optional = param.hasDefault ? "?" : "" - return "\(param.name)\(optional): \(param.type.tsType)" - } - let constructorSignature = - "constructor(\(paramSignatures.joined(separator: ", ")));" - printer.write( - lines: renderDocCallback(constructor.documentation, constructor.parameters) - ) - printer.write(constructorSignature) - } - - let sortedMethods = klass.methods.sorted { $0.name < $1.name } - for method in sortedMethods { - let staticKeyword = method.effects.isStatic ? "static " : "" - let methodSignature = - "\(staticKeyword)\(method.name)\(renderTSSignatureCallback(method.parameters, method.returnType, method.effects));" - printer.write(lines: renderDocCallback(method.documentation, method.parameters)) - printer.write(methodSignature) - } - - let sortedProperties = klass.properties.sorted { $0.name < $1.name } - for property in sortedProperties { - let staticKeyword = property.isStatic ? "static " : "" - let readonly = property.isReadonly ? "readonly " : "" - printer.write(lines: renderDocCallback(property.documentation, [])) - printer.write( - "\(staticKeyword)\(readonly)\(property.name): \(property.type.tsType);" - ) - } - - printer.write("release(): void;") - } - printer.write("}") - } - } - // Generate enum definitions within declare global namespace let sortedEnums = childNode.content.enums.sorted { $0.name < $1.name } for enumDefinition in sortedEnums { @@ -3351,25 +3409,6 @@ extension BridgeJSLink { } } - // Generate struct interface definitions - let sortedStructs = childNode.content.structs.sorted { $0.name < $1.name } - for structDef in sortedStructs { - let instanceProps = structDef.properties.filter { !$0.isStatic } - printer.write(lines: renderDocCallback(structDef.documentation, [])) - printer.write("export interface \(structDef.name) {") - printer.indent { - for property in instanceProps { - let tsType = BridgeJSLink.resolveTypeScriptType( - property.type, - exportedSkeletons: exportedSkeletons - ) - printer.write(lines: renderDocCallback(property.documentation, [])) - printer.write("\(property.name): \(tsType);") - } - } - printer.write("}") - } - // Only include functions and properties when exposeToGlobal is true if exposeToGlobal { let sortedFunctions = childNode.content.functions.sorted { $0.name < $1.name } @@ -3389,12 +3428,14 @@ extension BridgeJSLink { generateNamespaceDeclarationsForNode( node: childNode, - depth: depth + 1, + inNamespaceScope: true, printer: printer, exposeToGlobal: exposeToGlobal, exportedSkeletons: exportedSkeletons, renderTSSignatureCallback: renderTSSignatureCallback, - renderDocCallback: renderDocCallback + renderDocCallback: renderDocCallback, + renderStructInterface: renderStructInterface, + renderClassDeclaration: renderClassDeclaration ) printer.unindent() @@ -3402,7 +3443,7 @@ extension BridgeJSLink { } } - generateNamespaceDeclarations(node: node, depth: depth) + generateNamespaceDeclarations(node: node) } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ClassWithNestedTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ClassWithNestedTypes.swift new file mode 100644 index 000000000..7971283d2 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ClassWithNestedTypes.swift @@ -0,0 +1,34 @@ +@JS class Account { + @JS enum Role: String { + case admin + case guest + } + + @JS struct Credentials { + var token: String + + @JS init(token: String) { + self.token = token + } + + @JS static var maxLength: Int { 64 } + + @JS static func empty() -> Credentials { + Credentials(token: "") + } + } + + @JS var name: String + + @JS var role: Role { .admin } + + @JS static var defaultRole: Role { .guest } + + @JS init(name: String) { + self.name = name + } + + @JS func describe() -> String { + name + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/StructWithNestedTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/StructWithNestedTypes.swift new file mode 100644 index 000000000..d8e5973c1 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/StructWithNestedTypes.swift @@ -0,0 +1,52 @@ +@JS struct Shape { + @JS enum Kind: String { + case circle + case square + } + + var label: String + + @JS init(label: String) { + self.label = label + } +} + +@JS struct Widget { + @JS enum Variant: String { + case button + case slider + } + + @JS struct Layout { + @JS enum Alignment: String { + case leading + case trailing + } + + var padding: Int + } + + @JS struct Bounds { + var width: Int + var height: Int + + @JS init(width: Int, height: Int) { + self.width = width + self.height = height + } + + @JS static var dimensions: Int { + 2 + } + + @JS static func zero() -> Bounds { + Bounds(width: 0, height: 0) + } + } + + var name: String + + @JS init(name: String) { + self.name = name + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ClassWithNestedTypes.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ClassWithNestedTypes.json new file mode 100644 index 000000000..0aa78c471 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ClassWithNestedTypes.json @@ -0,0 +1,218 @@ +{ + "exported" : { + "aliases" : [ + + ], + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_Account_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "name", + "name" : "name", + "type" : { + "string" : { + + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_Account_describe", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "describe", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "name" : "Account", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "name", + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "role", + "type" : { + "rawValueEnum" : { + "_0" : "Account.Role", + "_1" : "String" + } + } + }, + { + "isReadonly" : true, + "isStatic" : true, + "name" : "defaultRole", + "staticContext" : { + "className" : { + "_0" : "Account" + } + }, + "type" : { + "rawValueEnum" : { + "_0" : "Account.Role", + "_1" : "String" + } + } + } + ], + "swiftCallName" : "Account" + } + ], + "enums" : [ + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "admin" + }, + { + "associatedValues" : [ + + ], + "name" : "guest" + } + ], + "emitStyle" : "const", + "name" : "Role", + "namespace" : [ + "Account" + ], + "rawType" : "String", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Account.Role", + "tsFullPath" : "Account.Role" + } + ], + "exposeToGlobal" : false, + "functions" : [ + + ], + "protocols" : [ + + ], + "structs" : [ + { + "constructor" : { + "abiName" : "bjs_Account_Credentials_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "token", + "name" : "token", + "type" : { + "string" : { + + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_Account_Credentials_static_empty", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "empty", + "parameters" : [ + + ], + "returnType" : { + "swiftStruct" : { + "_0" : "Account.Credentials" + } + }, + "staticContext" : { + "structName" : { + "_0" : "Account_Credentials" + } + } + } + ], + "name" : "Credentials", + "namespace" : [ + "Account" + ], + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "token", + "namespace" : [ + "Account" + ], + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : true, + "name" : "maxLength", + "staticContext" : { + "structName" : { + "_0" : "Account_Credentials" + } + }, + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "swiftCallName" : "Account.Credentials" + } + ] + }, + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ClassWithNestedTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ClassWithNestedTypes.swift new file mode 100644 index 000000000..3ae08e13a --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ClassWithNestedTypes.swift @@ -0,0 +1,177 @@ +extension Account.Role: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +} + +extension Account.Credentials: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Account.Credentials { + let token = String.bridgeJSStackPop() + return Account.Credentials(token: token) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.token.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_Account_Credentials(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Account_Credentials())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Account_Credentials") +fileprivate func _bjs_struct_lower_Account_Credentials_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_Account_Credentials_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_Account_Credentials(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Account_Credentials_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Account_Credentials") +fileprivate func _bjs_struct_lift_Account_Credentials_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_Account_Credentials_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_Account_Credentials() -> Int32 { + return _bjs_struct_lift_Account_Credentials_extern() +} + +@_expose(wasm, "bjs_Account_Credentials_init") +@_cdecl("bjs_Account_Credentials_init") +public func _bjs_Account_Credentials_init(_ tokenBytes: Int32, _ tokenLength: Int32) -> Void { + #if arch(wasm32) + let ret = Account.Credentials(token: String.bridgeJSLiftParameter(tokenBytes, tokenLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Account_Credentials_static_maxLength_get") +@_cdecl("bjs_Account_Credentials_static_maxLength_get") +public func _bjs_Account_Credentials_static_maxLength_get() -> Int32 { + #if arch(wasm32) + let ret = Account_Credentials.maxLength + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Account_Credentials_static_empty") +@_cdecl("bjs_Account_Credentials_static_empty") +public func _bjs_Account_Credentials_static_empty() -> Void { + #if arch(wasm32) + let ret = Account.Credentials.empty() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Account_init") +@_cdecl("bjs_Account_init") +public func _bjs_Account_init(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = Account(name: String.bridgeJSLiftParameter(nameBytes, nameLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Account_describe") +@_cdecl("bjs_Account_describe") +public func _bjs_Account_describe(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = Account.bridgeJSLiftParameter(_self).describe() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Account_name_get") +@_cdecl("bjs_Account_name_get") +public func _bjs_Account_name_get(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = Account.bridgeJSLiftParameter(_self).name + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Account_name_set") +@_cdecl("bjs_Account_name_set") +public func _bjs_Account_name_set(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + #if arch(wasm32) + Account.bridgeJSLiftParameter(_self).name = String.bridgeJSLiftParameter(valueBytes, valueLength) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Account_role_get") +@_cdecl("bjs_Account_role_get") +public func _bjs_Account_role_get(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = Account.bridgeJSLiftParameter(_self).role + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Account_static_defaultRole_get") +@_cdecl("bjs_Account_static_defaultRole_get") +public func _bjs_Account_static_defaultRole_get() -> Void { + #if arch(wasm32) + let ret = Account.defaultRole + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Account_deinit") +@_cdecl("bjs_Account_deinit") +public func _bjs_Account_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension Account: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_Account_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_Account_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_Account_wrap") +fileprivate func _bjs_Account_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_Account_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_Account_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Account_wrap_extern(pointer) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StructWithNestedTypes.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StructWithNestedTypes.json new file mode 100644 index 000000000..ec470b65f --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StructWithNestedTypes.json @@ -0,0 +1,337 @@ +{ + "exported" : { + "aliases" : [ + + ], + "classes" : [ + + ], + "enums" : [ + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "circle" + }, + { + "associatedValues" : [ + + ], + "name" : "square" + } + ], + "emitStyle" : "const", + "name" : "Kind", + "namespace" : [ + "Shape" + ], + "rawType" : "String", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Shape.Kind", + "tsFullPath" : "Shape.Kind" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "button" + }, + { + "associatedValues" : [ + + ], + "name" : "slider" + } + ], + "emitStyle" : "const", + "name" : "Variant", + "namespace" : [ + "Widget" + ], + "rawType" : "String", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Widget.Variant", + "tsFullPath" : "Widget.Variant" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "leading" + }, + { + "associatedValues" : [ + + ], + "name" : "trailing" + } + ], + "emitStyle" : "const", + "name" : "Alignment", + "namespace" : [ + "Widget", + "Layout" + ], + "rawType" : "String", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Widget.Layout.Alignment", + "tsFullPath" : "Widget.Layout.Alignment" + } + ], + "exposeToGlobal" : false, + "functions" : [ + + ], + "protocols" : [ + + ], + "structs" : [ + { + "constructor" : { + "abiName" : "bjs_Shape_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "label", + "name" : "label", + "type" : { + "string" : { + + } + } + } + ] + }, + "methods" : [ + + ], + "name" : "Shape", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "label", + "type" : { + "string" : { + + } + } + } + ], + "swiftCallName" : "Shape" + }, + { + "constructor" : { + "abiName" : "bjs_Widget_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "name", + "name" : "name", + "type" : { + "string" : { + + } + } + } + ] + }, + "methods" : [ + + ], + "name" : "Widget", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "name", + "type" : { + "string" : { + + } + } + } + ], + "swiftCallName" : "Widget" + }, + { + "methods" : [ + + ], + "name" : "Layout", + "namespace" : [ + "Widget" + ], + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "padding", + "namespace" : [ + "Widget" + ], + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "swiftCallName" : "Widget.Layout" + }, + { + "constructor" : { + "abiName" : "bjs_Widget_Bounds_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "width", + "name" : "width", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "label" : "height", + "name" : "height", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_Widget_Bounds_static_zero", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "zero", + "parameters" : [ + + ], + "returnType" : { + "swiftStruct" : { + "_0" : "Widget.Bounds" + } + }, + "staticContext" : { + "structName" : { + "_0" : "Widget_Bounds" + } + } + } + ], + "name" : "Bounds", + "namespace" : [ + "Widget" + ], + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "width", + "namespace" : [ + "Widget" + ], + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "height", + "namespace" : [ + "Widget" + ], + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "isReadonly" : true, + "isStatic" : true, + "name" : "dimensions", + "staticContext" : { + "structName" : { + "_0" : "Widget_Bounds" + } + }, + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "swiftCallName" : "Widget.Bounds" + } + ] + }, + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StructWithNestedTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StructWithNestedTypes.swift new file mode 100644 index 000000000..f8843b7cd --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StructWithNestedTypes.swift @@ -0,0 +1,249 @@ +extension Shape.Kind: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +} + +extension Widget.Variant: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +} + +extension Widget.Layout.Alignment: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +} + +extension Shape: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Shape { + let label = String.bridgeJSStackPop() + return Shape(label: label) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.label.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_Shape(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Shape())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Shape") +fileprivate func _bjs_struct_lower_Shape_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_Shape_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_Shape(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Shape_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Shape") +fileprivate func _bjs_struct_lift_Shape_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_Shape_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_Shape() -> Int32 { + return _bjs_struct_lift_Shape_extern() +} + +@_expose(wasm, "bjs_Shape_init") +@_cdecl("bjs_Shape_init") +public func _bjs_Shape_init(_ labelBytes: Int32, _ labelLength: Int32) -> Void { + #if arch(wasm32) + let ret = Shape(label: String.bridgeJSLiftParameter(labelBytes, labelLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension Widget: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Widget { + let name = String.bridgeJSStackPop() + return Widget(name: name) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.name.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_Widget(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Widget())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Widget") +fileprivate func _bjs_struct_lower_Widget_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_Widget_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_Widget(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Widget_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Widget") +fileprivate func _bjs_struct_lift_Widget_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_Widget_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_Widget() -> Int32 { + return _bjs_struct_lift_Widget_extern() +} + +@_expose(wasm, "bjs_Widget_init") +@_cdecl("bjs_Widget_init") +public func _bjs_Widget_init(_ nameBytes: Int32, _ nameLength: Int32) -> Void { + #if arch(wasm32) + let ret = Widget(name: String.bridgeJSLiftParameter(nameBytes, nameLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension Widget.Layout: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Widget.Layout { + let padding = Int.bridgeJSStackPop() + return Widget.Layout(padding: padding) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.padding.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_Widget_Layout(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Widget_Layout())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Widget_Layout") +fileprivate func _bjs_struct_lower_Widget_Layout_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_Widget_Layout_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_Widget_Layout(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Widget_Layout_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Widget_Layout") +fileprivate func _bjs_struct_lift_Widget_Layout_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_Widget_Layout_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_Widget_Layout() -> Int32 { + return _bjs_struct_lift_Widget_Layout_extern() +} + +extension Widget.Bounds: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Widget.Bounds { + let height = Int.bridgeJSStackPop() + let width = Int.bridgeJSStackPop() + return Widget.Bounds(width: width, height: height) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.width.bridgeJSStackPush() + self.height.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_Widget_Bounds(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Widget_Bounds())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Widget_Bounds") +fileprivate func _bjs_struct_lower_Widget_Bounds_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_Widget_Bounds_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_Widget_Bounds(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Widget_Bounds_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Widget_Bounds") +fileprivate func _bjs_struct_lift_Widget_Bounds_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_Widget_Bounds_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_Widget_Bounds() -> Int32 { + return _bjs_struct_lift_Widget_Bounds_extern() +} + +@_expose(wasm, "bjs_Widget_Bounds_init") +@_cdecl("bjs_Widget_Bounds_init") +public func _bjs_Widget_Bounds_init(_ width: Int32, _ height: Int32) -> Void { + #if arch(wasm32) + let ret = Widget.Bounds(width: Int.bridgeJSLiftParameter(width), height: Int.bridgeJSLiftParameter(height)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Widget_Bounds_static_dimensions_get") +@_cdecl("bjs_Widget_Bounds_static_dimensions_get") +public func _bjs_Widget_Bounds_static_dimensions_get() -> Int32 { + #if arch(wasm32) + let ret = Widget_Bounds.dimensions + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Widget_Bounds_static_zero") +@_cdecl("bjs_Widget_Bounds_static_zero") +public func _bjs_Widget_Bounds_static_zero() -> Void { + #if arch(wasm32) + let ret = Widget.Bounds.zero() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.d.ts index 3ee338254..e3092afb3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.d.ts @@ -37,13 +37,6 @@ export interface Surface { readonly label: string; } export type Exports = { - PolygonReference: { - new(underlying: PolygonReference): PolygonReference; - origin(): PolygonReference; - } - TagReference: { - new(underlying: TagReference): TagReference; - } roundtripPolygon(polygon: PolygonReference): PolygonReference; optionalPolygon(polygon: PolygonReference | null): PolygonReference | null; polygonArray(polygons: PolygonReference[]): PolygonReference[]; @@ -52,6 +45,13 @@ export type Exports = { roundtripTags(xs: (InnerTagTag | null)[]): (InnerTagTag | null)[]; describeUser(owner: HasOptionalUserId): HasOptionalUserId; InnerTag: InnerTagObject + PolygonReference: { + new(underlying: PolygonReference): PolygonReference; + origin(): PolygonReference; + }, + TagReference: { + new(underlying: TagReference): TagReference; + }, } export type Imports = { acceptTagged(tagged: string): void; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js index 8f9511e86..0b922111b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js @@ -421,8 +421,6 @@ export async function createInstantiator(options, swift) { enumHelpers.InnerTag = InnerTagHelpers; const exports = { - PolygonReference, - TagReference, roundtripPolygon: function bjs_roundtripPolygon(polygon) { const ret = instance.exports.bjs_roundtripPolygon(polygon.pointer); return PolygonReference.__construct(ret); @@ -517,6 +515,8 @@ export async function createInstantiator(options, swift) { return ret1; }, InnerTag: InnerTagValues, + PolygonReference, + TagReference, }; _exports = exports; return exports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.d.ts index f1d5d5fa9..73ea3b570 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.d.ts @@ -14,11 +14,11 @@ export interface SwiftHeapObject { export interface PolygonReference extends SwiftHeapObject { } export type Exports = { - PolygonReference: { - new(sides: number): PolygonReference; - } makePolygonFactory(): () => PolygonReference; makePolygonInspector(): (arg0: PolygonReference) => number; + PolygonReference: { + new(sides: number): PolygonReference; + }, } export type Imports = { } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js index bc7575fbc..a38fa118e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js @@ -363,7 +363,6 @@ export async function createInstantiator(options, swift) { } } const exports = { - PolygonReference, makePolygonFactory: function bjs_makePolygonFactory() { const ret = instance.exports.bjs_makePolygonFactory(); return swift.memory.getObject(ret); @@ -372,6 +371,7 @@ export async function createInstantiator(options, swift) { const ret = instance.exports.bjs_makePolygonInspector(); return swift.memory.getObject(ret); }, + PolygonReference, }; _exports = exports; return exports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.d.ts index 255249eef..f48189956 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.d.ts @@ -41,11 +41,6 @@ export interface MultiArrayContainer extends SwiftHeapObject { readonly strings: string[]; } export type Exports = { - Item: { - } - MultiArrayContainer: { - new(nums: number[], strs: string[]): MultiArrayContainer; - } processIntArray(values: number[]): number[]; processStringArray(values: string[]): string[]; processDoubleArray(values: number[]): number[]; @@ -76,6 +71,11 @@ export type Exports = { multiOptionalArrayParams(a: number[] | null, b: string[] | null): number; Direction: DirectionObject Status: StatusObject + Item: { + }, + MultiArrayContainer: { + new(nums: number[], strs: string[]): MultiArrayContainer; + }, } export type Imports = { checkArray(a: any): void; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js index 7978d1522..419cf15d5 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js @@ -493,8 +493,6 @@ export async function createInstantiator(options, swift) { structHelpers.Point = PointHelpers; const exports = { - Item, - MultiArrayContainer, processIntArray: function bjs_processIntArray(values) { for (const elem of values) { i32Stack.push((elem | 0)); @@ -1201,6 +1199,8 @@ export async function createInstantiator(options, swift) { }, Direction: DirectionValues, Status: StatusValues, + Item, + MultiArrayContainer, }; _exports = exports; return exports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.d.ts new file mode 100644 index 000000000..5537696c4 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.d.ts @@ -0,0 +1,51 @@ +// 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`. + +export type RoleObject = typeof Account.RoleValues; + +export namespace Account { + const RoleValues: { + readonly Admin: "admin"; + readonly Guest: "guest"; + }; + type RoleTag = typeof RoleValues[keyof typeof RoleValues]; + export interface Credentials { + token: string; + } +} +/// Represents a Swift heap object like a class instance or an actor instance. +export interface SwiftHeapObject { + /// Release the heap object. + /// + /// Note: Calling this method will release the heap object and it will no longer be accessible. + release(): void; +} +export interface Account extends SwiftHeapObject { + describe(): string; + name: string; + readonly role: Account.RoleTag; +} +export type Exports = { + Account: { + new(name: string): Account; + readonly defaultRole: Account.RoleTag; + Role: RoleObject + Credentials: { + init(token: string): Account.Credentials; + readonly maxLength: number; + empty(): Account.Credentials; + }, + }, +} +export type Imports = { +} +export function createInstantiator(options: { + imports: Imports; +}, swift: any): Promise<{ + addImports: (importObject: WebAssembly.Imports) => void; + setInstance: (instance: WebAssembly.Instance) => void; + createExports: (instance: WebAssembly.Instance) => Exports; +}>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.js new file mode 100644 index 000000000..272bb8c49 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.js @@ -0,0 +1,375 @@ +// 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`. + +export const RoleValues = { + Admin: "admin", + Guest: "guest", +}; + +export async function createInstantiator(options, swift) { + let instance; + let memory; + let setException; + let decodeString; + const textDecoder = new TextDecoder("utf-8"); + const textEncoder = new TextEncoder("utf-8"); + let tmpRetString; + let tmpRetBytes; + let tmpRetException; + let tmpRetOptionalBool; + let tmpRetOptionalInt; + let tmpRetOptionalFloat; + let tmpRetOptionalDouble; + let tmpRetOptionalHeapObject; + let strStack = []; + let i32Stack = []; + let i64Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; + let taStack = []; + const enumHelpers = {}; + const structHelpers = {}; + + let _exports = null; + let bjs = null; + const __bjs_createAccount_CredentialsHelpers = () => ({ + lower: (value) => { + const bytes = textEncoder.encode(value.token); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + }, + lift: () => { + const string = strStack.pop(); + return { token: string }; + } + }); + + return { + /** + * @param {WebAssembly.Imports} importObject + */ + addImports: (importObject, importsContext) => { + bjs = {}; + importObject["bjs"] = bjs; + bjs["swift_js_return_string"] = function(ptr, len) { + tmpRetString = decodeString(ptr, len); + } + bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { + const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); + bytes.set(source); + } + bjs["swift_js_make_js_string"] = function(ptr, len) { + return swift.memory.retain(decodeString(ptr, len)); + } + bjs["swift_js_init_memory_with_result"] = function(ptr, len) { + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); + target.set(tmpRetBytes); + tmpRetBytes = undefined; + } + bjs["swift_js_throw"] = function(id) { + tmpRetException = swift.memory.retainByRef(id); + } + bjs["swift_js_retain"] = function(id) { + return swift.memory.retainByRef(id); + } + bjs["swift_js_release"] = function(id) { + swift.memory.release(id); + } + bjs["swift_js_push_i32"] = function(v) { + i32Stack.push(v | 0); + } + bjs["swift_js_push_f32"] = function(v) { + f32Stack.push(Math.fround(v)); + } + bjs["swift_js_push_f64"] = function(v) { + f64Stack.push(v); + } + bjs["swift_js_push_string"] = function(ptr, len) { + const value = decodeString(ptr, len); + strStack.push(value); + } + bjs["swift_js_pop_i32"] = function() { + return i32Stack.pop(); + } + bjs["swift_js_pop_f32"] = function() { + return f32Stack.pop(); + } + bjs["swift_js_pop_f64"] = function() { + return f64Stack.pop(); + } + bjs["swift_js_push_pointer"] = function(pointer) { + ptrStack.push(pointer); + } + bjs["swift_js_pop_pointer"] = function() { + return ptrStack.pop(); + } + bjs["swift_js_push_i64"] = function(v) { + i64Stack.push(v); + } + bjs["swift_js_pop_i64"] = function() { + return i64Stack.pop(); + } + const taCtors = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array]; + bjs["swift_js_push_typed_array"] = function(kind, ptr, count) { + const Ctor = taCtors[kind]; + const byteLen = count * Ctor.BYTES_PER_ELEMENT; + const copy = memory.buffer.slice(ptr, ptr + byteLen); + taStack.push(Array.from(new Ctor(copy))); + } + bjs["swift_js_struct_lower_Account_Credentials"] = function(objectId) { + structHelpers.Account_Credentials.lower(swift.memory.getObject(objectId)); + } + bjs["swift_js_struct_lift_Account_Credentials"] = function() { + const value = structHelpers.Account_Credentials.lift(); + return swift.memory.retain(value); + } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } + bjs["swift_js_return_optional_bool"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalBool = null; + } else { + tmpRetOptionalBool = value !== 0; + } + } + bjs["swift_js_return_optional_int"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalInt = null; + } else { + tmpRetOptionalInt = value | 0; + } + } + bjs["swift_js_return_optional_float"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalFloat = null; + } else { + tmpRetOptionalFloat = Math.fround(value); + } + } + bjs["swift_js_return_optional_double"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalDouble = null; + } else { + tmpRetOptionalDouble = value; + } + } + bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = decodeString(ptr, len); + } + } + bjs["swift_js_return_optional_object"] = function(isSome, objectId) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = swift.memory.getObject(objectId); + } + } + bjs["swift_js_return_optional_heap_object"] = function(isSome, pointer) { + if (isSome === 0) { + tmpRetOptionalHeapObject = null; + } else { + tmpRetOptionalHeapObject = pointer; + } + } + bjs["swift_js_get_optional_int_presence"] = function() { + return tmpRetOptionalInt != null ? 1 : 0; + } + bjs["swift_js_get_optional_int_value"] = function() { + const value = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; + return value; + } + bjs["swift_js_get_optional_string"] = function() { + const str = tmpRetString; + tmpRetString = undefined; + if (str == null) { + return -1; + } else { + const bytes = textEncoder.encode(str); + tmpRetBytes = bytes; + return bytes.length; + } + } + bjs["swift_js_get_optional_float_presence"] = function() { + return tmpRetOptionalFloat != null ? 1 : 0; + } + bjs["swift_js_get_optional_float_value"] = function() { + const value = tmpRetOptionalFloat; + tmpRetOptionalFloat = undefined; + return value; + } + bjs["swift_js_get_optional_double_presence"] = function() { + return tmpRetOptionalDouble != null ? 1 : 0; + } + bjs["swift_js_get_optional_double_value"] = function() { + const value = tmpRetOptionalDouble; + tmpRetOptionalDouble = undefined; + return value; + } + bjs["swift_js_get_optional_heap_object_pointer"] = function() { + const pointer = tmpRetOptionalHeapObject; + tmpRetOptionalHeapObject = undefined; + return pointer || 0; + } + bjs["swift_js_closure_unregister"] = function(funcRef) {} + // Wrapper functions for module: TestModule + if (!importObject["TestModule"]) { + importObject["TestModule"] = {}; + } + importObject["TestModule"]["bjs_Account_wrap"] = function(pointer) { + const obj = _exports['Account'].__construct(pointer); + return swift.memory.retain(obj); + }; + }, + setInstance: (i) => { + instance = i; + memory = instance.exports.memory; + + decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + + setException = (error) => { + instance.exports._swift_js_exception.value = swift.memory.retain(error) + } + }, + /** @param {WebAssembly.Instance} instance */ + createExports: (instance) => { + const js = swift.memory.heap; + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.identityMap?.delete(state.pointer); + state.deinit(state.pointer); + }); + + /// Represents a Swift heap object like a class instance or an actor instance. + class SwiftHeapObject { + static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; + const makeFresh = (identityMap) => { + const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false, identityMap }; + obj.pointer = pointer; + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); + if (identityMap) { + identityMap.set(pointer, new WeakRef(obj)); + } + return obj; + }; + + if (!identityCache) { + return makeFresh(null); + } + + const cached = identityCache.get(pointer)?.deref(); + if (cached && !cached.__swiftHeapObjectState.hasReleased) { + deinit(pointer); + return cached; + } + if (identityCache.has(pointer)) { + identityCache.delete(pointer); + } + + return makeFresh(identityCache); + } + + release() { + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.identityMap?.delete(state.pointer); + state.deinit(state.pointer); + } + } + class Account extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Account_deinit, Account.prototype, null); + } + + constructor(name) { + const nameBytes = textEncoder.encode(name); + const nameId = swift.memory.retain(nameBytes); + const ret = instance.exports.bjs_Account_init(nameId, nameBytes.length); + return Account.__construct(ret); + } + describe() { + instance.exports.bjs_Account_describe(this.pointer); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + } + get name() { + instance.exports.bjs_Account_name_get(this.pointer); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + } + set name(value) { + const valueBytes = textEncoder.encode(value); + const valueId = swift.memory.retain(valueBytes); + instance.exports.bjs_Account_name_set(this.pointer, valueId, valueBytes.length); + } + get role() { + instance.exports.bjs_Account_role_get(this.pointer); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + } + static get defaultRole() { + instance.exports.bjs_Account_static_defaultRole_get(); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + } + } + const Account_CredentialsHelpers = __bjs_createAccount_CredentialsHelpers(); + structHelpers.Account_Credentials = Account_CredentialsHelpers; + + const exports = { + Account: Object.assign(Account, { + Role: RoleValues, + Credentials: { + init: function(token) { + const tokenBytes = textEncoder.encode(token); + const tokenId = swift.memory.retain(tokenBytes); + instance.exports.bjs_Account_Credentials_init(tokenId, tokenBytes.length); + const structValue = structHelpers.Account_Credentials.lift(); + return structValue; + }, + get maxLength() { + const ret = instance.exports.bjs_Account_Credentials_static_maxLength_get(); + return ret; + }, + empty: function() { + instance.exports.bjs_Account_Credentials_static_empty(); + const structValue = structHelpers.Account_Credentials.lift(); + return structValue; + }, + }, + }), + }; + _exports = exports; + return exports; + }, + } +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.d.ts index ac5658eb3..961b9fa5b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.d.ts @@ -46,22 +46,6 @@ export interface ConstructorDefaults extends SwiftHeapObject { tag: string | null; } export type Exports = { - DefaultGreeter: { - new(name: string): DefaultGreeter; - } - EmptyGreeter: { - new(): EmptyGreeter; - } - ConstructorDefaults: { - /** - * @param name - Optional parameter (default: "Default") - * @param count - Optional parameter (default: 42) - * @param enabled - Optional parameter (default: true) - * @param status - Optional parameter (default: Status.Active) - * @param tag - Optional parameter (default: null) - */ - new(name?: string, count?: number, enabled?: boolean, status?: StatusTag, tag?: string | null): ConstructorDefaults; - } /** * @param message - Optional parameter (default: "Hello World") */ @@ -143,6 +127,22 @@ export type Exports = { */ testMixedWithArrayDefault(name?: string, values?: number[], enabled?: boolean): string; Status: StatusObject + ConstructorDefaults: { + /** + * @param name - Optional parameter (default: "Default") + * @param count - Optional parameter (default: 42) + * @param enabled - Optional parameter (default: true) + * @param status - Optional parameter (default: Status.Active) + * @param tag - Optional parameter (default: null) + */ + new(name?: string, count?: number, enabled?: boolean, status?: StatusTag, tag?: string | null): ConstructorDefaults; + }, + DefaultGreeter: { + new(name: string): DefaultGreeter; + }, + EmptyGreeter: { + new(): EmptyGreeter; + }, MathOperations: { /** * @param baseValue - Optional parameter (default: 0.0) @@ -152,7 +152,7 @@ export type Exports = { * @param b - Optional parameter (default: 5.0) */ subtract(a: number, b?: number): number; - } + }, } export type Imports = { } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js index 0c6bfbec8..b7f67fe15 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js @@ -456,9 +456,6 @@ export async function createInstantiator(options, swift) { structHelpers.MathOperations = MathOperationsHelpers; const exports = { - DefaultGreeter, - EmptyGreeter, - ConstructorDefaults, testStringDefault: function bjs_testStringDefault(message = "Hello World") { const messageBytes = textEncoder.encode(message); const messageId = swift.memory.retain(messageBytes); @@ -675,6 +672,9 @@ export async function createInstantiator(options, swift) { return ret; }, Status: StatusValues, + ConstructorDefaults, + DefaultGreeter, + EmptyGreeter, MathOperations: { init: function(baseValue = 0.0) { instance.exports.bjs_MathOperations_init(baseValue); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.d.ts index f14b29aa4..652177cd8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.d.ts @@ -18,14 +18,14 @@ export interface SwiftHeapObject { export interface Box extends SwiftHeapObject { } export type Exports = { - Box: { - } mirrorDictionary(values: Record): Record; optionalDictionary(values: Record | null): Record | null; nestedDictionary(values: Record): Record; boxDictionary(boxes: Record): Record; optionalBoxDictionary(boxes: Record): Record; roundtripCounters(counters: Counters): Counters; + Box: { + }, } export type Imports = { importMirrorDictionary(values: Record): Record; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js index 104472a02..d0ac5307f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js @@ -360,7 +360,6 @@ export async function createInstantiator(options, swift) { structHelpers.Counters = CountersHelpers; const exports = { - Box, mirrorDictionary: function bjs_mirrorDictionary(values) { const entries = Object.entries(values); for (const entry of entries) { @@ -513,6 +512,7 @@ export async function createInstantiator(options, swift) { const structValue = structHelpers.Counters.lift(); return structValue; }, + Box, }; _exports = exports; return exports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.d.ts index 359d719d1..196ef73fe 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.d.ts @@ -77,13 +77,6 @@ export interface Greeter extends SwiftHeapObject { name: string; } export type Exports = { - Greeter: { - /** - * Create a greeter. - * @param name The name to greet. - */ - new(name: string): Greeter; - } /** * Returns a greeting for a user. * @param name The user's name. @@ -120,6 +113,13 @@ export type Exports = { */ terminator(): string; Color: ColorObject + Greeter: { + /** + * Create a greeter. + * @param name The name to greet. + */ + new(name: string): Greeter; + }, MathUtils: { /** * Doubles a value, in a namespace. diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.js index 07e8673bf..f29814675 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.js @@ -351,7 +351,6 @@ export async function createInstantiator(options, swift) { structHelpers.Point = PointHelpers; const exports = { - Greeter, greet: function bjs_greet(name, greeting = "Hello") { const nameBytes = textEncoder.encode(name); const nameId = swift.memory.retain(nameBytes); @@ -407,6 +406,7 @@ export async function createInstantiator(options, swift) { return ret; } }, + Greeter, MathUtils: { double: function bjs_MathUtils_double(value) { const ret = instance.exports.bjs_MathUtils_double(value); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.d.ts index 9525038e6..d2772fa8b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.d.ts @@ -14,10 +14,10 @@ export interface SwiftHeapObject { export interface ColorBox extends SwiftHeapObject { } export type Exports = { + roundtripColor(color: ColorBox): ColorBox; ColorBox: { new(name: string): ColorBox; - } - roundtripColor(color: ColorBox): ColorBox; + }, } export type Imports = { } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js index ccf57601b..42f3fd958 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js @@ -290,11 +290,11 @@ export async function createInstantiator(options, swift) { } } const exports = { - ColorBox, roundtripColor: function bjs_roundtripColor(color) { const ret = instance.exports.bjs_roundtripColor(color.pointer); return ColorBox.__construct(ret); }, + ColorBox, }; _exports = exports; return exports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.d.ts index 13f77ae08..36fc92474 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.d.ts @@ -153,8 +153,6 @@ export interface SwiftHeapObject { export interface User extends SwiftHeapObject { } export type Exports = { - User: { - } handle(result: APIResultTag): void; getResult(): APIResultTag; roundtripAPIResult(result: APIResultTag): APIResultTag; @@ -184,6 +182,8 @@ export type Exports = { API: { NetworkingResult: NetworkingResultObject }, + User: { + }, Utilities: { Result: ResultObject }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js index 35b05fe61..8ff3dd90d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js @@ -1061,7 +1061,6 @@ export async function createInstantiator(options, swift) { enumHelpers.OptionalAllTypesResult = OptionalAllTypesResultHelpers; const exports = { - User, handle: function bjs_handle(result) { const resultCaseId = enumHelpers.APIResult.lower(result); instance.exports.bjs_handle(resultCaseId); @@ -1255,6 +1254,7 @@ export async function createInstantiator(options, swift) { API: { NetworkingResult: NetworkingResultValues, }, + User, Utilities: { Result: ResultValues, }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.d.ts index b78f0cecd..0ca8b16b9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.d.ts @@ -39,11 +39,6 @@ declare global { } namespace Networking { namespace API { - class HTTPServer { - constructor(); - call(method: Networking.API.MethodTag): void; - release(): void; - } const MethodValues: { readonly Get: 0; readonly Post: 1; @@ -51,19 +46,24 @@ declare global { readonly Delete: 3; }; type MethodTag = typeof MethodValues[keyof typeof MethodValues]; + class HTTPServer { + constructor(); + call(method: Networking.API.MethodTag): void; + release(): void; + } } namespace APIV2 { namespace Internal { - class TestServer { - constructor(); - call(method: Networking.APIV2.Internal.SupportedMethodTag): void; - release(): void; - } const SupportedMethodValues: { readonly Get: 0; readonly Post: 1; }; type SupportedMethodTag = typeof SupportedMethodValues[keyof typeof SupportedMethodValues]; + class TestServer { + constructor(); + call(method: Networking.APIV2.Internal.SupportedMethodTag): void; + release(): void; + } } } } @@ -114,21 +114,21 @@ export type Exports = { Formatting: { Converter: { new(): Converter; - } + }, }, Networking: { API: { + Method: MethodObject HTTPServer: { new(): HTTPServer; - } - Method: MethodObject + }, }, APIV2: { Internal: { + SupportedMethod: SupportedMethodObject TestServer: { new(): TestServer; - } - SupportedMethod: SupportedMethodObject + }, }, }, }, @@ -144,7 +144,7 @@ export type Exports = { Utils: { Converter: { new(): Converter; - } + }, }, } export type Imports = { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js index 1a8f5662f..6c45f0333 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js @@ -438,13 +438,13 @@ export async function createInstantiator(options, swift) { }, Networking: { API: { - HTTPServer, Method: MethodValues, + HTTPServer, }, APIV2: { Internal: { - TestServer, SupportedMethod: SupportedMethodValues, + TestServer, }, }, }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.d.ts index 23d872d27..b5a85a082 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.d.ts @@ -75,21 +75,21 @@ export type Exports = { Formatting: { Converter: { new(): Converter; - } + }, }, Networking: { API: { + Method: MethodObject HTTPServer: { new(): HTTPServer; - } - Method: MethodObject + }, }, APIV2: { Internal: { + SupportedMethod: SupportedMethodObject TestServer: { new(): TestServer; - } - SupportedMethod: SupportedMethodObject + }, }, }, }, @@ -105,7 +105,7 @@ export type Exports = { Utils: { Converter: { new(): Converter; - } + }, }, } export type Imports = { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js index 9196e99b3..2a9e7948a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js @@ -389,13 +389,13 @@ export async function createInstantiator(options, swift) { }, Networking: { API: { - HTTPServer, Method: MethodValues, + HTTPServer, }, APIV2: { Internal: { - TestServer, SupportedMethod: SupportedMethodValues, + TestServer, }, }, }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.d.ts index e5e2a3a84..02d17c011 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.d.ts @@ -23,13 +23,13 @@ export interface ExplicitlyUncachedModel extends SwiftHeapObject { export type Exports = { CachedModel: { new(name: string): CachedModel; - } - UncachedModel: { - new(value: number): UncachedModel; - } + }, ExplicitlyUncachedModel: { new(count: number): ExplicitlyUncachedModel; - } + }, + UncachedModel: { + new(value: number): UncachedModel; + }, } export type Imports = { } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js index 36728f890..83f53d8a6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js @@ -348,8 +348,8 @@ export async function createInstantiator(options, swift) { } const exports = { CachedModel, - UncachedModel, ExplicitlyUncachedModel, + UncachedModel, }; _exports = exports; return exports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.d.ts index e5e2a3a84..02d17c011 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.d.ts @@ -23,13 +23,13 @@ export interface ExplicitlyUncachedModel extends SwiftHeapObject { export type Exports = { CachedModel: { new(name: string): CachedModel; - } - UncachedModel: { - new(value: number): UncachedModel; - } + }, ExplicitlyUncachedModel: { new(count: number): ExplicitlyUncachedModel; - } + }, + UncachedModel: { + new(value: number): UncachedModel; + }, } export type Imports = { } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js index ed180c1c8..bb6f36902 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js @@ -346,8 +346,8 @@ export async function createInstantiator(options, swift) { } const exports = { CachedModel, - UncachedModel, ExplicitlyUncachedModel, + UncachedModel, }; _exports = exports; return exports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.d.ts index e5e2a3a84..02d17c011 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.d.ts @@ -23,13 +23,13 @@ export interface ExplicitlyUncachedModel extends SwiftHeapObject { export type Exports = { CachedModel: { new(name: string): CachedModel; - } - UncachedModel: { - new(value: number): UncachedModel; - } + }, ExplicitlyUncachedModel: { new(count: number): ExplicitlyUncachedModel; - } + }, + UncachedModel: { + new(value: number): UncachedModel; + }, } export type Imports = { } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js index ed180c1c8..bb6f36902 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js @@ -346,8 +346,8 @@ export async function createInstantiator(options, swift) { } const exports = { CachedModel, - UncachedModel, ExplicitlyUncachedModel, + UncachedModel, }; _exports = exports; return exports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.d.ts index f4c13c610..85109479e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.d.ts @@ -19,13 +19,13 @@ export interface JSValueHolder extends SwiftHeapObject { optionalValue: any | null; } export type Exports = { - JSValueHolder: { - new(value: any, optionalValue: any | null): JSValueHolder; - } roundTripJSValue(value: any): any; roundTripOptionalJSValue(value: any | null): any | null; roundTripJSValueArray(values: any[]): any[]; roundTripOptionalJSValueArray(values: any[] | null): any[] | null; + JSValueHolder: { + new(value: any, optionalValue: any | null): JSValueHolder; + }, } export type Imports = { jsEchoJSValue(value: any): any; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js index d47fd3e85..ae59008ba 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js @@ -527,7 +527,6 @@ export async function createInstantiator(options, swift) { } } const exports = { - JSValueHolder, roundTripJSValue: function bjs_roundTripJSValue(value) { const [valueKind, valuePayload1, valuePayload2] = __bjs_jsValueLower(value); instance.exports.bjs_roundTripJSValue(valueKind, valuePayload1, valuePayload2); @@ -627,6 +626,7 @@ export async function createInstantiator(options, swift) { } return optResult; }, + JSValueHolder, }; _exports = exports; return exports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.d.ts index 7b4cc95e6..c7ff9a39c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.d.ts @@ -16,10 +16,10 @@ export interface GlobalClass extends SwiftHeapObject { } export type Exports = { GlobalAPI: { + globalFunction(): string; GlobalClass: { new(): GlobalClass; - } - globalFunction(): string; + }, }, } export type Imports = { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js index 577fa0ca7..39ecf8d99 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js @@ -295,13 +295,13 @@ export async function createInstantiator(options, swift) { } const exports = { GlobalAPI: { - GlobalClass, globalFunction: function bjs_GlobalAPI_globalFunction() { instance.exports.bjs_GlobalAPI_globalFunction(); const ret = tmpRetString; tmpRetString = undefined; return ret; }, + GlobalClass, }, }; _exports = exports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.d.ts index 88485232e..01a392e91 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.d.ts @@ -8,12 +8,12 @@ export {}; declare global { namespace GlobalAPI { + function globalFunction(): string; class GlobalClass { constructor(); greet(): string; release(): void; } - function globalFunction(): string; } } @@ -32,16 +32,16 @@ export interface PrivateClass extends SwiftHeapObject { } export type Exports = { GlobalAPI: { + globalFunction(): string; GlobalClass: { new(): GlobalClass; - } - globalFunction(): string; + }, }, PrivateAPI: { + privateFunction(): string; PrivateClass: { new(): PrivateClass; - } - privateFunction(): string; + }, }, } export type Imports = { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js index e15c7bcfb..62d7651e8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js @@ -322,22 +322,22 @@ export async function createInstantiator(options, swift) { } const exports = { GlobalAPI: { - GlobalClass, globalFunction: function bjs_GlobalAPI_globalFunction() { instance.exports.bjs_GlobalAPI_globalFunction(); const ret = tmpRetString; tmpRetString = undefined; return ret; }, + GlobalClass, }, PrivateAPI: { - PrivateClass, privateFunction: function bjs_PrivateAPI_privateFunction() { instance.exports.bjs_PrivateAPI_privateFunction(); const ret = tmpRetString; tmpRetString = undefined; return ret; }, + PrivateClass, }, }; _exports = exports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.d.ts index 193857072..89aad5c32 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.d.ts @@ -16,10 +16,10 @@ export interface PrivateClass extends SwiftHeapObject { } export type Exports = { PrivateAPI: { + privateFunction(): string; PrivateClass: { new(): PrivateClass; - } - privateFunction(): string; + }, }, } export type Imports = { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js index e1605fb10..69bfe5ff1 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js @@ -295,13 +295,13 @@ export async function createInstantiator(options, swift) { } const exports = { PrivateAPI: { - PrivateClass, privateFunction: function bjs_PrivateAPI_privateFunction() { instance.exports.bjs_PrivateAPI_privateFunction(); const ret = tmpRetString; tmpRetString = undefined; return ret; }, + PrivateClass, }, }; _exports = exports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.d.ts index ae792be4c..ac9ea13c4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.d.ts @@ -89,7 +89,7 @@ export type Exports = { Collections: { Container: { new(): Container; - } + }, }, MyModule: { Utils: { @@ -104,7 +104,7 @@ export type Exports = { Converters: { Converter: { new(): Converter; - } + }, }, }, __Swift: { @@ -113,9 +113,9 @@ export type Exports = { new(name: string): Greeter; makeDefault(): Greeter; readonly defaultGreeting: string; - } + }, UUID: { - } + }, }, }, } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.d.ts index 4c02c18b3..debd3ffcf 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.d.ts @@ -36,7 +36,7 @@ export type Exports = { Collections: { Container: { new(): Container; - } + }, }, MyModule: { Utils: { @@ -51,7 +51,7 @@ export type Exports = { Converters: { Converter: { new(): Converter; - } + }, }, }, __Swift: { @@ -60,9 +60,9 @@ export type Exports = { new(name: string): Greeter; makeDefault(): Greeter; readonly defaultGreeting: string; - } + }, UUID: { - } + }, }, }, } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.d.ts index 4e966661e..c418ed8a5 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.d.ts @@ -30,10 +30,10 @@ export interface Player extends SwiftHeapObject { getTag(): string; } export type Exports = { - User: { - } Player: { - } + }, + User: { + }, } export type Imports = { } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js index 1fb339f32..972f9ae74 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js @@ -351,12 +351,8 @@ export async function createInstantiator(options, swift) { structHelpers.Player_Stats = Player_StatsHelpers; const exports = { - User, Player, - Player: { - }, - User: { - }, + User, }; _exports = exports; return exports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.d.ts index c4a22ac0c..0f64324cd 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.d.ts @@ -42,12 +42,6 @@ export interface WithOptionalJSClass { childOrNull: WithOptionalJSClass | null; } export type Exports = { - Greeter: { - new(name: string | null): Greeter; - } - OptionalPropertyHolder: { - new(): OptionalPropertyHolder; - } roundTripOptionalClass(value: Greeter | null): Greeter | null; testOptionalPropertyRoundtrip(holder: OptionalPropertyHolder | null): OptionalPropertyHolder | null; roundTripExportedOptionalJSObject(value: any | null): any | null; @@ -71,6 +65,12 @@ export type Exports = { roundTripAlias(age: number | null): number | null; roundTripOptionalAlias(name: string | null): string | null; testMixedOptionals(firstName: string | null, lastName: string | null, age: number | null, active: boolean): string | null; + Greeter: { + new(name: string | null): Greeter; + }, + OptionalPropertyHolder: { + new(): OptionalPropertyHolder; + }, } export type Imports = { WithOptionalJSClass: { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js index 956582377..5a253cdc0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js @@ -685,8 +685,6 @@ export async function createInstantiator(options, swift) { } } const exports = { - Greeter, - OptionalPropertyHolder, roundTripOptionalClass: function bjs_roundTripOptionalClass(value) { const isSome = value != null; let result; @@ -972,6 +970,8 @@ export async function createInstantiator(options, swift) { tmpRetString = undefined; return optResult; }, + Greeter, + OptionalPropertyHolder, }; _exports = exports; return exports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.d.ts index 8f65849ab..5872a3020 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.d.ts @@ -31,11 +31,11 @@ export interface PropertyHolder extends SwiftHeapObject { observedProperty: number; } export type Exports = { - PropertyHolder: { - new(intValue: number, floatValue: number, doubleValue: number, boolValue: boolean, stringValue: string, jsObject: any): PropertyHolder; - } createPropertyHolder(intValue: number, floatValue: number, doubleValue: number, boolValue: boolean, stringValue: string, jsObject: any): PropertyHolder; testPropertyHolder(holder: PropertyHolder): string; + PropertyHolder: { + new(intValue: number, floatValue: number, doubleValue: number, boolValue: boolean, stringValue: string, jsObject: any): PropertyHolder; + }, } export type Imports = { } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js index 0070d0dbe..61560134a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js @@ -406,7 +406,6 @@ export async function createInstantiator(options, swift) { } } const exports = { - PropertyHolder, createPropertyHolder: function bjs_createPropertyHolder(intValue, floatValue, doubleValue, boolValue, stringValue, jsObject) { const stringValueBytes = textEncoder.encode(stringValue); const stringValueId = swift.memory.retain(stringValueBytes); @@ -419,6 +418,7 @@ export async function createInstantiator(options, swift) { tmpRetString = undefined; return ret; }, + PropertyHolder, }; _exports = exports; return exports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.d.ts index 27cd9212b..a413fa500 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.d.ts @@ -96,21 +96,21 @@ export interface DelegateManager extends SwiftHeapObject { delegatesByName: Record; } export type Exports = { - Helper: { - new(value: number): Helper; - } - MyViewController: { - new(delegate: MyViewControllerDelegate): MyViewController; - } - DelegateManager: { - new(delegates: MyViewControllerDelegate[]): DelegateManager; - } processDelegates(delegates: MyViewControllerDelegate[]): MyViewControllerDelegate[]; processDelegatesByName(delegates: Record): Record; Direction: DirectionObject ExampleEnum: ExampleEnumObject Result: ResultObject Priority: PriorityObject + DelegateManager: { + new(delegates: MyViewControllerDelegate[]): DelegateManager; + }, + Helper: { + new(value: number): Helper; + }, + MyViewController: { + new(delegate: MyViewControllerDelegate): MyViewController; + }, } export type Imports = { } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js index 999210eb5..b2a894ffa 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js @@ -793,9 +793,6 @@ export async function createInstantiator(options, swift) { enumHelpers.Result = ResultHelpers; const exports = { - Helper, - MyViewController, - DelegateManager, processDelegates: function bjs_processDelegates(delegates) { for (const elem of delegates) { const objId = swift.memory.retain(elem); @@ -847,6 +844,9 @@ export async function createInstantiator(options, swift) { ExampleEnum: ExampleEnumValues, Result: ResultValues, Priority: PriorityValues, + DelegateManager, + Helper, + MyViewController, }; _exports = exports; return exports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.d.ts index 6b7a9d28d..7d5a3c9aa 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.d.ts @@ -19,13 +19,13 @@ export interface Widget extends SwiftHeapObject { name: string; } export type Exports = { - Widget: { - new(name: string): Widget; - } processRenderable(item: Renderable, transform: (arg0: Renderable) => string): string; makeRenderableFactory(defaultName: string): () => Renderable; roundtripRenderable(callback: (arg0: Renderable) => Renderable): (arg0: Renderable) => Renderable; processOptionalRenderable(callback: (arg0: Renderable | null) => string): string; + Widget: { + new(name: string): Widget; + }, } export type Imports = { } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js index d9c31ed1d..01f9fe0e1 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js @@ -447,7 +447,6 @@ export async function createInstantiator(options, swift) { } } const exports = { - Widget, processRenderable: function bjs_processRenderable(item, transform) { const callbackId = swift.memory.retain(transform); instance.exports.bjs_processRenderable(swift.memory.retain(item), callbackId); @@ -473,6 +472,7 @@ export async function createInstantiator(options, swift) { tmpRetString = undefined; return ret; }, + Widget, }; _exports = exports; return exports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.d.ts index 5916e1648..e5602e42d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.d.ts @@ -51,15 +51,15 @@ export interface MathUtils extends SwiftHeapObject { multiply(x: number, y: number): number; } export type Exports = { + Calculator: CalculatorObject + APIResult: APIResultObject MathUtils: { new(): MathUtils; subtract(a: number, b: number): number; add(a: number, b: number): number; divide(a: number, b: number): number; readonly pi: number; - } - Calculator: CalculatorObject - APIResult: APIResultObject + }, Utils: { String: { uppercase(text: string): string; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js index d626e9adf..25f989a00 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js @@ -361,7 +361,6 @@ export async function createInstantiator(options, swift) { globalThis.Utils.String = {}; } const exports = { - MathUtils, Calculator: { ...CalculatorValues, square: function(value) { @@ -388,6 +387,7 @@ export async function createInstantiator(options, swift) { return ret; } }, + MathUtils, Utils: { String: { uppercase: function bjs_Utils_String_static_uppercase(text) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.d.ts index c9cb26910..a168f3ad1 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.d.ts @@ -41,15 +41,15 @@ export interface MathUtils extends SwiftHeapObject { multiply(x: number, y: number): number; } export type Exports = { + Calculator: CalculatorObject + APIResult: APIResultObject MathUtils: { new(): MathUtils; subtract(a: number, b: number): number; add(a: number, b: number): number; divide(a: number, b: number): number; readonly pi: number; - } - Calculator: CalculatorObject - APIResult: APIResultObject + }, Utils: { String: { uppercase(text: string): string; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js index 93f1e7ec7..ca4093992 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js @@ -355,7 +355,6 @@ export async function createInstantiator(options, swift) { enumHelpers.APIResult = APIResultHelpers; const exports = { - MathUtils, Calculator: { ...CalculatorValues, square: function(value) { @@ -382,6 +381,7 @@ export async function createInstantiator(options, swift) { return ret; } }, + MathUtils, Utils: { String: { uppercase: function bjs_Utils_String_static_uppercase(text) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.d.ts index fea3c4b59..b54e14def 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.d.ts @@ -40,6 +40,7 @@ export interface SwiftHeapObject { export interface PropertyClass extends SwiftHeapObject { } export type Exports = { + PropertyEnum: PropertyEnumObject PropertyClass: { new(): PropertyClass; readonly staticConstant: string; @@ -49,8 +50,7 @@ export type Exports = { computedProperty: string; readonly readOnlyComputed: number; optionalProperty: string | null; - } - PropertyEnum: PropertyEnumObject + }, PropertyNamespace: { readonly namespaceConstant: string; namespaceProperty: string; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js index edf069178..63dd9cba5 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js @@ -367,7 +367,6 @@ export async function createInstantiator(options, swift) { globalThis.PropertyNamespace.Nested = {}; } const exports = { - PropertyClass, PropertyEnum: { ...PropertyEnumValues, get enumProperty() { @@ -397,6 +396,7 @@ export async function createInstantiator(options, swift) { instance.exports.bjs_PropertyEnum_static_computedEnum_set(valueId, valueBytes.length); } }, + PropertyClass, PropertyNamespace: { get namespaceProperty() { instance.exports.bjs_PropertyNamespace_static_namespaceProperty_get(); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.d.ts index 4ce689edb..aea927c79 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.d.ts @@ -26,6 +26,7 @@ export interface SwiftHeapObject { export interface PropertyClass extends SwiftHeapObject { } export type Exports = { + PropertyEnum: PropertyEnumObject PropertyClass: { new(): PropertyClass; readonly staticConstant: string; @@ -35,8 +36,7 @@ export type Exports = { computedProperty: string; readonly readOnlyComputed: number; optionalProperty: string | null; - } - PropertyEnum: PropertyEnumObject + }, PropertyNamespace: { readonly namespaceConstant: string; namespaceProperty: string; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js index 64132a3c2..b5680b9b0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js @@ -361,7 +361,6 @@ export async function createInstantiator(options, swift) { } } const exports = { - PropertyClass, PropertyEnum: { ...PropertyEnumValues, get enumProperty() { @@ -391,6 +390,7 @@ export async function createInstantiator(options, swift) { instance.exports.bjs_PropertyEnum_static_computedEnum_set(valueId, valueBytes.length); } }, + PropertyClass, PropertyNamespace: { get namespaceProperty() { instance.exports.bjs_PropertyNamespace_static_namespaceProperty_get(); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.d.ts new file mode 100644 index 000000000..fe4708fd8 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.d.ts @@ -0,0 +1,73 @@ +// 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`. + +export interface Shape { + label: string; +} +export interface Widget { + name: string; +} +export type KindObject = typeof Shape.KindValues; + +export type VariantObject = typeof Widget.VariantValues; + +export type AlignmentObject = typeof Widget.Layout.AlignmentValues; + +export namespace Shape { + const KindValues: { + readonly Circle: "circle"; + readonly Square: "square"; + }; + type KindTag = typeof KindValues[keyof typeof KindValues]; +} +export namespace Widget { + const VariantValues: { + readonly Button: "button"; + readonly Slider: "slider"; + }; + type VariantTag = typeof VariantValues[keyof typeof VariantValues]; + export interface Bounds { + width: number; + height: number; + } + export interface Layout { + padding: number; + } + export namespace Layout { + const AlignmentValues: { + readonly Leading: "leading"; + readonly Trailing: "trailing"; + }; + type AlignmentTag = typeof AlignmentValues[keyof typeof AlignmentValues]; + } +} +export type Exports = { + Shape: { + init(label: string): Shape; + Kind: KindObject + }, + Widget: { + init(name: string): Widget; + Variant: VariantObject + Bounds: { + init(width: number, height: number): Widget.Bounds; + readonly dimensions: number; + zero(): Widget.Bounds; + }, + Layout: { + Alignment: AlignmentObject + }, + }, +} +export type Imports = { +} +export function createInstantiator(options: { + imports: Imports; +}, swift: any): Promise<{ + addImports: (importObject: WebAssembly.Imports) => void; + setInstance: (instance: WebAssembly.Instance) => void; + createExports: (instance: WebAssembly.Instance) => Exports; +}>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.js new file mode 100644 index 000000000..ee5cc0a3e --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.js @@ -0,0 +1,364 @@ +// 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`. + +export const KindValues = { + Circle: "circle", + Square: "square", +}; + +export const VariantValues = { + Button: "button", + Slider: "slider", +}; + +export const AlignmentValues = { + Leading: "leading", + Trailing: "trailing", +}; + +export async function createInstantiator(options, swift) { + let instance; + let memory; + let setException; + let decodeString; + const textDecoder = new TextDecoder("utf-8"); + const textEncoder = new TextEncoder("utf-8"); + let tmpRetString; + let tmpRetBytes; + let tmpRetException; + let tmpRetOptionalBool; + let tmpRetOptionalInt; + let tmpRetOptionalFloat; + let tmpRetOptionalDouble; + let tmpRetOptionalHeapObject; + let strStack = []; + let i32Stack = []; + let i64Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; + let taStack = []; + const enumHelpers = {}; + const structHelpers = {}; + + let _exports = null; + let bjs = null; + const __bjs_createShapeHelpers = () => ({ + lower: (value) => { + const bytes = textEncoder.encode(value.label); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + }, + lift: () => { + const string = strStack.pop(); + return { label: string }; + } + }); + const __bjs_createWidgetHelpers = () => ({ + lower: (value) => { + const bytes = textEncoder.encode(value.name); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + }, + lift: () => { + const string = strStack.pop(); + return { name: string }; + } + }); + const __bjs_createWidget_LayoutHelpers = () => ({ + lower: (value) => { + i32Stack.push((value.padding | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return { padding: int }; + } + }); + const __bjs_createWidget_BoundsHelpers = () => ({ + lower: (value) => { + i32Stack.push((value.width | 0)); + i32Stack.push((value.height | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + const int1 = i32Stack.pop(); + return { width: int1, height: int }; + } + }); + + return { + /** + * @param {WebAssembly.Imports} importObject + */ + addImports: (importObject, importsContext) => { + bjs = {}; + importObject["bjs"] = bjs; + bjs["swift_js_return_string"] = function(ptr, len) { + tmpRetString = decodeString(ptr, len); + } + bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { + const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); + bytes.set(source); + } + bjs["swift_js_make_js_string"] = function(ptr, len) { + return swift.memory.retain(decodeString(ptr, len)); + } + bjs["swift_js_init_memory_with_result"] = function(ptr, len) { + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); + target.set(tmpRetBytes); + tmpRetBytes = undefined; + } + bjs["swift_js_throw"] = function(id) { + tmpRetException = swift.memory.retainByRef(id); + } + bjs["swift_js_retain"] = function(id) { + return swift.memory.retainByRef(id); + } + bjs["swift_js_release"] = function(id) { + swift.memory.release(id); + } + bjs["swift_js_push_i32"] = function(v) { + i32Stack.push(v | 0); + } + bjs["swift_js_push_f32"] = function(v) { + f32Stack.push(Math.fround(v)); + } + bjs["swift_js_push_f64"] = function(v) { + f64Stack.push(v); + } + bjs["swift_js_push_string"] = function(ptr, len) { + const value = decodeString(ptr, len); + strStack.push(value); + } + bjs["swift_js_pop_i32"] = function() { + return i32Stack.pop(); + } + bjs["swift_js_pop_f32"] = function() { + return f32Stack.pop(); + } + bjs["swift_js_pop_f64"] = function() { + return f64Stack.pop(); + } + bjs["swift_js_push_pointer"] = function(pointer) { + ptrStack.push(pointer); + } + bjs["swift_js_pop_pointer"] = function() { + return ptrStack.pop(); + } + bjs["swift_js_push_i64"] = function(v) { + i64Stack.push(v); + } + bjs["swift_js_pop_i64"] = function() { + return i64Stack.pop(); + } + const taCtors = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array]; + bjs["swift_js_push_typed_array"] = function(kind, ptr, count) { + const Ctor = taCtors[kind]; + const byteLen = count * Ctor.BYTES_PER_ELEMENT; + const copy = memory.buffer.slice(ptr, ptr + byteLen); + taStack.push(Array.from(new Ctor(copy))); + } + bjs["swift_js_struct_lower_Shape"] = function(objectId) { + structHelpers.Shape.lower(swift.memory.getObject(objectId)); + } + bjs["swift_js_struct_lift_Shape"] = function() { + const value = structHelpers.Shape.lift(); + return swift.memory.retain(value); + } + bjs["swift_js_struct_lower_Widget"] = function(objectId) { + structHelpers.Widget.lower(swift.memory.getObject(objectId)); + } + bjs["swift_js_struct_lift_Widget"] = function() { + const value = structHelpers.Widget.lift(); + return swift.memory.retain(value); + } + bjs["swift_js_struct_lower_Widget_Layout"] = function(objectId) { + structHelpers.Widget_Layout.lower(swift.memory.getObject(objectId)); + } + bjs["swift_js_struct_lift_Widget_Layout"] = function() { + const value = structHelpers.Widget_Layout.lift(); + return swift.memory.retain(value); + } + bjs["swift_js_struct_lower_Widget_Bounds"] = function(objectId) { + structHelpers.Widget_Bounds.lower(swift.memory.getObject(objectId)); + } + bjs["swift_js_struct_lift_Widget_Bounds"] = function() { + const value = structHelpers.Widget_Bounds.lift(); + return swift.memory.retain(value); + } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } + bjs["swift_js_return_optional_bool"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalBool = null; + } else { + tmpRetOptionalBool = value !== 0; + } + } + bjs["swift_js_return_optional_int"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalInt = null; + } else { + tmpRetOptionalInt = value | 0; + } + } + bjs["swift_js_return_optional_float"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalFloat = null; + } else { + tmpRetOptionalFloat = Math.fround(value); + } + } + bjs["swift_js_return_optional_double"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalDouble = null; + } else { + tmpRetOptionalDouble = value; + } + } + bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = decodeString(ptr, len); + } + } + bjs["swift_js_return_optional_object"] = function(isSome, objectId) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = swift.memory.getObject(objectId); + } + } + bjs["swift_js_return_optional_heap_object"] = function(isSome, pointer) { + if (isSome === 0) { + tmpRetOptionalHeapObject = null; + } else { + tmpRetOptionalHeapObject = pointer; + } + } + bjs["swift_js_get_optional_int_presence"] = function() { + return tmpRetOptionalInt != null ? 1 : 0; + } + bjs["swift_js_get_optional_int_value"] = function() { + const value = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; + return value; + } + bjs["swift_js_get_optional_string"] = function() { + const str = tmpRetString; + tmpRetString = undefined; + if (str == null) { + return -1; + } else { + const bytes = textEncoder.encode(str); + tmpRetBytes = bytes; + return bytes.length; + } + } + bjs["swift_js_get_optional_float_presence"] = function() { + return tmpRetOptionalFloat != null ? 1 : 0; + } + bjs["swift_js_get_optional_float_value"] = function() { + const value = tmpRetOptionalFloat; + tmpRetOptionalFloat = undefined; + return value; + } + bjs["swift_js_get_optional_double_presence"] = function() { + return tmpRetOptionalDouble != null ? 1 : 0; + } + bjs["swift_js_get_optional_double_value"] = function() { + const value = tmpRetOptionalDouble; + tmpRetOptionalDouble = undefined; + return value; + } + bjs["swift_js_get_optional_heap_object_pointer"] = function() { + const pointer = tmpRetOptionalHeapObject; + tmpRetOptionalHeapObject = undefined; + return pointer || 0; + } + bjs["swift_js_closure_unregister"] = function(funcRef) {} + }, + setInstance: (i) => { + instance = i; + memory = instance.exports.memory; + + decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + + setException = (error) => { + instance.exports._swift_js_exception.value = swift.memory.retain(error) + } + }, + /** @param {WebAssembly.Instance} instance */ + createExports: (instance) => { + const js = swift.memory.heap; + const ShapeHelpers = __bjs_createShapeHelpers(); + structHelpers.Shape = ShapeHelpers; + + const WidgetHelpers = __bjs_createWidgetHelpers(); + structHelpers.Widget = WidgetHelpers; + + const Widget_LayoutHelpers = __bjs_createWidget_LayoutHelpers(); + structHelpers.Widget_Layout = Widget_LayoutHelpers; + + const Widget_BoundsHelpers = __bjs_createWidget_BoundsHelpers(); + structHelpers.Widget_Bounds = Widget_BoundsHelpers; + + const exports = { + Shape: { + init: function(label) { + const labelBytes = textEncoder.encode(label); + const labelId = swift.memory.retain(labelBytes); + instance.exports.bjs_Shape_init(labelId, labelBytes.length); + const structValue = structHelpers.Shape.lift(); + return structValue; + }, + Kind: KindValues, + }, + Widget: { + init: function(name) { + const nameBytes = textEncoder.encode(name); + const nameId = swift.memory.retain(nameBytes); + instance.exports.bjs_Widget_init(nameId, nameBytes.length); + const structValue = structHelpers.Widget.lift(); + return structValue; + }, + Variant: VariantValues, + Bounds: { + init: function(width, height) { + instance.exports.bjs_Widget_Bounds_init(width, height); + const structValue = structHelpers.Widget_Bounds.lift(); + return structValue; + }, + get dimensions() { + const ret = instance.exports.bjs_Widget_Bounds_static_dimensions_get(); + return ret; + }, + zero: function() { + instance.exports.bjs_Widget_Bounds_static_zero(); + const structValue = structHelpers.Widget_Bounds.lift(); + return structValue; + }, + }, + Layout: { + Alignment: AlignmentValues, + }, + }, + }; + _exports = exports; + return exports; + }, + } +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.d.ts index 6d590950c..2f56a1cb8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.d.ts @@ -23,16 +23,16 @@ export interface PublicGreeter extends SwiftHeapObject { export interface PackageGreeter extends SwiftHeapObject { } export type Exports = { + takeGreeter(greeter: Greeter): void; Greeter: { new(name: string): Greeter; greetAnonymously(): string; readonly defaultGreeting: string; - } - PublicGreeter: { - } + }, PackageGreeter: { - } - takeGreeter(greeter: Greeter): void; + }, + PublicGreeter: { + }, } export type Imports = { jsRoundTripGreeter(greeter: Greeter): Greeter; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js index 7f9fb8a20..be63f59be 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js @@ -374,12 +374,12 @@ export async function createInstantiator(options, swift) { } const exports = { - Greeter, - PublicGreeter, - PackageGreeter, takeGreeter: function bjs_takeGreeter(greeter) { instance.exports.bjs_takeGreeter(greeter.pointer); }, + Greeter, + PackageGreeter, + PublicGreeter, }; _exports = exports; return exports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.d.ts index be62eeedd..70f23c11a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.d.ts @@ -64,12 +64,6 @@ export interface Person extends SwiftHeapObject { export interface TestProcessor extends SwiftHeapObject { } export type Exports = { - Person: { - new(name: string): Person; - } - TestProcessor: { - new(transform: (arg0: string) => string): TestProcessor; - } roundtripAnimal(animalClosure: (arg0: Animal) => Animal): (arg0: Animal) => Animal; roundtripOptionalAnimal(animalClosure: (arg0: Animal | null) => Animal | null): (arg0: Animal | null) => Animal | null; roundtripString(stringClosure: (arg0: string) => string): (arg0: string) => string; @@ -105,7 +99,13 @@ export type Exports = { APIResult: APIResultObject Animal: { init(type: string): Animal; - } + }, + Person: { + new(name: string): Person; + }, + TestProcessor: { + new(transform: (arg0: string) => string): TestProcessor; + }, } export type Imports = { } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js index f5912b3f5..f3b9d987c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js @@ -1422,8 +1422,6 @@ export async function createInstantiator(options, swift) { enumHelpers.APIResult = APIResultHelpers; const exports = { - Person, - TestProcessor, roundtripAnimal: function bjs_roundtripAnimal(animalClosure) { const callbackId = swift.memory.retain(animalClosure); const ret = instance.exports.bjs_roundtripAnimal(callbackId); @@ -1576,6 +1574,8 @@ export async function createInstantiator(options, swift) { return structValue; }, }, + Person, + TestProcessor, }; _exports = exports; return exports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts index bf4ebc71f..14ddf714e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts @@ -63,24 +63,24 @@ export interface Greeter extends SwiftHeapObject { name: string; } export type Exports = { - Greeter: { - new(name: string): Greeter; - } roundtrip(session: Person): Person; roundtripContainer(container: Container): Container; Precision: PrecisionObject - DataPoint: { - init(x: number, y: number, label: string, optCount: number | null, optFlag: boolean | null): DataPoint; - readonly dimensions: number; - origin(): DataPoint; - } ConfigStruct: { readonly maxRetries: number; defaultConfig: string; timeout: number; readonly computedSetting: string; update(timeout: number): number; - } + }, + DataPoint: { + init(x: number, y: number, label: string, optCount: number | null, optFlag: boolean | null): DataPoint; + readonly dimensions: number; + origin(): DataPoint; + }, + Greeter: { + new(name: string): Greeter; + }, } export type Imports = { } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js index b25010a23..44ae8a39d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js @@ -600,7 +600,6 @@ export async function createInstantiator(options, swift) { structHelpers.Vector2D = Vector2DHelpers; const exports = { - Greeter, roundtrip: function bjs_roundtrip(session) { structHelpers.Person.lower(session); instance.exports.bjs_roundtrip(); @@ -614,26 +613,6 @@ export async function createInstantiator(options, swift) { return structValue; }, Precision: PrecisionValues, - DataPoint: { - init: function(x, y, label, optCount, optFlag) { - const labelBytes = textEncoder.encode(label); - const labelId = swift.memory.retain(labelBytes); - const isSome = optCount != null; - const isSome1 = optFlag != null; - instance.exports.bjs_DataPoint_init(x, y, labelId, labelBytes.length, +isSome, isSome ? optCount : 0, +isSome1, isSome1 ? optFlag ? 1 : 0 : 0); - const structValue = structHelpers.DataPoint.lift(); - return structValue; - }, - get dimensions() { - const ret = instance.exports.bjs_DataPoint_static_dimensions_get(); - return ret; - }, - origin: function() { - instance.exports.bjs_DataPoint_static_origin(); - const structValue = structHelpers.DataPoint.lift(); - return structValue; - }, - }, ConfigStruct: { get maxRetries() { const ret = instance.exports.bjs_ConfigStruct_static_maxRetries_get(); @@ -668,6 +647,27 @@ export async function createInstantiator(options, swift) { return ret; }, }, + DataPoint: { + init: function(x, y, label, optCount, optFlag) { + const labelBytes = textEncoder.encode(label); + const labelId = swift.memory.retain(labelBytes); + const isSome = optCount != null; + const isSome1 = optFlag != null; + instance.exports.bjs_DataPoint_init(x, y, labelId, labelBytes.length, +isSome, isSome ? optCount : 0, +isSome1, isSome1 ? optFlag ? 1 : 0 : 0); + const structValue = structHelpers.DataPoint.lift(); + return structValue; + }, + get dimensions() { + const ret = instance.exports.bjs_DataPoint_static_dimensions_get(); + return ret; + }, + origin: function() { + instance.exports.bjs_DataPoint_static_origin(); + const structValue = structHelpers.DataPoint.lift(); + return structValue; + }, + }, + Greeter, }; _exports = exports; return exports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.d.ts index 4f9aa4e4a..5a4ee78ce 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.d.ts @@ -25,7 +25,7 @@ export type Exports = { roundTripPointerFields(value: PointerFields): PointerFields; PointerFields: { init(raw: number, mutRaw: number, opaque: number, ptr: number, mutPtr: number): PointerFields; - } + }, } export type Imports = { } diff --git a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift index 282b7cc60..92bf7ff68 100644 --- a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift @@ -1359,6 +1359,27 @@ enum GraphOperations { @JS static func roundtripMetadata(_ m: Metadata) -> Metadata { m } } +@JS class NestedTypeHost { + @JS enum Variant: String { + case primary + case secondary + } + + @JS struct Label { + var text: String + + @JS init(text: String) { + self.text = text + } + } + + @JS init() {} + + @JS func describe() -> String { + "host" + } +} + class ExportAPITests: XCTestCase { func testAll() { var hasDeinitGreeter = false diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 8968773a4..ff22e7fbe 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -5797,6 +5797,9 @@ public func _bjs_NestedStructGroupB_static_roundtripMetadata() -> Void { #endif } +extension NestedTypeHost.Variant: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +} + extension LightColor: _BridgedSwiftCaseEnum { @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { return bridgeJSRawValue @@ -6573,6 +6576,63 @@ fileprivate func _bjs_struct_lift_NestedStructGroupB_Metadata_extern() -> Int32 return _bjs_struct_lift_NestedStructGroupB_Metadata_extern() } +extension NestedTypeHost.Label: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> NestedTypeHost.Label { + let text = String.bridgeJSStackPop() + return NestedTypeHost.Label(text: text) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.text.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_NestedTypeHost_Label(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_NestedTypeHost_Label())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_NestedTypeHost_Label") +fileprivate func _bjs_struct_lower_NestedTypeHost_Label_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_NestedTypeHost_Label_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_NestedTypeHost_Label(_ objectId: Int32) -> Void { + return _bjs_struct_lower_NestedTypeHost_Label_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_NestedTypeHost_Label") +fileprivate func _bjs_struct_lift_NestedTypeHost_Label_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_NestedTypeHost_Label_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_NestedTypeHost_Label() -> Int32 { + return _bjs_struct_lift_NestedTypeHost_Label_extern() +} + +@_expose(wasm, "bjs_NestedTypeHost_Label_init") +@_cdecl("bjs_NestedTypeHost_Label_init") +public func _bjs_NestedTypeHost_Label_init(_ textBytes: Int32, _ textLength: Int32) -> Void { + #if arch(wasm32) + let ret = NestedTypeHost.Label(text: String.bridgeJSLiftParameter(textBytes, textLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + extension Point: _BridgedSwiftStruct { @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Point { let y = Int.bridgeJSStackPop() @@ -12882,6 +12942,59 @@ fileprivate func _bjs_TextProcessor_wrap_extern(_ pointer: UnsafeMutableRawPoint return _bjs_TextProcessor_wrap_extern(pointer) } +@_expose(wasm, "bjs_NestedTypeHost_init") +@_cdecl("bjs_NestedTypeHost_init") +public func _bjs_NestedTypeHost_init() -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = NestedTypeHost() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_NestedTypeHost_describe") +@_cdecl("bjs_NestedTypeHost_describe") +public func _bjs_NestedTypeHost_describe(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = NestedTypeHost.bridgeJSLiftParameter(_self).describe() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_NestedTypeHost_deinit") +@_cdecl("bjs_NestedTypeHost_deinit") +public func _bjs_NestedTypeHost_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension NestedTypeHost: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_NestedTypeHost_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_NestedTypeHost_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_NestedTypeHost_wrap") +fileprivate func _bjs_NestedTypeHost_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_NestedTypeHost_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_NestedTypeHost_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_NestedTypeHost_wrap_extern(pointer) +} + @_expose(wasm, "bjs_OptionalHolder_init") @_cdecl("bjs_OptionalHolder_init") public func _bjs_OptionalHolder_init(_ nullableGreeterIsSome: Int32, _ nullableGreeterValue: UnsafeMutableRawPointer, _ undefinedNumberIsSome: Int32, _ undefinedNumberValue: Float64) -> UnsafeMutableRawPointer { diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index 25fd27d9f..018eceded 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -4705,6 +4705,43 @@ ], "swiftCallName" : "TextProcessor" }, + { + "constructor" : { + "abiName" : "bjs_NestedTypeHost_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + { + "abiName" : "bjs_NestedTypeHost_describe", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "describe", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "name" : "NestedTypeHost", + "properties" : [ + + ], + "swiftCallName" : "NestedTypeHost" + }, { "constructor" : { "abiName" : "bjs_OptionalHolder_init", @@ -10002,6 +10039,36 @@ { "associatedValues" : [ + ], + "name" : "primary" + }, + { + "associatedValues" : [ + + ], + "name" : "secondary" + } + ], + "emitStyle" : "const", + "name" : "Variant", + "namespace" : [ + "NestedTypeHost" + ], + "rawType" : "String", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "NestedTypeHost.Variant", + "tsFullPath" : "NestedTypeHost.Variant" + }, + { + "cases" : [ + { + "associatedValues" : [ + ], "name" : "red" }, @@ -18037,6 +18104,50 @@ ], "swiftCallName" : "NestedStructGroupB.Metadata" }, + { + "constructor" : { + "abiName" : "bjs_NestedTypeHost_Label_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "text", + "name" : "text", + "type" : { + "string" : { + + } + } + } + ] + }, + "methods" : [ + + ], + "name" : "Label", + "namespace" : [ + "NestedTypeHost" + ], + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "text", + "namespace" : [ + "NestedTypeHost" + ], + "type" : { + "string" : { + + } + } + } + ], + "swiftCallName" : "NestedTypeHost.Label" + }, { "methods" : [ diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index f431209dd..1bd824da5 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -683,6 +683,14 @@ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { testServer.call(exports.Networking.APIV2.Internal.SupportedMethod.Post); testServer.release(); + const nestedHost = new exports.NestedTypeHost(); + assert.equal(nestedHost.describe(), "host"); + assert.equal(exports.NestedTypeHost.Variant.Primary, "primary"); + assert.equal(exports.NestedTypeHost.Variant.Secondary, "secondary"); + const hostLabel = exports.NestedTypeHost.Label.init("Save"); + assert.equal(hostLabel.text, "Save"); + nestedHost.release(); + const s1 = { tag: exports.APIResult.Tag.Success, param0: "Cześć 🙋‍♂️" }; const f1 = { tag: exports.APIResult.Tag.Failure, param0: 42 }; const i1 = { tag: APIResultValues.Tag.Info }; From 22905075f8b61834810babe5fb9a2f613f22f398 Mon Sep 17 00:00:00 2001 From: Max Desiatov Date: Wed, 1 Jul 2026 12:59:09 +0100 Subject: [PATCH 25/50] Fix `JavaScriptEventLoop` for Embedded Swift in `main` toolchain snapshots (#784) --- .../JavaScriptEventLoop+ExecutorFactory.swift | 23 ++++++------------- 1 file changed, 7 insertions(+), 16 deletions(-) diff --git a/Sources/JavaScriptEventLoop/JavaScriptEventLoop+ExecutorFactory.swift b/Sources/JavaScriptEventLoop/JavaScriptEventLoop+ExecutorFactory.swift index 17aedca3b..d00672059 100644 --- a/Sources/JavaScriptEventLoop/JavaScriptEventLoop+ExecutorFactory.swift +++ b/Sources/JavaScriptEventLoop/JavaScriptEventLoop+ExecutorFactory.swift @@ -40,22 +40,13 @@ extension JavaScriptEventLoop: SchedulingExecutor { tolerance: C.Duration?, clock: C ) { - #if hasFeature(Embedded) - #if compiler(>=6.4) - // In Embedded Swift, ContinuousClock and SuspendingClock are unavailable. - // Hand-off the scheduling work to the Clock implementation for custom clocks. - clock.enqueue( - job, - on: self, - at: clock.now.advanced(by: delay), - tolerance: tolerance - ) + #if $Embedded + // ContinuousClock and SuspendingClock are unavailable in Embedded Swift, + // but Swift.Duration is, and every standard clock uses it. + guard let duration = delay as? Duration else { + fatalError("Unsupported clock type; only Duration-based clocks are supported in Embedded Swift") + } #else - fatalError( - "Delayed enqueue requires Swift 6.4+ in Embedded mode" - ) - #endif // #if compiler(>=6.4) (Embedded) - #else // #if hasFeature(Embedded) let duration: Duration if let _ = clock as? ContinuousClock { duration = delay as! ContinuousClock.Duration @@ -64,12 +55,12 @@ extension JavaScriptEventLoop: SchedulingExecutor { } else { fatalError("Unsupported clock type; only ContinuousClock and SuspendingClock are supported") } + #endif let milliseconds = Self.delayInMilliseconds(from: duration) self.enqueue( UnownedJob(job), withDelay: milliseconds ) - #endif // #if hasFeature(Embedded) } private static func delayInMilliseconds(from swiftDuration: Duration) -> Double { From 86097064bb078276cbd314e56141655465e9ddf9 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Wed, 1 Jul 2026 23:46:02 +0200 Subject: [PATCH 26/50] BridgeJS: Fix static property call expression for nested structs and enums --- Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift | 4 ++-- .../BridgeJSCodegenTests/ClassWithNestedTypes.swift | 2 +- .../BridgeJSCodegenTests/StructWithNestedTypes.swift | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift index 663c2362e..2cc551857 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift @@ -560,7 +560,7 @@ public class ExportSwift { func callName(for property: ExportedProperty) -> String { switch self { case .enumStatic(let enumDef): - return property.callName(prefix: enumDef.swiftCallName) + return "\(enumDef.swiftCallName).\(property.name)" case .classStatic(let klass): // property.callName() would use staticContext (the ABI name) as prefix; // use swiftCallName directly so the emitted expression is valid Swift. @@ -568,7 +568,7 @@ public class ExportSwift { case .classInstance: return property.callName() case .structStatic(let structDef): - return property.callName(prefix: structDef.swiftCallName) + return "\(structDef.swiftCallName).\(property.name)" } } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ClassWithNestedTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ClassWithNestedTypes.swift index 3ae08e13a..52c633045 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ClassWithNestedTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ClassWithNestedTypes.swift @@ -62,7 +62,7 @@ public func _bjs_Account_Credentials_init(_ tokenBytes: Int32, _ tokenLength: In @_cdecl("bjs_Account_Credentials_static_maxLength_get") public func _bjs_Account_Credentials_static_maxLength_get() -> Int32 { #if arch(wasm32) - let ret = Account_Credentials.maxLength + let ret = Account.Credentials.maxLength return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StructWithNestedTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StructWithNestedTypes.swift index f8843b7cd..ad99f0a03 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StructWithNestedTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StructWithNestedTypes.swift @@ -230,7 +230,7 @@ public func _bjs_Widget_Bounds_init(_ width: Int32, _ height: Int32) -> Void { @_cdecl("bjs_Widget_Bounds_static_dimensions_get") public func _bjs_Widget_Bounds_static_dimensions_get() -> Int32 { #if arch(wasm32) - let ret = Widget_Bounds.dimensions + let ret = Widget.Bounds.dimensions return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") From 79a58f210b6a66e1e171f3d7d564d8faafb9b099 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Wed, 1 Jul 2026 23:46:02 +0200 Subject: [PATCH 27/50] BridgeJS: Add runtime coverage for nested static members --- .../BridgeJSRuntimeTests/ExportAPITests.swift | 6 +++ .../Generated/BridgeJS.swift | 22 +++++++++++ .../Generated/JavaScript/BridgeJS.json | 39 +++++++++++++++++++ Tests/prelude.mjs | 2 + 4 files changed, 69 insertions(+) diff --git a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift index 92bf7ff68..5a852a23d 100644 --- a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift @@ -1371,6 +1371,12 @@ enum GraphOperations { @JS init(text: String) { self.text = text } + + @JS static var maxLength: Int { 64 } + + @JS static func untitled() -> Label { + Label(text: "untitled") + } } @JS init() {} diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index ff22e7fbe..a3104e685 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -6633,6 +6633,28 @@ public func _bjs_NestedTypeHost_Label_init(_ textBytes: Int32, _ textLength: Int #endif } +@_expose(wasm, "bjs_NestedTypeHost_Label_static_maxLength_get") +@_cdecl("bjs_NestedTypeHost_Label_static_maxLength_get") +public func _bjs_NestedTypeHost_Label_static_maxLength_get() -> Int32 { + #if arch(wasm32) + let ret = NestedTypeHost.Label.maxLength + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_NestedTypeHost_Label_static_untitled") +@_cdecl("bjs_NestedTypeHost_Label_static_untitled") +public func _bjs_NestedTypeHost_Label_static_untitled() -> Void { + #if arch(wasm32) + let ret = NestedTypeHost.Label.untitled() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + extension Point: _BridgedSwiftStruct { @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Point { let y = Int.bridgeJSStackPop() diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index 018eceded..451a3213d 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -18125,7 +18125,28 @@ ] }, "methods" : [ + { + "abiName" : "bjs_NestedTypeHost_Label_static_untitled", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "name" : "untitled", + "parameters" : [ + ], + "returnType" : { + "swiftStruct" : { + "_0" : "NestedTypeHost.Label" + } + }, + "staticContext" : { + "structName" : { + "_0" : "NestedTypeHost_Label" + } + } + } ], "name" : "Label", "namespace" : [ @@ -18144,6 +18165,24 @@ } } + }, + { + "isReadonly" : true, + "isStatic" : true, + "name" : "maxLength", + "staticContext" : { + "structName" : { + "_0" : "NestedTypeHost_Label" + } + }, + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } } ], "swiftCallName" : "NestedTypeHost.Label" diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index 1bd824da5..887510e65 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -689,6 +689,8 @@ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { assert.equal(exports.NestedTypeHost.Variant.Secondary, "secondary"); const hostLabel = exports.NestedTypeHost.Label.init("Save"); assert.equal(hostLabel.text, "Save"); + assert.equal(exports.NestedTypeHost.Label.maxLength, 64); + assert.equal(exports.NestedTypeHost.Label.untitled().text, "untitled"); nestedHost.release(); const s1 = { tag: exports.APIResult.Tag.Success, param0: "Cześć 🙋‍♂️" }; From bc356b5385c618bd30927c2ef0b9f8165751d006 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Wed, 8 Jul 2026 17:21:53 +0200 Subject: [PATCH 28/50] BridgeJS: Unify optional stack encoding to presence-flag form --- .../Sources/BridgeJSLink/JSGlueGen.swift | 59 ------------------- .../__Snapshots__/BridgeJSLinkTests/Alias.js | 10 ++-- .../BridgeJSLinkTests/EnumAssociatedValue.js | 10 ++-- .../JavaScriptKit/BridgeJSIntrinsics.swift | 24 ++------ 4 files changed, 16 insertions(+), 87 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift index 6e7bd7628..8ef7bbeb4 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift @@ -2195,35 +2195,6 @@ struct IntrinsicJSFragment: Sendable { wrappedType: BridgeType, kind: JSOptionalKind ) throws -> IntrinsicJSFragment { - if case .associatedValueEnum(let fullName) = wrappedType { - let base = fullName.components(separatedBy: ".").last ?? fullName - let absenceLiteral = kind.absenceLiteral - return IntrinsicJSFragment( - parameters: [], - printCode: { arguments, context in - let (scope, printer) = (context.scope, context.printer) - let caseIdVar = scope.variable("caseId") - let resultVar = scope.variable("optValue") - - printer.write("const \(caseIdVar) = \(scope.popI32());") - printer.write("let \(resultVar);") - printer.write("if (\(caseIdVar) === -1) {") - printer.indent { - printer.write("\(resultVar) = \(absenceLiteral);") - } - printer.write("} else {") - printer.indent { - printer.write( - "\(resultVar) = \(JSGlueVariableScope.reservedEnumHelpers).\(base).lift(\(caseIdVar));" - ) - } - printer.write("}") - - return [resultVar] - } - ) - } - let absenceLiteral = kind.absenceLiteral return IntrinsicJSFragment( parameters: [], @@ -2261,36 +2232,6 @@ struct IntrinsicJSFragment: Sendable { wrappedType: BridgeType, kind: JSOptionalKind ) throws -> IntrinsicJSFragment { - if case .associatedValueEnum(let fullName) = wrappedType { - let base = fullName.components(separatedBy: ".").last ?? fullName - return IntrinsicJSFragment( - parameters: ["value"], - printCode: { arguments, context in - let (scope, printer) = (context.scope, context.printer) - let value = arguments[0] - let isSomeVar = scope.variable("isSome") - let presenceExpr = kind.presenceCheck(value: value) - - printer.write("const \(isSomeVar) = \(presenceExpr) ? 1 : 0;") - printer.write("if (\(isSomeVar)) {") - printer.indent { - let caseIdVar = scope.variable("caseId") - printer.write( - "const \(caseIdVar) = \(JSGlueVariableScope.reservedEnumHelpers).\(base).lower(\(value));" - ) - scope.emitPushI32Parameter(caseIdVar, printer: printer) - } - printer.write("} else {") - printer.indent { - scope.emitPushI32Parameter("-1", printer: printer) - } - printer.write("}") - - return [] - } - ) - } - return IntrinsicJSFragment( parameters: ["value"], printCode: { arguments, context in diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js index 0b922111b..92fb5a109 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js @@ -482,9 +482,8 @@ export async function createInstantiator(options, swift) { if (isSome) { const caseId = enumHelpers.InnerTag.lower(elem); i32Stack.push(caseId); - } else { - i32Stack.push(-1); } + i32Stack.push(isSome); } i32Stack.push(xs.length); instance.exports.bjs_roundtripTags(); @@ -495,12 +494,13 @@ export async function createInstantiator(options, swift) { } else { arrayResult = []; for (let i = 0; i < arrayLen; i++) { - const caseId1 = i32Stack.pop(); + const isSome1 = i32Stack.pop(); let optValue; - if (caseId1 === -1) { + if (isSome1 === 0) { optValue = null; } else { - optValue = enumHelpers.InnerTag.lift(caseId1); + const enumValue = enumHelpers.InnerTag.lift(i32Stack.pop()); + optValue = enumValue; } arrayResult.push(optValue); } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js index 8ff3dd90d..36683fd58 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js @@ -676,9 +676,8 @@ export async function createInstantiator(options, swift) { if (isSome) { const caseId = enumHelpers.APIResult.lower(value.param0); i32Stack.push(caseId); - } else { - i32Stack.push(-1); } + i32Stack.push(isSome); return OptionalAllTypesResultValues.Tag.OptNestedEnum; } case OptionalAllTypesResultValues.Tag.OptArray: { @@ -738,12 +737,13 @@ export async function createInstantiator(options, swift) { return { tag: OptionalAllTypesResultValues.Tag.OptJSObject, param0: optValue }; } case OptionalAllTypesResultValues.Tag.OptNestedEnum: { - const caseId = i32Stack.pop(); + const isSome = i32Stack.pop(); let optValue; - if (caseId === -1) { + if (isSome === 0) { optValue = null; } else { - optValue = enumHelpers.APIResult.lift(caseId); + const enumValue = enumHelpers.APIResult.lift(i32Stack.pop()); + optValue = enumValue; } return { tag: OptionalAllTypesResultValues.Tag.OptNestedEnum, param0: optValue }; } diff --git a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift index 1fbdff0b8..a07ca0152 100644 --- a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift +++ b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift @@ -1100,23 +1100,6 @@ extension _BridgedSwiftAssociatedValueEnum { _swift_js_push_i32(bridgeJSStackPushPayload()) } - public static func bridgeJSStackPopAsOptional() -> Self? { - let discriminator = _swift_js_pop_i32() - if discriminator == -1 { - return nil - } - return bridgeJSStackPopPayload(discriminator) - } - - public static func bridgeJSStackPushAsOptional(_ value: consuming Self?) { - switch consume value { - case .none: - _swift_js_push_i32(-1) - case .some(let value): - _swift_js_push_i32(value.bridgeJSStackPushPayload()) - } - } - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ caseId: Int32) -> Self { return bridgeJSStackPopPayload(caseId) } @@ -2378,7 +2361,12 @@ extension _BridgedAsOptional where Wrapped: _BridgedSwiftAssociatedValueEnum { } @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() { - Wrapped.bridgeJSStackPushAsOptional(asOptional) + switch asOptional { + case .none: + _swift_js_push_i32(-1) + case .some(let value): + _swift_js_push_i32(value.bridgeJSStackPushPayload()) + } } } From 0717703097059655013ddd9303995f61d9b9dea3 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 20 Jul 2026 19:10:49 +0100 Subject: [PATCH 29/50] Bump actions/setup-node from 6 to 7 (#790) Bumps [actions/setup-node](https://github.com/actions/setup-node) from 6 to 7. - [Release notes](https://github.com/actions/setup-node/releases) - [Commits](https://github.com/actions/setup-node/compare/v6...v7) --- updated-dependencies: - dependency-name: actions/setup-node dependency-version: '7' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/test.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index e19fed6f2..0458dec5d 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -81,7 +81,7 @@ jobs: steps: - uses: actions/checkout@v7 - name: Setup Node.js - uses: actions/setup-node@v6 + uses: actions/setup-node@v7 with: node-version: '20' - name: Install TypeScript @@ -117,7 +117,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - - uses: actions/setup-node@v6 + - uses: actions/setup-node@v7 with: node-version: '20' - run: npm install From 0e35c39017edfa6a18d2570bdfc06ebfdcca73be Mon Sep 17 00:00:00 2001 From: William Taylor Date: Tue, 21 Jul 2026 04:11:03 +1000 Subject: [PATCH 30/50] BridgeJS: Fix syntax error in generated JS (#789) --- .../Sources/BridgeJSLink/JSGlueGen.swift | 10 +++------- .../Inputs/MacroSwift/SwiftStruct.swift | 4 ++++ .../BridgeJSCodegenTests/SwiftStruct.json | 17 +++++++++++++++++ .../BridgeJSCodegenTests/SwiftStruct.swift | 11 +++++++++++ .../BridgeJSLinkTests/DefaultParameters.js | 4 ++-- .../BridgeJSLinkTests/SwiftStruct.d.ts | 1 + .../BridgeJSLinkTests/SwiftStruct.js | 9 ++++++++- 7 files changed, 46 insertions(+), 10 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift index 8ef7bbeb4..782988751 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift @@ -2381,14 +2381,10 @@ struct IntrinsicJSFragment: Sendable { if method.returnType == .void { printer.write("\(callExpr);") } else { - printer.write("const ret = \(callExpr);") - } - - // Lift return value if needed - if method.returnType != .void { let liftFragment = try IntrinsicJSFragment.liftReturn(type: method.returnType) - let liftArgs = liftFragment.parameters.isEmpty ? [] : ["ret"] - let lifted = try liftFragment.printCode(liftArgs, context) + let returnVariable = context.scope.variable("ret") + printer.write("const \(returnVariable) = \(callExpr);") + let lifted = try liftFragment.printCode([returnVariable], context) if let liftedValue = lifted.first { printer.write("return \(liftedValue);") } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStruct.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStruct.swift index 63bb0ff8d..4d2a84763 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStruct.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/SwiftStruct.swift @@ -74,6 +74,10 @@ extension Vector2D { @JS func scaled(by factor: Double) -> Vector2D { return Vector2D(dx: dx * factor, dy: dy * factor) } + + @JS func describe() -> String { + return "Vector2D(\(dx), \(dy))" + } } extension DataPoint { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json index d1a4b6882..2fcab7cb0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.json @@ -686,6 +686,23 @@ "_0" : "Vector2D" } } + }, + { + "abiName" : "bjs_Vector2D_describe", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "describe", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } } ], "name" : "Vector2D", diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift index 9f671c711..f98038b45 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift @@ -525,6 +525,17 @@ public func _bjs_Vector2D_scaled(_ factor: Float64) -> Void { #endif } +@_expose(wasm, "bjs_Vector2D_describe") +@_cdecl("bjs_Vector2D_describe") +public func _bjs_Vector2D_describe() -> Void { + #if arch(wasm32) + let ret = Vector2D.bridgeJSLiftParameter().describe() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_roundtrip") @_cdecl("bjs_roundtrip") public func _bjs_roundtrip() -> Void { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js index b7f67fe15..ba2b7cc77 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js @@ -67,8 +67,8 @@ export async function createInstantiator(options, swift) { }.bind(instance1); instance1.multiply = function(a, b) { structHelpers.MathOperations.lower(this); - const ret = instance.exports.bjs_MathOperations_multiply(a, b); - return ret; + const ret1 = instance.exports.bjs_MathOperations_multiply(a, b); + return ret1; }.bind(instance1); return instance1; } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts index 14ddf714e..3b394fb06 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts @@ -48,6 +48,7 @@ export interface Vector2D { dy: number; magnitude(): number; scaled(factor: number): Vector2D; + describe(): string; } export type PrecisionObject = typeof PrecisionValues; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js index 44ae8a39d..92a99becb 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js @@ -237,10 +237,17 @@ export async function createInstantiator(options, swift) { }.bind(instance1); instance1.scaled = function(factor) { structHelpers.Vector2D.lower(this); - const ret = instance.exports.bjs_Vector2D_scaled(factor); + const ret1 = instance.exports.bjs_Vector2D_scaled(factor); const structValue = structHelpers.Vector2D.lift(); return structValue; }.bind(instance1); + instance1.describe = function() { + structHelpers.Vector2D.lower(this); + const ret2 = instance.exports.bjs_Vector2D_describe(); + const ret3 = tmpRetString; + tmpRetString = undefined; + return ret3; + }.bind(instance1); return instance1; } }); From de3c2fe6d1116a6b6bafdd46b306e082ea70f334 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Tue, 28 Jul 2026 17:59:14 +0200 Subject: [PATCH 31/50] BridgeJS: Fix argument order for stack-lowered imported parameters --- .../PlayBridgeJS/Generated/BridgeJS.swift | 2 +- .../Sources/BridgeJSCore/ImportTS.swift | 10 +- .../Inputs/MacroSwift/ImportArray.swift | 9 + .../BridgeJSCodegenTests/AliasInClosure.swift | 2 +- .../BridgeJSCodegenTests/ArrayTypes.swift | 2 +- .../BridgeJSCodegenTests/Async.swift | 34 +- .../AsyncAssociatedValueEnum.swift | 6 +- .../BridgeJSCodegenTests/AsyncImport.swift | 12 +- .../AsyncStaticImport.swift | 4 +- .../BridgeJSCodegenTests/DocComments.swift | 2 +- .../EnumAssociatedValueImport.swift | 4 +- .../BridgeJSCodegenTests/EnumCaseImport.swift | 2 +- .../BridgeJSCodegenTests/GlobalGetter.swift | 2 +- .../GlobalThisImports.swift | 2 +- .../BridgeJSCodegenTests/ImportArray.json | 116 +++++++ .../BridgeJSCodegenTests/ImportArray.swift | 48 +++ .../InvalidPropertyNames.swift | 16 +- .../BridgeJSCodegenTests/JSClass.swift | 10 +- .../BridgeJSCodegenTests/Optionals.swift | 36 +- .../PrimitiveParameters.swift | 2 +- .../BridgeJSCodegenTests/Protocol.swift | 32 +- .../ProtocolInClosure.swift | 6 +- .../BridgeJSCodegenTests/SwiftClosure.swift | 72 ++-- .../SwiftClosureImports.swift | 16 +- .../SwiftStructImports.swift | 4 +- .../SwiftTypedClosureAccess.swift | 14 +- .../BridgeJSLinkTests/ImportArray.d.ts | 2 + .../BridgeJSLinkTests/ImportArray.js | 79 +++++ .../Generated/BridgeJS.swift | 324 +++++++++++------- .../Generated/JavaScript/BridgeJS.json | 193 +++++++++++ .../BridgeJSRuntimeTests/ImportAPITests.swift | 27 ++ Tests/prelude.mjs | 6 + 32 files changed, 832 insertions(+), 264 deletions(-) diff --git a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift index 37b024346..10976f793 100644 --- a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift +++ b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift @@ -264,8 +264,8 @@ fileprivate func bjs_TS2Swift_convert_extern(_ self: Int32, _ tsBytes: Int32, _ } func _$TS2Swift_convert(_ self: JSObject, _ ts: String) throws(JSException) -> String { - let selfValue = self.bridgeJSLowerParameter() let ret0 = ts.bridgeJSWithLoweredParameter { (tsBytes, tsLength) in + let selfValue = self.bridgeJSLowerParameter() let ret = bjs_TS2Swift_convert(selfValue, tsBytes, tsLength) return ret } diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift index 7a37b17f0..474f1a75f 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift @@ -107,7 +107,7 @@ public struct ImportTS { let abiReturnType: WasmCoreType? // Track destructured variable names for multiple lowered parameters var destructuredVarNames: [String] = [] - // Stack-lowered parameters should be evaluated in reverse order to match LIFO stacks + // Parameters are lowered in reverse order to match the LIFO stacks they push onto var stackLoweringStmts: [String] = [] // Values to extend lifetime during call var valuesToExtendLifetimeDuringCall: [String] = [] @@ -206,12 +206,8 @@ public struct ImportTS { initializerExpr = ExprSyntax("\(raw: param.name).bridgeJSLowerParameter()") } - if loweringInfo.loweredParameters.isEmpty { - stackLoweringStmts.insert("let _ = \(initializerExpr)", at: 0) - return - } - - body.write("let \(pattern) = \(initializerExpr)") + let binding = loweringInfo.loweredParameters.isEmpty ? "_" : pattern + stackLoweringStmts.insert("let \(binding) = \(initializerExpr)", at: 0) } destructuredVarNames.append(contentsOf: destructuredNames) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ImportArray.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ImportArray.swift index cd9142a26..a603e9c78 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ImportArray.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ImportArray.swift @@ -1,2 +1,11 @@ @JSFunction func roundtrip(_ items: [Int]) throws(JSException) -> [Int] @JSFunction func logStrings(_ items: [String]) throws(JSException) + +// An optional container lowers to an `isSome` parameter *and* a stack payload, +// so it has to be ordered with the other stack-lowered parameters. +@JSFunction func optionalArrayThenArray(_ a: [Int]?, _ b: [Int]) throws(JSException) -> Int +@JSFunction func borrowedStringAroundStackParams( + _ s: String, + _ a: [Int]?, + _ b: [Int] +) throws(JSException) -> Int diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.swift index 38cc900ae..3c87bcdcc 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.swift @@ -27,8 +27,8 @@ private enum _BJS_Closure_10TestModuleAl7Polygon_Si { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0Pointer = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_TestModule_10TestModuleAl7Polygon_Si(callbackValue, param0Pointer) return Int.bridgeJSLiftReturn(ret) #else diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift index a058d13a7..51c6911bd 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift @@ -534,8 +534,8 @@ fileprivate func bjs_checkArrayWithLength_extern(_ a: Int32, _ b: Float64) -> Vo } func _$checkArrayWithLength(_ a: JSObject, _ b: Double) throws(JSException) -> Void { - let aValue = a.bridgeJSLowerParameter() let bValue = b.bridgeJSLowerParameter() + let aValue = a.bridgeJSLowerParameter() bjs_checkArrayWithLength(aValue, bValue) if let error = _swift_js_take_exception() { throw error diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift index 661fbd3a5..230676e67 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift @@ -350,8 +350,8 @@ fileprivate func promise_reject_TestModule_extern(_ promise: Int32, _ valueKind: } func _$Promise_reject(_ promise: JSObject, _ value: JSValue) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let (valueKind, valuePayload1, valuePayload2) = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_reject_TestModule(promiseValue, valueKind, valuePayload1, valuePayload2) if let error = _swift_js_take_exception() { throw error } } @@ -391,8 +391,8 @@ fileprivate func promise_resolve_TestModule_Si_extern(_ promise: Int32, _ value: } func _$Promise_resolve_Si(_ promise: JSObject, _ value: Int) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let valueValue = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_TestModule_Si(promiseValue, valueValue) if let error = _swift_js_take_exception() { throw error } } @@ -412,8 +412,8 @@ fileprivate func promise_resolve_TestModule_SS_extern(_ promise: Int32, _ valueB } func _$Promise_resolve_SS(_ promise: JSObject, _ value: String) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() value.bridgeJSWithLoweredParameter { (valueBytes, valueLength) in + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_TestModule_SS(promiseValue, valueBytes, valueLength) } if let error = _swift_js_take_exception() { throw error } @@ -434,8 +434,8 @@ fileprivate func promise_resolve_TestModule_Sb_extern(_ promise: Int32, _ value: } func _$Promise_resolve_Sb(_ promise: JSObject, _ value: Bool) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let valueValue = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_TestModule_Sb(promiseValue, valueValue) if let error = _swift_js_take_exception() { throw error } } @@ -455,8 +455,8 @@ fileprivate func promise_resolve_TestModule_Sf_extern(_ promise: Int32, _ value: } func _$Promise_resolve_Sf(_ promise: JSObject, _ value: Float) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let valueValue = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_TestModule_Sf(promiseValue, valueValue) if let error = _swift_js_take_exception() { throw error } } @@ -476,8 +476,8 @@ fileprivate func promise_resolve_TestModule_Sd_extern(_ promise: Int32, _ value: } func _$Promise_resolve_Sd(_ promise: JSObject, _ value: Double) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let valueValue = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_TestModule_Sd(promiseValue, valueValue) if let error = _swift_js_take_exception() { throw error } } @@ -497,8 +497,8 @@ fileprivate func promise_resolve_TestModule_8JSObjectC_extern(_ promise: Int32, } func _$Promise_resolve_8JSObjectC(_ promise: JSObject, _ value: JSObject) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let valueValue = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_TestModule_8JSObjectC(promiseValue, valueValue) if let error = _swift_js_take_exception() { throw error } } @@ -518,8 +518,8 @@ fileprivate func promise_resolve_TestModule_10AsyncPointV_extern(_ promise: Int3 } func _$Promise_resolve_10AsyncPointV(_ promise: JSObject, _ value: AsyncPoint) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let valueObjectId = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_TestModule_10AsyncPointV(promiseValue, valueObjectId) if let error = _swift_js_take_exception() { throw error } } @@ -539,8 +539,8 @@ fileprivate func promise_resolve_TestModule_14AsyncDirectionO_extern(_ promise: } func _$Promise_resolve_14AsyncDirectionO(_ promise: JSObject, _ value: AsyncDirection) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let valueValue = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_TestModule_14AsyncDirectionO(promiseValue, valueValue) if let error = _swift_js_take_exception() { throw error } } @@ -560,8 +560,8 @@ fileprivate func promise_resolve_TestModule_10AsyncThemeO_extern(_ promise: Int3 } func _$Promise_resolve_10AsyncThemeO(_ promise: JSObject, _ value: AsyncTheme) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() value.bridgeJSWithLoweredParameter { (valueBytes, valueLength) in + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_TestModule_10AsyncThemeO(promiseValue, valueBytes, valueLength) } if let error = _swift_js_take_exception() { throw error } @@ -582,8 +582,8 @@ fileprivate func promise_resolve_TestModule_Sq14AsyncDirectionO_extern(_ promise } func _$Promise_resolve_Sq14AsyncDirectionO(_ promise: JSObject, _ value: Optional) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let (valueIsSome, valueValue) = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_TestModule_Sq14AsyncDirectionO(promiseValue, valueIsSome, valueValue) if let error = _swift_js_take_exception() { throw error } } @@ -603,8 +603,8 @@ fileprivate func promise_resolve_TestModule_Sq10AsyncThemeO_extern(_ promise: In } func _$Promise_resolve_Sq10AsyncThemeO(_ promise: JSObject, _ value: Optional) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() value.bridgeJSWithLoweredParameter { (valueIsSome, valueBytes, valueLength) in + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_TestModule_Sq10AsyncThemeO(promiseValue, valueIsSome, valueBytes, valueLength) } if let error = _swift_js_take_exception() { throw error } @@ -625,8 +625,8 @@ fileprivate func promise_resolve_TestModule_Sq10AsyncPointV_extern(_ promise: In } func _$Promise_resolve_Sq10AsyncPointV(_ promise: JSObject, _ value: Optional) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let valueIsSome = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_TestModule_Sq10AsyncPointV(promiseValue, valueIsSome) if let error = _swift_js_take_exception() { throw error } } @@ -646,8 +646,8 @@ fileprivate func promise_resolve_TestModule_Sa10AsyncPointV_extern(_ promise: In } func _$Promise_resolve_Sa10AsyncPointV(_ promise: JSObject, _ value: [AsyncPoint]) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let _ = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_TestModule_Sa10AsyncPointV(promiseValue) if let error = _swift_js_take_exception() { throw error } } @@ -667,8 +667,8 @@ fileprivate func promise_resolve_TestModule_Sa14AsyncDirectionO_extern(_ promise } func _$Promise_resolve_Sa14AsyncDirectionO(_ promise: JSObject, _ value: [AsyncDirection]) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let _ = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_TestModule_Sa14AsyncDirectionO(promiseValue) if let error = _swift_js_take_exception() { throw error } } @@ -688,8 +688,8 @@ fileprivate func promise_resolve_TestModule_SD10AsyncPointV_extern(_ promise: In } func _$Promise_resolve_SD10AsyncPointV(_ promise: JSObject, _ value: [String: AsyncPoint]) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let _ = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_TestModule_SD10AsyncPointV(promiseValue) if let error = _swift_js_take_exception() { throw error } } @@ -709,8 +709,8 @@ fileprivate func promise_resolve_TestModule_SD14AsyncDirectionO_extern(_ promise } func _$Promise_resolve_SD14AsyncDirectionO(_ promise: JSObject, _ value: [String: AsyncDirection]) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let _ = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_TestModule_SD14AsyncDirectionO(promiseValue) if let error = _swift_js_take_exception() { throw error } } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncAssociatedValueEnum.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncAssociatedValueEnum.swift index 7ceb8cfe3..3208eda33 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncAssociatedValueEnum.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncAssociatedValueEnum.swift @@ -67,8 +67,8 @@ fileprivate func promise_reject_TestModule_extern(_ promise: Int32, _ valueKind: } func _$Promise_reject(_ promise: JSObject, _ value: JSValue) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let (valueKind, valuePayload1, valuePayload2) = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_reject_TestModule(promiseValue, valueKind, valuePayload1, valuePayload2) if let error = _swift_js_take_exception() { throw error } } @@ -88,8 +88,8 @@ fileprivate func promise_resolve_TestModule_18AsyncPayloadResultO_extern(_ promi } func _$Promise_resolve_18AsyncPayloadResultO(_ promise: JSObject, _ value: AsyncPayloadResult) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let valueCaseId = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_TestModule_18AsyncPayloadResultO(promiseValue, valueCaseId) if let error = _swift_js_take_exception() { throw error } } @@ -109,8 +109,8 @@ fileprivate func promise_resolve_TestModule_Sq18AsyncPayloadResultO_extern(_ pro } func _$Promise_resolve_Sq18AsyncPayloadResultO(_ promise: JSObject, _ value: Optional) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let (valueIsSome, valueCaseId) = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_TestModule_Sq18AsyncPayloadResultO(promiseValue, valueIsSome, valueCaseId) if let error = _swift_js_take_exception() { throw error } } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncImport.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncImport.swift index 7a60bc6b7..9568a4426 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncImport.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncImport.swift @@ -27,8 +27,8 @@ private enum _BJS_Closure_10TestModules7JSValueV_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let (param0Kind, param0Payload1, param0Payload2) = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_TestModule_10TestModules7JSValueV_y(callbackValue, param0Kind, param0Payload1, param0Payload2) #else fatalError("Only available on WebAssembly") @@ -88,8 +88,8 @@ private enum _BJS_Closure_10TestModules8JSObjectC_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_TestModule_10TestModules8JSObjectC_y(callbackValue, param0Value) #else fatalError("Only available on WebAssembly") @@ -149,8 +149,8 @@ private enum _BJS_Closure_10TestModulesSS_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_TestModule_10TestModulesSS_y(callbackValue, param0Bytes, param0Length) } #else @@ -211,8 +211,8 @@ private enum _BJS_Closure_10TestModulesSb_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_TestModule_10TestModulesSb_y(callbackValue, param0Value) #else fatalError("Only available on WebAssembly") @@ -272,8 +272,8 @@ private enum _BJS_Closure_10TestModulesSd_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_TestModule_10TestModulesSd_y(callbackValue, param0Value) #else fatalError("Only available on WebAssembly") @@ -333,8 +333,8 @@ private enum _BJS_Closure_10TestModulesSi_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_TestModule_10TestModulesSi_y(callbackValue, param0Value) #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncStaticImport.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncStaticImport.swift index ee7dc73e7..40b2a009e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncStaticImport.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncStaticImport.swift @@ -27,8 +27,8 @@ private enum _BJS_Closure_10TestModules7JSValueV_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let (param0Kind, param0Payload1, param0Payload2) = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_TestModule_10TestModules7JSValueV_y(callbackValue, param0Kind, param0Payload1, param0Payload2) #else fatalError("Only available on WebAssembly") @@ -88,8 +88,8 @@ private enum _BJS_Closure_10TestModulesSd_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_TestModule_10TestModulesSd_y(callbackValue, param0Value) #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DocComments.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DocComments.swift index eaed9e413..f91df6c26 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DocComments.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DocComments.swift @@ -2,8 +2,8 @@ struct AnyListener: Listener, _BridgedSwiftProtocolWrapper { let jsObject: JSObject func onEvent(id: Int) -> Void { - let jsObjectValue = jsObject.bridgeJSLowerParameter() let idValue = id.bridgeJSLowerParameter() + let jsObjectValue = jsObject.bridgeJSLowerParameter() _extern_onEvent(jsObjectValue, idValue) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValueImport.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValueImport.swift index 5e1db5c72..55d1992a3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValueImport.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValueImport.swift @@ -84,8 +84,8 @@ func _$PayloadSignalControls_roundTrip(_ signal: PayloadSignal) throws(JSExcepti } func _$PayloadSignalControls_send(_ self: JSObject, _ signal: PayloadSignal) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() let signalCaseId = signal.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() bjs_PayloadSignalControls_send(selfValue, signalCaseId) if let error = _swift_js_take_exception() { throw error @@ -102,8 +102,8 @@ func _$PayloadSignalControls_current(_ self: JSObject) throws(JSException) -> Pa } func _$PayloadSignalControls_roundTripOptional(_ self: JSObject, _ signal: Optional) throws(JSException) -> Optional { - let selfValue = self.bridgeJSLowerParameter() let (signalIsSome, signalCaseId) = signal.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() let ret = bjs_PayloadSignalControls_roundTripOptional(selfValue, signalIsSome, signalCaseId) if let error = _swift_js_take_exception() { throw error diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCaseImport.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCaseImport.swift index 3487ad425..f297e1620 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCaseImport.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCaseImport.swift @@ -79,8 +79,8 @@ func _$SignalControls_roundTrip(_ signal: Signal) throws(JSException) -> Signal } func _$SignalControls_send(_ self: JSObject, _ signal: Signal) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() let signalValue = signal.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() bjs_SignalControls_send(selfValue, signalValue) if let error = _swift_js_take_exception() { throw error diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalGetter.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalGetter.swift index 5e7088db8..68afce080 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalGetter.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalGetter.swift @@ -31,8 +31,8 @@ fileprivate func bjs_JSConsole_log_extern(_ self: Int32, _ messageBytes: Int32, } func _$JSConsole_log(_ self: JSObject, _ message: String) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() message.bridgeJSWithLoweredParameter { (messageBytes, messageLength) in + let selfValue = self.bridgeJSLowerParameter() bjs_JSConsole_log(selfValue, messageBytes, messageLength) } if let error = _swift_js_take_exception() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalThisImports.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalThisImports.swift index 35b1c6281..4ba7a26fe 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalThisImports.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GlobalThisImports.swift @@ -55,8 +55,8 @@ fileprivate func bjs_JSConsole_log_extern(_ self: Int32, _ messageBytes: Int32, } func _$JSConsole_log(_ self: JSObject, _ message: String) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() message.bridgeJSWithLoweredParameter { (messageBytes, messageLength) in + let selfValue = self.bridgeJSLowerParameter() bjs_JSConsole_log(selfValue, messageBytes, messageLength) } if let error = _swift_js_take_exception() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.json index 7bf447ad5..4d9bcc87f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.json @@ -68,6 +68,122 @@ } } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "optionalArrayThenArray", + "parameters" : [ + { + "name" : "a", + "type" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + }, + "_1" : "null" + } + } + }, + { + "name" : "b", + "type" : { + "array" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "borrowedStringAroundStackParams", + "parameters" : [ + { + "name" : "s", + "type" : { + "string" : { + + } + } + }, + { + "name" : "a", + "type" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + }, + "_1" : "null" + } + } + }, + { + "name" : "b", + "type" : { + "array" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } } ], "types" : [ diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.swift index db1f136e7..9c4b49e3c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.swift @@ -37,4 +37,52 @@ func _$logStrings(_ items: [String]) throws(JSException) -> Void { if let error = _swift_js_take_exception() { throw error } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_optionalArrayThenArray") +fileprivate func bjs_optionalArrayThenArray_extern(_ a: Int32) -> Int32 +#else +fileprivate func bjs_optionalArrayThenArray_extern(_ a: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_optionalArrayThenArray(_ a: Int32) -> Int32 { + return bjs_optionalArrayThenArray_extern(a) +} + +func _$optionalArrayThenArray(_ a: Optional<[Int]>, _ b: [Int]) throws(JSException) -> Int { + let _ = b.bridgeJSLowerParameter() + let aIsSome = a.bridgeJSLowerParameter() + let ret = bjs_optionalArrayThenArray(aIsSome) + if let error = _swift_js_take_exception() { + throw error + } + return Int.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_borrowedStringAroundStackParams") +fileprivate func bjs_borrowedStringAroundStackParams_extern(_ sBytes: Int32, _ sLength: Int32, _ a: Int32) -> Int32 +#else +fileprivate func bjs_borrowedStringAroundStackParams_extern(_ sBytes: Int32, _ sLength: Int32, _ a: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_borrowedStringAroundStackParams(_ sBytes: Int32, _ sLength: Int32, _ a: Int32) -> Int32 { + return bjs_borrowedStringAroundStackParams_extern(sBytes, sLength, a) +} + +func _$borrowedStringAroundStackParams(_ s: String, _ a: Optional<[Int]>, _ b: [Int]) throws(JSException) -> Int { + let ret0 = s.bridgeJSWithLoweredParameter { (sBytes, sLength) in + let _ = b.bridgeJSLowerParameter() + let aIsSome = a.bridgeJSLowerParameter() + let ret = bjs_borrowedStringAroundStackParams(sBytes, sLength, aIsSome) + return ret + } + let ret = ret0 + if let error = _swift_js_take_exception() { + throw error + } + return Int.bridgeJSLiftReturn(ret) } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/InvalidPropertyNames.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/InvalidPropertyNames.swift index 7f7fa8685..f82632737 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/InvalidPropertyNames.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/InvalidPropertyNames.swift @@ -327,8 +327,8 @@ func _$WeirdNaming_Any_get(_ self: JSObject) throws(JSException) -> String { } func _$WeirdNaming_normalProperty_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() newValue.bridgeJSWithLoweredParameter { (newValueBytes, newValueLength) in + let selfValue = self.bridgeJSLowerParameter() bjs_WeirdNaming_normalProperty_set(selfValue, newValueBytes, newValueLength) } if let error = _swift_js_take_exception() { @@ -337,8 +337,8 @@ func _$WeirdNaming_normalProperty_set(_ self: JSObject, _ newValue: String) thro } func _$WeirdNaming_property_with_dashes_set(_ self: JSObject, _ newValue: Double) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() let newValueValue = newValue.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() bjs_WeirdNaming_property_with_dashes_set(selfValue, newValueValue) if let error = _swift_js_take_exception() { throw error @@ -346,8 +346,8 @@ func _$WeirdNaming_property_with_dashes_set(_ self: JSObject, _ newValue: Double } func _$WeirdNaming__123invalidStart_set(_ self: JSObject, _ newValue: Bool) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() let newValueValue = newValue.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() bjs_WeirdNaming__123invalidStart_set(selfValue, newValueValue) if let error = _swift_js_take_exception() { throw error @@ -355,8 +355,8 @@ func _$WeirdNaming__123invalidStart_set(_ self: JSObject, _ newValue: Bool) thro } func _$WeirdNaming_property_with_spaces_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() newValue.bridgeJSWithLoweredParameter { (newValueBytes, newValueLength) in + let selfValue = self.bridgeJSLowerParameter() bjs_WeirdNaming_property_with_spaces_set(selfValue, newValueBytes, newValueLength) } if let error = _swift_js_take_exception() { @@ -365,8 +365,8 @@ func _$WeirdNaming_property_with_spaces_set(_ self: JSObject, _ newValue: String } func _$WeirdNaming__specialChar_set(_ self: JSObject, _ newValue: Double) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() let newValueValue = newValue.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() bjs_WeirdNaming__specialChar_set(selfValue, newValueValue) if let error = _swift_js_take_exception() { throw error @@ -374,8 +374,8 @@ func _$WeirdNaming__specialChar_set(_ self: JSObject, _ newValue: Double) throws } func _$WeirdNaming_constructor_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() newValue.bridgeJSWithLoweredParameter { (newValueBytes, newValueLength) in + let selfValue = self.bridgeJSLowerParameter() bjs_WeirdNaming_constructor_set(selfValue, newValueBytes, newValueLength) } if let error = _swift_js_take_exception() { @@ -384,8 +384,8 @@ func _$WeirdNaming_constructor_set(_ self: JSObject, _ newValue: String) throws( } func _$WeirdNaming_for_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() newValue.bridgeJSWithLoweredParameter { (newValueBytes, newValueLength) in + let selfValue = self.bridgeJSLowerParameter() bjs_WeirdNaming_for_set(selfValue, newValueBytes, newValueLength) } if let error = _swift_js_take_exception() { @@ -394,8 +394,8 @@ func _$WeirdNaming_for_set(_ self: JSObject, _ newValue: String) throws(JSExcept } func _$WeirdNaming_any_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() newValue.bridgeJSWithLoweredParameter { (newValueBytes, newValueLength) in + let selfValue = self.bridgeJSLowerParameter() bjs_WeirdNaming_any_set(selfValue, newValueBytes, newValueLength) } if let error = _swift_js_take_exception() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClass.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClass.swift index 3e1de0030..37009f318 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClass.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSClass.swift @@ -121,8 +121,8 @@ func _$Greeter_age_get(_ self: JSObject) throws(JSException) -> Double { } func _$Greeter_name_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() newValue.bridgeJSWithLoweredParameter { (newValueBytes, newValueLength) in + let selfValue = self.bridgeJSLowerParameter() bjs_Greeter_name_set(selfValue, newValueBytes, newValueLength) } if let error = _swift_js_take_exception() { @@ -140,8 +140,8 @@ func _$Greeter_greet(_ self: JSObject) throws(JSException) -> String { } func _$Greeter_changeName(_ self: JSObject, _ name: String) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() name.bridgeJSWithLoweredParameter { (nameBytes, nameLength) in + let selfValue = self.bridgeJSLowerParameter() bjs_Greeter_changeName(selfValue, nameBytes, nameLength) } if let error = _swift_js_take_exception() { @@ -174,9 +174,9 @@ fileprivate func bjs_Animatable_getAnimations_extern(_ self: Int32, _ options: I } func _$Animatable_animate(_ self: JSObject, _ keyframes: JSObject, _ options: JSObject) throws(JSException) -> JSObject { - let selfValue = self.bridgeJSLowerParameter() - let keyframesValue = keyframes.bridgeJSLowerParameter() let optionsValue = options.bridgeJSLowerParameter() + let keyframesValue = keyframes.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() let ret = bjs_Animatable_animate(selfValue, keyframesValue, optionsValue) if let error = _swift_js_take_exception() { throw error @@ -185,8 +185,8 @@ func _$Animatable_animate(_ self: JSObject, _ keyframes: JSObject, _ options: JS } func _$Animatable_getAnimations(_ self: JSObject, _ options: JSObject) throws(JSException) -> JSObject { - let selfValue = self.bridgeJSLowerParameter() let optionsValue = options.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() let ret = bjs_Animatable_getAnimations(selfValue, optionsValue) if let error = _swift_js_take_exception() { throw error diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.swift index 65380d1e3..f96fe39ff 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Optionals.swift @@ -873,8 +873,8 @@ func _$WithOptionalJSClass_childOrNull_get(_ self: JSObject) throws(JSException) } func _$WithOptionalJSClass_stringOrNull_set(_ self: JSObject, _ newValue: Optional) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() newValue.bridgeJSWithLoweredParameter { (newValueIsSome, newValueBytes, newValueLength) in + let selfValue = self.bridgeJSLowerParameter() bjs_WithOptionalJSClass_stringOrNull_set(selfValue, newValueIsSome, newValueBytes, newValueLength) } if let error = _swift_js_take_exception() { @@ -883,8 +883,8 @@ func _$WithOptionalJSClass_stringOrNull_set(_ self: JSObject, _ newValue: Option } func _$WithOptionalJSClass_stringOrUndefined_set(_ self: JSObject, _ newValue: JSUndefinedOr) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() newValue.bridgeJSWithLoweredParameter { (newValueIsSome, newValueBytes, newValueLength) in + let selfValue = self.bridgeJSLowerParameter() bjs_WithOptionalJSClass_stringOrUndefined_set(selfValue, newValueIsSome, newValueBytes, newValueLength) } if let error = _swift_js_take_exception() { @@ -893,8 +893,8 @@ func _$WithOptionalJSClass_stringOrUndefined_set(_ self: JSObject, _ newValue: J } func _$WithOptionalJSClass_doubleOrNull_set(_ self: JSObject, _ newValue: Optional) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() let (newValueIsSome, newValueValue) = newValue.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() bjs_WithOptionalJSClass_doubleOrNull_set(selfValue, newValueIsSome, newValueValue) if let error = _swift_js_take_exception() { throw error @@ -902,8 +902,8 @@ func _$WithOptionalJSClass_doubleOrNull_set(_ self: JSObject, _ newValue: Option } func _$WithOptionalJSClass_doubleOrUndefined_set(_ self: JSObject, _ newValue: JSUndefinedOr) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() let (newValueIsSome, newValueValue) = newValue.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() bjs_WithOptionalJSClass_doubleOrUndefined_set(selfValue, newValueIsSome, newValueValue) if let error = _swift_js_take_exception() { throw error @@ -911,8 +911,8 @@ func _$WithOptionalJSClass_doubleOrUndefined_set(_ self: JSObject, _ newValue: J } func _$WithOptionalJSClass_boolOrNull_set(_ self: JSObject, _ newValue: Optional) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() let (newValueIsSome, newValueValue) = newValue.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() bjs_WithOptionalJSClass_boolOrNull_set(selfValue, newValueIsSome, newValueValue) if let error = _swift_js_take_exception() { throw error @@ -920,8 +920,8 @@ func _$WithOptionalJSClass_boolOrNull_set(_ self: JSObject, _ newValue: Optional } func _$WithOptionalJSClass_boolOrUndefined_set(_ self: JSObject, _ newValue: JSUndefinedOr) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() let (newValueIsSome, newValueValue) = newValue.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() bjs_WithOptionalJSClass_boolOrUndefined_set(selfValue, newValueIsSome, newValueValue) if let error = _swift_js_take_exception() { throw error @@ -929,8 +929,8 @@ func _$WithOptionalJSClass_boolOrUndefined_set(_ self: JSObject, _ newValue: JSU } func _$WithOptionalJSClass_intOrNull_set(_ self: JSObject, _ newValue: Optional) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() let (newValueIsSome, newValueValue) = newValue.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() bjs_WithOptionalJSClass_intOrNull_set(selfValue, newValueIsSome, newValueValue) if let error = _swift_js_take_exception() { throw error @@ -938,8 +938,8 @@ func _$WithOptionalJSClass_intOrNull_set(_ self: JSObject, _ newValue: Optional< } func _$WithOptionalJSClass_intOrUndefined_set(_ self: JSObject, _ newValue: JSUndefinedOr) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() let (newValueIsSome, newValueValue) = newValue.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() bjs_WithOptionalJSClass_intOrUndefined_set(selfValue, newValueIsSome, newValueValue) if let error = _swift_js_take_exception() { throw error @@ -947,8 +947,8 @@ func _$WithOptionalJSClass_intOrUndefined_set(_ self: JSObject, _ newValue: JSUn } func _$WithOptionalJSClass_childOrNull_set(_ self: JSObject, _ newValue: Optional) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() let (newValueIsSome, newValueValue) = newValue.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() bjs_WithOptionalJSClass_childOrNull_set(selfValue, newValueIsSome, newValueValue) if let error = _swift_js_take_exception() { throw error @@ -956,8 +956,8 @@ func _$WithOptionalJSClass_childOrNull_set(_ self: JSObject, _ newValue: Optiona } func _$WithOptionalJSClass_roundTripStringOrNull(_ self: JSObject, _ value: Optional) throws(JSException) -> Optional { - let selfValue = self.bridgeJSLowerParameter() value.bridgeJSWithLoweredParameter { (valueIsSome, valueBytes, valueLength) in + let selfValue = self.bridgeJSLowerParameter() bjs_WithOptionalJSClass_roundTripStringOrNull(selfValue, valueIsSome, valueBytes, valueLength) } if let error = _swift_js_take_exception() { @@ -967,8 +967,8 @@ func _$WithOptionalJSClass_roundTripStringOrNull(_ self: JSObject, _ value: Opti } func _$WithOptionalJSClass_roundTripStringOrUndefined(_ self: JSObject, _ value: JSUndefinedOr) throws(JSException) -> JSUndefinedOr { - let selfValue = self.bridgeJSLowerParameter() value.bridgeJSWithLoweredParameter { (valueIsSome, valueBytes, valueLength) in + let selfValue = self.bridgeJSLowerParameter() bjs_WithOptionalJSClass_roundTripStringOrUndefined(selfValue, valueIsSome, valueBytes, valueLength) } if let error = _swift_js_take_exception() { @@ -978,8 +978,8 @@ func _$WithOptionalJSClass_roundTripStringOrUndefined(_ self: JSObject, _ value: } func _$WithOptionalJSClass_roundTripDoubleOrNull(_ self: JSObject, _ value: Optional) throws(JSException) -> Optional { - let selfValue = self.bridgeJSLowerParameter() let (valueIsSome, valueValue) = value.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() bjs_WithOptionalJSClass_roundTripDoubleOrNull(selfValue, valueIsSome, valueValue) if let error = _swift_js_take_exception() { throw error @@ -988,8 +988,8 @@ func _$WithOptionalJSClass_roundTripDoubleOrNull(_ self: JSObject, _ value: Opti } func _$WithOptionalJSClass_roundTripDoubleOrUndefined(_ self: JSObject, _ value: JSUndefinedOr) throws(JSException) -> JSUndefinedOr { - let selfValue = self.bridgeJSLowerParameter() let (valueIsSome, valueValue) = value.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() bjs_WithOptionalJSClass_roundTripDoubleOrUndefined(selfValue, valueIsSome, valueValue) if let error = _swift_js_take_exception() { throw error @@ -998,8 +998,8 @@ func _$WithOptionalJSClass_roundTripDoubleOrUndefined(_ self: JSObject, _ value: } func _$WithOptionalJSClass_roundTripBoolOrNull(_ self: JSObject, _ value: Optional) throws(JSException) -> Optional { - let selfValue = self.bridgeJSLowerParameter() let (valueIsSome, valueValue) = value.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() let ret = bjs_WithOptionalJSClass_roundTripBoolOrNull(selfValue, valueIsSome, valueValue) if let error = _swift_js_take_exception() { throw error @@ -1008,8 +1008,8 @@ func _$WithOptionalJSClass_roundTripBoolOrNull(_ self: JSObject, _ value: Option } func _$WithOptionalJSClass_roundTripBoolOrUndefined(_ self: JSObject, _ value: JSUndefinedOr) throws(JSException) -> JSUndefinedOr { - let selfValue = self.bridgeJSLowerParameter() let (valueIsSome, valueValue) = value.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() let ret = bjs_WithOptionalJSClass_roundTripBoolOrUndefined(selfValue, valueIsSome, valueValue) if let error = _swift_js_take_exception() { throw error @@ -1018,8 +1018,8 @@ func _$WithOptionalJSClass_roundTripBoolOrUndefined(_ self: JSObject, _ value: J } func _$WithOptionalJSClass_roundTripIntOrNull(_ self: JSObject, _ value: Optional) throws(JSException) -> Optional { - let selfValue = self.bridgeJSLowerParameter() let (valueIsSome, valueValue) = value.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() bjs_WithOptionalJSClass_roundTripIntOrNull(selfValue, valueIsSome, valueValue) if let error = _swift_js_take_exception() { throw error @@ -1028,8 +1028,8 @@ func _$WithOptionalJSClass_roundTripIntOrNull(_ self: JSObject, _ value: Optiona } func _$WithOptionalJSClass_roundTripIntOrUndefined(_ self: JSObject, _ value: JSUndefinedOr) throws(JSException) -> JSUndefinedOr { - let selfValue = self.bridgeJSLowerParameter() let (valueIsSome, valueValue) = value.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() bjs_WithOptionalJSClass_roundTripIntOrUndefined(selfValue, valueIsSome, valueValue) if let error = _swift_js_take_exception() { throw error @@ -1038,8 +1038,8 @@ func _$WithOptionalJSClass_roundTripIntOrUndefined(_ self: JSObject, _ value: JS } func _$WithOptionalJSClass_roundTripChildOrNull(_ self: JSObject, _ value: Optional) throws(JSException) -> Optional { - let selfValue = self.bridgeJSLowerParameter() let (valueIsSome, valueValue) = value.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() bjs_WithOptionalJSClass_roundTripChildOrNull(selfValue, valueIsSome, valueValue) if let error = _swift_js_take_exception() { throw error diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveParameters.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveParameters.swift index 3f9448a4b..e818f2877 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveParameters.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/PrimitiveParameters.swift @@ -21,8 +21,8 @@ fileprivate func bjs_check_extern(_ a: Float64, _ b: Int32) -> Void { } func _$check(_ a: Double, _ b: Bool) throws(JSException) -> Void { - let aValue = a.bridgeJSLowerParameter() let bValue = b.bridgeJSLowerParameter() + let aValue = a.bridgeJSLowerParameter() bjs_check(aValue, bValue) if let error = _swift_js_take_exception() { throw error diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift index e8df6c966..cfda92ac0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift @@ -7,23 +7,23 @@ struct AnyMyViewControllerDelegate: MyViewControllerDelegate, _BridgedSwiftProto } func onValueChanged(_ value: String) -> Void { - let jsObjectValue = jsObject.bridgeJSLowerParameter() value.bridgeJSWithLoweredParameter { (valueBytes, valueLength) in + let jsObjectValue = jsObject.bridgeJSLowerParameter() _extern_onValueChanged(jsObjectValue, valueBytes, valueLength) } } func onCountUpdated(count: Int) -> Bool { - let jsObjectValue = jsObject.bridgeJSLowerParameter() let countValue = count.bridgeJSLowerParameter() + let jsObjectValue = jsObject.bridgeJSLowerParameter() let ret = _extern_onCountUpdated(jsObjectValue, countValue) return Bool.bridgeJSLiftReturn(ret) } func onLabelUpdated(_ prefix: String, _ suffix: String) -> Void { - let jsObjectValue = jsObject.bridgeJSLowerParameter() prefix.bridgeJSWithLoweredParameter { (prefixBytes, prefixLength) in suffix.bridgeJSWithLoweredParameter { (suffixBytes, suffixLength) in + let jsObjectValue = jsObject.bridgeJSLowerParameter() _extern_onLabelUpdated(jsObjectValue, prefixBytes, prefixLength, suffixBytes, suffixLength) } } @@ -36,8 +36,8 @@ struct AnyMyViewControllerDelegate: MyViewControllerDelegate, _BridgedSwiftProto } func onHelperUpdated(_ helper: Helper) -> Void { - let jsObjectValue = jsObject.bridgeJSLowerParameter() let helperPointer = helper.bridgeJSLowerParameter() + let jsObjectValue = jsObject.bridgeJSLowerParameter() _extern_onHelperUpdated(jsObjectValue, helperPointer) } @@ -48,8 +48,8 @@ struct AnyMyViewControllerDelegate: MyViewControllerDelegate, _BridgedSwiftProto } func onOptionalHelperUpdated(_ helper: Optional) -> Void { - let jsObjectValue = jsObject.bridgeJSLowerParameter() let (helperIsSome, helperPointer) = helper.bridgeJSLowerParameter() + let jsObjectValue = jsObject.bridgeJSLowerParameter() _extern_onOptionalHelperUpdated(jsObjectValue, helperIsSome, helperPointer) } @@ -66,8 +66,8 @@ struct AnyMyViewControllerDelegate: MyViewControllerDelegate, _BridgedSwiftProto } func handleResult(_ result: Result) -> Void { - let jsObjectValue = jsObject.bridgeJSLowerParameter() let resultCaseId = result.bridgeJSLowerParameter() + let jsObjectValue = jsObject.bridgeJSLowerParameter() _extern_handleResult(jsObjectValue, resultCaseId) } @@ -84,8 +84,8 @@ struct AnyMyViewControllerDelegate: MyViewControllerDelegate, _BridgedSwiftProto return Int.bridgeJSLiftReturn(ret) } set { - let jsObjectValue = jsObject.bridgeJSLowerParameter() let newValueValue = newValue.bridgeJSLowerParameter() + let jsObjectValue = jsObject.bridgeJSLowerParameter() bjs_MyViewControllerDelegate_eventCount_set(jsObjectValue, newValueValue) } } @@ -105,8 +105,8 @@ struct AnyMyViewControllerDelegate: MyViewControllerDelegate, _BridgedSwiftProto return Optional.bridgeJSLiftReturnFromSideChannel() } set { - let jsObjectValue = jsObject.bridgeJSLowerParameter() newValue.bridgeJSWithLoweredParameter { (newValueIsSome, newValueBytes, newValueLength) in + let jsObjectValue = jsObject.bridgeJSLowerParameter() bjs_MyViewControllerDelegate_optionalName_set(jsObjectValue, newValueIsSome, newValueBytes, newValueLength) } } @@ -119,8 +119,8 @@ struct AnyMyViewControllerDelegate: MyViewControllerDelegate, _BridgedSwiftProto return Optional.bridgeJSLiftReturnFromSideChannel() } set { - let jsObjectValue = jsObject.bridgeJSLowerParameter() newValue.bridgeJSWithLoweredParameter { (newValueIsSome, newValueBytes, newValueLength) in + let jsObjectValue = jsObject.bridgeJSLowerParameter() bjs_MyViewControllerDelegate_optionalRawEnum_set(jsObjectValue, newValueIsSome, newValueBytes, newValueLength) } } @@ -133,8 +133,8 @@ struct AnyMyViewControllerDelegate: MyViewControllerDelegate, _BridgedSwiftProto return ExampleEnum.bridgeJSLiftReturn(ret) } set { - let jsObjectValue = jsObject.bridgeJSLowerParameter() newValue.bridgeJSWithLoweredParameter { (newValueBytes, newValueLength) in + let jsObjectValue = jsObject.bridgeJSLowerParameter() bjs_MyViewControllerDelegate_rawStringEnum_set(jsObjectValue, newValueBytes, newValueLength) } } @@ -147,8 +147,8 @@ struct AnyMyViewControllerDelegate: MyViewControllerDelegate, _BridgedSwiftProto return Result.bridgeJSLiftReturn(ret) } set { - let jsObjectValue = jsObject.bridgeJSLowerParameter() let newValueCaseId = newValue.bridgeJSLowerParameter() + let jsObjectValue = jsObject.bridgeJSLowerParameter() bjs_MyViewControllerDelegate_result_set(jsObjectValue, newValueCaseId) } } @@ -160,8 +160,8 @@ struct AnyMyViewControllerDelegate: MyViewControllerDelegate, _BridgedSwiftProto return Optional.bridgeJSLiftReturn(ret) } set { - let jsObjectValue = jsObject.bridgeJSLowerParameter() let (newValueIsSome, newValueCaseId) = newValue.bridgeJSLowerParameter() + let jsObjectValue = jsObject.bridgeJSLowerParameter() bjs_MyViewControllerDelegate_optionalResult_set(jsObjectValue, newValueIsSome, newValueCaseId) } } @@ -173,8 +173,8 @@ struct AnyMyViewControllerDelegate: MyViewControllerDelegate, _BridgedSwiftProto return Direction.bridgeJSLiftReturn(ret) } set { - let jsObjectValue = jsObject.bridgeJSLowerParameter() let newValueValue = newValue.bridgeJSLowerParameter() + let jsObjectValue = jsObject.bridgeJSLowerParameter() bjs_MyViewControllerDelegate_direction_set(jsObjectValue, newValueValue) } } @@ -186,8 +186,8 @@ struct AnyMyViewControllerDelegate: MyViewControllerDelegate, _BridgedSwiftProto return Optional.bridgeJSLiftReturn(ret) } set { - let jsObjectValue = jsObject.bridgeJSLowerParameter() let (newValueIsSome, newValueValue) = newValue.bridgeJSLowerParameter() + let jsObjectValue = jsObject.bridgeJSLowerParameter() bjs_MyViewControllerDelegate_directionOptional_set(jsObjectValue, newValueIsSome, newValueValue) } } @@ -199,8 +199,8 @@ struct AnyMyViewControllerDelegate: MyViewControllerDelegate, _BridgedSwiftProto return Priority.bridgeJSLiftReturn(ret) } set { - let jsObjectValue = jsObject.bridgeJSLowerParameter() let newValueValue = newValue.bridgeJSLowerParameter() + let jsObjectValue = jsObject.bridgeJSLowerParameter() bjs_MyViewControllerDelegate_priority_set(jsObjectValue, newValueValue) } } @@ -212,8 +212,8 @@ struct AnyMyViewControllerDelegate: MyViewControllerDelegate, _BridgedSwiftProto return Optional.bridgeJSLiftReturnFromSideChannel() } set { - let jsObjectValue = jsObject.bridgeJSLowerParameter() let (newValueIsSome, newValueValue) = newValue.bridgeJSLowerParameter() + let jsObjectValue = jsObject.bridgeJSLowerParameter() bjs_MyViewControllerDelegate_priorityOptional_set(jsObjectValue, newValueIsSome, newValueValue) } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.swift index 26c3d1db0..d956a6f3a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ProtocolInClosure.swift @@ -27,8 +27,8 @@ private enum _BJS_Closure_10TestModule10RenderableP_10RenderableP { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0ObjectId = (param0 as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_TestModule_10TestModule10RenderableP_10RenderableP(callbackValue, param0ObjectId) return AnyRenderable.bridgeJSLiftReturn(ret) #else @@ -90,8 +90,8 @@ private enum _BJS_Closure_10TestModule10RenderableP_SS { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0ObjectId = (param0 as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_TestModule_10TestModule10RenderableP_SS(callbackValue, param0ObjectId) return String.bridgeJSLiftReturn(ret) #else @@ -153,13 +153,13 @@ private enum _BJS_Closure_10TestModuleSq10RenderableP_SS { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let (param0IsSome, param0ObjectId): (Int32, Int32) if let param0 { (param0IsSome, param0ObjectId) = (1, (param0 as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()) } else { (param0IsSome, param0ObjectId) = (0, 0) } + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_TestModule_10TestModuleSq10RenderableP_SS(callbackValue, param0IsSome, param0ObjectId) return String.bridgeJSLiftReturn(ret) #else diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift index f8f2c76a0..e1f10ab97 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift @@ -27,8 +27,8 @@ private enum _BJS_Closure_10TestModule10HttpStatusO_10HttpStatusO { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_TestModule_10TestModule10HttpStatusO_10HttpStatusO(callbackValue, param0Value) return HttpStatus.bridgeJSLiftReturn(ret) #else @@ -90,8 +90,8 @@ private enum _BJS_Closure_10TestModule5ThemeO_5ThemeO { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_TestModule_10TestModule5ThemeO_5ThemeO(callbackValue, param0Bytes, param0Length) return ret } @@ -156,8 +156,8 @@ private enum _BJS_Closure_10TestModule6AnimalV_6AnimalV { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let _ = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_TestModule_10TestModule6AnimalV_6AnimalV(callbackValue) return Animal.bridgeJSLiftReturn() #else @@ -219,8 +219,8 @@ private enum _BJS_Closure_10TestModule6PersonC_6PersonC { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0Pointer = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_TestModule_10TestModule6PersonC_6PersonC(callbackValue, param0Pointer) return Person.bridgeJSLiftReturn(ret) #else @@ -282,8 +282,8 @@ private enum _BJS_Closure_10TestModule9APIResultO_9APIResultO { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0CaseId = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_TestModule_10TestModule9APIResultO_9APIResultO(callbackValue, param0CaseId) return APIResult.bridgeJSLiftReturn(ret) #else @@ -345,8 +345,8 @@ private enum _BJS_Closure_10TestModule9DirectionO_9DirectionO { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_TestModule_10TestModule9DirectionO_9DirectionO(callbackValue, param0Value) return Direction.bridgeJSLiftReturn(ret) #else @@ -408,8 +408,8 @@ private enum _BJS_Closure_10TestModuleKSS_Sb { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] (param0: String) throws(JSException) -> Bool in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_TestModule_10TestModuleKSS_Sb(callbackValue, param0Bytes, param0Length) return ret } @@ -491,8 +491,8 @@ private enum _BJS_Closure_10TestModuleKSS_Si { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] (param0: String) throws(JSException) -> Int in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_TestModule_10TestModuleKSS_Si(callbackValue, param0Bytes, param0Length) return ret } @@ -574,8 +574,8 @@ private enum _BJS_Closure_10TestModuleSS_SS { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_TestModule_10TestModuleSS_SS(callbackValue, param0Bytes, param0Length) return ret } @@ -640,8 +640,8 @@ private enum _BJS_Closure_10TestModuleSb_Sb { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_TestModule_10TestModuleSb_Sb(callbackValue, param0Value) return Bool.bridgeJSLiftReturn(ret) #else @@ -703,8 +703,8 @@ private enum _BJS_Closure_10TestModuleSd_Sd { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_TestModule_10TestModuleSd_Sd(callbackValue, param0Value) return Double.bridgeJSLiftReturn(ret) #else @@ -766,8 +766,8 @@ private enum _BJS_Closure_10TestModuleSf_Sf { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_TestModule_10TestModuleSf_Sf(callbackValue, param0Value) return Float.bridgeJSLiftReturn(ret) #else @@ -829,8 +829,8 @@ private enum _BJS_Closure_10TestModuleSi_Si { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_TestModule_10TestModuleSi_Si(callbackValue, param0Value) return Int.bridgeJSLiftReturn(ret) #else @@ -892,8 +892,8 @@ private enum _BJS_Closure_10TestModuleSq10HttpStatusO_Sq10HttpStatusO { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let (param0IsSome, param0Value) = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_TestModule_10TestModuleSq10HttpStatusO_Sq10HttpStatusO(callbackValue, param0IsSome, param0Value) return Optional.bridgeJSLiftReturnFromSideChannel() #else @@ -955,8 +955,8 @@ private enum _BJS_Closure_10TestModuleSq5ThemeO_Sq5ThemeO { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() param0.bridgeJSWithLoweredParameter { (param0IsSome, param0Bytes, param0Length) in + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO(callbackValue, param0IsSome, param0Bytes, param0Length) } return Optional.bridgeJSLiftReturnFromSideChannel() @@ -1019,8 +1019,8 @@ private enum _BJS_Closure_10TestModuleSq6AnimalV_Sq6AnimalV { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0IsSome = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV(callbackValue, param0IsSome) return Optional.bridgeJSLiftReturn() #else @@ -1082,8 +1082,8 @@ private enum _BJS_Closure_10TestModuleSq6PersonC_Sq6PersonC { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let (param0IsSome, param0Pointer) = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_TestModule_10TestModuleSq6PersonC_Sq6PersonC(callbackValue, param0IsSome, param0Pointer) return Optional.bridgeJSLiftReturn(ret) #else @@ -1145,8 +1145,8 @@ private enum _BJS_Closure_10TestModuleSq9APIResultO_Sq9APIResultO { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let (param0IsSome, param0CaseId) = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_TestModule_10TestModuleSq9APIResultO_Sq9APIResultO(callbackValue, param0IsSome, param0CaseId) return Optional.bridgeJSLiftReturn(ret) #else @@ -1208,8 +1208,8 @@ private enum _BJS_Closure_10TestModuleSq9DirectionO_Sq9DirectionO { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let (param0IsSome, param0Value) = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_TestModule_10TestModuleSq9DirectionO_Sq9DirectionO(callbackValue, param0IsSome, param0Value) return Optional.bridgeJSLiftReturn(ret) #else @@ -1271,8 +1271,8 @@ private enum _BJS_Closure_10TestModuleSqSS_SqSS { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() param0.bridgeJSWithLoweredParameter { (param0IsSome, param0Bytes, param0Length) in + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_TestModule_10TestModuleSqSS_SqSS(callbackValue, param0IsSome, param0Bytes, param0Length) } return Optional.bridgeJSLiftReturnFromSideChannel() @@ -1335,8 +1335,8 @@ private enum _BJS_Closure_10TestModuleSqSb_SqSb { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let (param0IsSome, param0Value) = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_TestModule_10TestModuleSqSb_SqSb(callbackValue, param0IsSome, param0Value) return Optional.bridgeJSLiftReturn(ret) #else @@ -1398,8 +1398,8 @@ private enum _BJS_Closure_10TestModuleSqSd_SqSd { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let (param0IsSome, param0Value) = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_TestModule_10TestModuleSqSd_SqSd(callbackValue, param0IsSome, param0Value) return Optional.bridgeJSLiftReturnFromSideChannel() #else @@ -1461,8 +1461,8 @@ private enum _BJS_Closure_10TestModuleSqSf_SqSf { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let (param0IsSome, param0Value) = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_TestModule_10TestModuleSqSf_SqSf(callbackValue, param0IsSome, param0Value) return Optional.bridgeJSLiftReturnFromSideChannel() #else @@ -1524,8 +1524,8 @@ private enum _BJS_Closure_10TestModuleSqSi_SqSi { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let (param0IsSome, param0Value) = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_TestModule_10TestModuleSqSi_SqSi(callbackValue, param0IsSome, param0Value) return Optional.bridgeJSLiftReturnFromSideChannel() #else @@ -1592,8 +1592,8 @@ private enum _BJS_Closure_10TestModuleYaKSS_SS { }, makeRejectClosure: { JSTypedClosure<(sending JSValue) -> Void>($0) }) { resolveRef, rejectRef in - let callbackValue = callback.bridgeJSLowerParameter() param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_TestModule_10TestModuleYaKSS_SS(resolveRef, rejectRef, callbackValue, param0Bytes, param0Length) } } @@ -1663,8 +1663,8 @@ private enum _BJS_Closure_10TestModuleYaKSb_9APIResultO { }, makeRejectClosure: { JSTypedClosure<(sending JSValue) -> Void>($0) }) { resolveRef, rejectRef in - let callbackValue = callback.bridgeJSLowerParameter() let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_TestModule_10TestModuleYaKSb_9APIResultO(resolveRef, rejectRef, callbackValue, param0Value) } return resolved @@ -1733,8 +1733,8 @@ private enum _BJS_Closure_10TestModuleYaSS_6AnimalV { }, makeRejectClosure: { JSTypedClosure<(sending JSValue) -> Void>($0) }) { resolveRef, rejectRef in - let callbackValue = callback.bridgeJSLowerParameter() param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_TestModule_10TestModuleYaSS_6AnimalV(resolveRef, rejectRef, callbackValue, param0Bytes, param0Length) } } @@ -1804,8 +1804,8 @@ private enum _BJS_Closure_10TestModuleYaSS_SS { }, makeRejectClosure: { JSTypedClosure<(sending JSValue) -> Void>($0) }) { resolveRef, rejectRef in - let callbackValue = callback.bridgeJSLowerParameter() param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_TestModule_10TestModuleYaSS_SS(resolveRef, rejectRef, callbackValue, param0Bytes, param0Length) } } @@ -1870,8 +1870,8 @@ private enum _BJS_Closure_10TestModules6AnimalV_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let _ = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_TestModule_10TestModules6AnimalV_y(callbackValue) #else fatalError("Only available on WebAssembly") @@ -1931,8 +1931,8 @@ private enum _BJS_Closure_10TestModules7JSValueV_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let (param0Kind, param0Payload1, param0Payload2) = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_TestModule_10TestModules7JSValueV_y(callbackValue, param0Kind, param0Payload1, param0Payload2) #else fatalError("Only available on WebAssembly") @@ -1992,8 +1992,8 @@ private enum _BJS_Closure_10TestModules9APIResultO_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0CaseId = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_TestModule_10TestModules9APIResultO_y(callbackValue, param0CaseId) #else fatalError("Only available on WebAssembly") @@ -2053,8 +2053,8 @@ private enum _BJS_Closure_10TestModulesSS_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_TestModule_10TestModulesSS_y(callbackValue, param0Bytes, param0Length) } #else @@ -2652,8 +2652,8 @@ fileprivate func promise_reject_TestModule_extern(_ promise: Int32, _ valueKind: } func _$Promise_reject(_ promise: JSObject, _ value: JSValue) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let (valueKind, valuePayload1, valuePayload2) = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_reject_TestModule(promiseValue, valueKind, valuePayload1, valuePayload2) if let error = _swift_js_take_exception() { throw error } } @@ -2673,8 +2673,8 @@ fileprivate func promise_resolve_TestModule_SS_extern(_ promise: Int32, _ valueB } func _$Promise_resolve_SS(_ promise: JSObject, _ value: String) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() value.bridgeJSWithLoweredParameter { (valueBytes, valueLength) in + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_TestModule_SS(promiseValue, valueBytes, valueLength) } if let error = _swift_js_take_exception() { throw error } @@ -2695,8 +2695,8 @@ fileprivate func promise_resolve_TestModule_6AnimalV_extern(_ promise: Int32, _ } func _$Promise_resolve_6AnimalV(_ promise: JSObject, _ value: Animal) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let valueObjectId = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_TestModule_6AnimalV(promiseValue, valueObjectId) if let error = _swift_js_take_exception() { throw error } } @@ -2716,8 +2716,8 @@ fileprivate func promise_resolve_TestModule_9APIResultO_extern(_ promise: Int32, } func _$Promise_resolve_9APIResultO(_ promise: JSObject, _ value: APIResult) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let valueCaseId = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_TestModule_9APIResultO(promiseValue, valueCaseId) if let error = _swift_js_take_exception() { throw error } } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.swift index 93c534c12..6f133d748 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosureImports.swift @@ -27,8 +27,8 @@ private enum _BJS_Closure_10TestModuleKSS_Sb { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] (param0: String) throws(JSException) -> Bool in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_TestModule_10TestModuleKSS_Sb(callbackValue, param0Bytes, param0Length) return ret } @@ -110,8 +110,8 @@ private enum _BJS_Closure_10TestModuleSi_Si { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_TestModule_10TestModuleSi_Si(callbackValue, param0Value) return Int.bridgeJSLiftReturn(ret) #else @@ -178,8 +178,8 @@ private enum _BJS_Closure_10TestModuleYaKSS_SS { }, makeRejectClosure: { JSTypedClosure<(sending JSValue) -> Void>($0) }) { resolveRef, rejectRef in - let callbackValue = callback.bridgeJSLowerParameter() param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_TestModule_10TestModuleYaKSS_SS(resolveRef, rejectRef, callbackValue, param0Bytes, param0Length) } } @@ -244,8 +244,8 @@ private enum _BJS_Closure_10TestModules7JSValueV_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let (param0Kind, param0Payload1, param0Payload2) = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_TestModule_10TestModules7JSValueV_y(callbackValue, param0Kind, param0Payload1, param0Payload2) #else fatalError("Only available on WebAssembly") @@ -305,8 +305,8 @@ private enum _BJS_Closure_10TestModulesSS_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_TestModule_10TestModulesSS_y(callbackValue, param0Bytes, param0Length) } #else @@ -373,8 +373,8 @@ fileprivate func promise_reject_TestModule_extern(_ promise: Int32, _ valueKind: } func _$Promise_reject(_ promise: JSObject, _ value: JSValue) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let (valueKind, valuePayload1, valuePayload2) = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_reject_TestModule(promiseValue, valueKind, valuePayload1, valuePayload2) if let error = _swift_js_take_exception() { throw error } } @@ -394,8 +394,8 @@ fileprivate func promise_resolve_TestModule_SS_extern(_ promise: Int32, _ valueB } func _$Promise_resolve_SS(_ promise: JSObject, _ value: String) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() value.bridgeJSWithLoweredParameter { (valueBytes, valueLength) in + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_TestModule_SS(promiseValue, valueBytes, valueLength) } if let error = _swift_js_take_exception() { throw error } @@ -414,9 +414,9 @@ fileprivate func bjs_applyInt_extern(_ value: Int32, _ transform: Int32) -> Int3 } func _$applyInt(_ value: Int, _ transform: @escaping (Int) -> Int) throws(JSException) -> Int { - let valueValue = value.bridgeJSLowerParameter() let transform = JSTypedClosure<(Int) -> Int>(transform) let transformFuncRef = transform.bridgeJSLowerParameter() + let valueValue = value.bridgeJSLowerParameter() let ret = withExtendedLifetime((transform)) { bjs_applyInt(valueValue, transformFuncRef) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.swift index cec50ffca..0e792ea14 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.swift @@ -59,9 +59,9 @@ fileprivate func bjs_translate_extern(_ point: Int32, _ dx: Int32, _ dy: Int32) } func _$translate(_ point: Point, _ dx: Int, _ dy: Int) throws(JSException) -> Point { - let pointObjectId = point.bridgeJSLowerParameter() - let dxValue = dx.bridgeJSLowerParameter() let dyValue = dy.bridgeJSLowerParameter() + let dxValue = dx.bridgeJSLowerParameter() + let pointObjectId = point.bridgeJSLowerParameter() let ret = bjs_translate(pointObjectId, dxValue, dyValue) if let error = _swift_js_take_exception() { throw error diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftTypedClosureAccess.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftTypedClosureAccess.swift index fbd181fcc..c86b122a1 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftTypedClosureAccess.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftTypedClosureAccess.swift @@ -27,8 +27,8 @@ private enum _BJS_Closure_10TestModule13JSPublicEventC_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_TestModule_10TestModule13JSPublicEventC_y(callbackValue, param0Value) #else fatalError("Only available on WebAssembly") @@ -88,8 +88,8 @@ private enum _BJS_Closure_10TestModule14JSPackageEventC_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_TestModule_10TestModule14JSPackageEventC_y(callbackValue, param0Value) #else fatalError("Only available on WebAssembly") @@ -149,8 +149,8 @@ private enum _BJS_Closure_10TestModule15JSInternalEventC_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_TestModule_10TestModule15JSInternalEventC_y(callbackValue, param0Value) #else fatalError("Only available on WebAssembly") @@ -206,8 +206,8 @@ fileprivate func bjs_JSPublicTarget_addInternalListener_extern(_ self: Int32, _ } func _$JSPublicTarget_addPublicListener(_ self: JSObject, _ handler: JSTypedClosure<(JSPublicEvent) -> Void>) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() let handlerFuncRef = handler.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() bjs_JSPublicTarget_addPublicListener(selfValue, handlerFuncRef) if let error = _swift_js_take_exception() { throw error @@ -215,8 +215,8 @@ func _$JSPublicTarget_addPublicListener(_ self: JSObject, _ handler: JSTypedClos } func _$JSPublicTarget_addInternalListener(_ self: JSObject, _ handler: JSTypedClosure<(JSPublicEvent) -> Void>) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() let handlerFuncRef = handler.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() bjs_JSPublicTarget_addInternalListener(selfValue, handlerFuncRef) if let error = _swift_js_take_exception() { throw error @@ -236,8 +236,8 @@ fileprivate func bjs_JSPackageTarget_addPackageListener_extern(_ self: Int32, _ } func _$JSPackageTarget_addPackageListener(_ self: JSObject, _ handler: JSTypedClosure<(JSPackageEvent) -> Void>) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() let handlerFuncRef = handler.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() bjs_JSPackageTarget_addPackageListener(selfValue, handlerFuncRef) if let error = _swift_js_take_exception() { throw error @@ -257,8 +257,8 @@ fileprivate func bjs_JSInternalTarget_addInternalListener_extern(_ self: Int32, } func _$JSInternalTarget_addInternalListener(_ self: JSObject, _ handler: JSTypedClosure<(JSInternalEvent) -> Void>) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() let handlerFuncRef = handler.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() bjs_JSInternalTarget_addInternalListener(selfValue, handlerFuncRef) if let error = _swift_js_take_exception() { throw error diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.d.ts index 5d1e2c4dc..cd4f822e2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.d.ts @@ -9,6 +9,8 @@ export type Exports = { export type Imports = { roundtrip(items: number[]): number[]; logStrings(items: string[]): void; + optionalArrayThenArray(a: number[] | null, b: number[]): number; + borrowedStringAroundStackParams(s: string, a: number[] | null, b: number[]): number; } export function createInstantiator(options: { imports: Imports; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js index 2ad7251f8..07341894e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js @@ -247,6 +247,85 @@ export async function createInstantiator(options, swift) { setException(error); } } + TestModule["bjs_optionalArrayThenArray"] = function bjs_optionalArrayThenArray(a) { + try { + let optResult; + if (a) { + const arrayLen = i32Stack.pop(); + let arrayResult; + if (arrayLen === -1) { + arrayResult = taStack.pop(); + } else { + arrayResult = []; + for (let i = 0; i < arrayLen; i++) { + const int = i32Stack.pop(); + arrayResult.push(int); + } + arrayResult.reverse(); + } + optResult = arrayResult; + } else { + optResult = null; + } + const arrayLen1 = i32Stack.pop(); + let arrayResult1; + if (arrayLen1 === -1) { + arrayResult1 = taStack.pop(); + } else { + arrayResult1 = []; + for (let i1 = 0; i1 < arrayLen1; i1++) { + const int1 = i32Stack.pop(); + arrayResult1.push(int1); + } + arrayResult1.reverse(); + } + let ret = imports.optionalArrayThenArray(optResult, arrayResult1); + return ret; + } catch (error) { + setException(error); + return 0 + } + } + TestModule["bjs_borrowedStringAroundStackParams"] = function bjs_borrowedStringAroundStackParams(sBytes, sCount, a) { + try { + const string = decodeString(sBytes, sCount); + let optResult; + if (a) { + const arrayLen = i32Stack.pop(); + let arrayResult; + if (arrayLen === -1) { + arrayResult = taStack.pop(); + } else { + arrayResult = []; + for (let i = 0; i < arrayLen; i++) { + const int = i32Stack.pop(); + arrayResult.push(int); + } + arrayResult.reverse(); + } + optResult = arrayResult; + } else { + optResult = null; + } + const arrayLen1 = i32Stack.pop(); + let arrayResult1; + if (arrayLen1 === -1) { + arrayResult1 = taStack.pop(); + } else { + arrayResult1 = []; + for (let i1 = 0; i1 < arrayLen1; i1++) { + const int1 = i32Stack.pop(); + arrayResult1.push(int1); + } + arrayResult1.reverse(); + } + let ret = imports.borrowedStringAroundStackParams(string, optResult, arrayResult1); + return ret; + } catch (error) { + setException(error); + return 0 + } + } }, setInstance: (i) => { instance = i; diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index a3104e685..201c80e22 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -37,8 +37,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTests10HttpStatusO_Si { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests10HttpStatusO_Si(callbackValue, param0Value) return Int.bridgeJSLiftReturn(ret) #else @@ -100,8 +100,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTests13DataProcessorP_13DataProcessor let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0ObjectId = (param0 as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_13DataProcessorP(callbackValue, param0ObjectId) return AnyDataProcessor.bridgeJSLiftReturn(ret) #else @@ -163,8 +163,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTests13DataProcessorP_SS { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0ObjectId = (param0 as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests13DataProcessorP_SS(callbackValue, param0ObjectId) return String.bridgeJSLiftReturn(ret) #else @@ -226,8 +226,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTests5ThemeO_SS { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_SS(callbackValue, param0Bytes, param0Length) return ret } @@ -292,8 +292,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTests5ThemeO_Sb { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests5ThemeO_Sb(callbackValue, param0Bytes, param0Length) return ret } @@ -358,8 +358,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTests7GreeterC_SS { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0Pointer = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests7GreeterC_SS(callbackValue, param0Pointer) return String.bridgeJSLiftReturn(ret) #else @@ -421,8 +421,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTests8JSObjectC_8JSObjectC { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8JSObjectC_8JSObjectC(callbackValue, param0Value) return JSObject.bridgeJSLiftReturn(ret) #else @@ -484,8 +484,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTests9APIResultO_SS { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0CaseId = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9APIResultO_SS(callbackValue, param0CaseId) return String.bridgeJSLiftReturn(ret) #else @@ -547,8 +547,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTests9DirectionO_SS { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_SS(callbackValue, param0Value) return String.bridgeJSLiftReturn(ret) #else @@ -610,8 +610,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTests9DirectionO_Sb { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9DirectionO_Sb(callbackValue, param0Value) return Bool.bridgeJSLiftReturn(ret) #else @@ -673,8 +673,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsAl7Polygon_Si { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0Pointer = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsAl7Polygon_Si(callbackValue, param0Pointer) return Int.bridgeJSLiftReturn(ret) #else @@ -736,8 +736,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsKSS_Sb { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] (param0: String) throws(JSException) -> Bool in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Sb(callbackValue, param0Bytes, param0Length) return ret } @@ -819,8 +819,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsKSS_Si { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] (param0: String) throws(JSException) -> Int in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsKSS_Si(callbackValue, param0Bytes, param0Length) return ret } @@ -902,8 +902,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSS_7GreeterC { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_7GreeterC(callbackValue, param0Bytes, param0Length) return ret } @@ -968,8 +968,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSS_SS { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let ret0 = param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSS_SS(callbackValue, param0Bytes, param0Length) return ret } @@ -1034,8 +1034,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSd_8Vector2DV { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_8Vector2DV(callbackValue, param0Value) return Vector2D.bridgeJSLiftReturn() #else @@ -1097,8 +1097,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSd_Sd { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sd(callbackValue, param0Value) return Double.bridgeJSLiftReturn(ret) #else @@ -1160,8 +1160,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSd_Sq8Vector2DV { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSd_Sq8Vector2DV(callbackValue, param0Value) return Optional.bridgeJSLiftReturn() #else @@ -1223,10 +1223,10 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSiSSSd_SS { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] (param0, param1, param2) in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() - let param0Value = param0.bridgeJSLowerParameter() let ret0 = param1.bridgeJSWithLoweredParameter { (param1Bytes, param1Length) in let param2Value = param2.bridgeJSLowerParameter() + let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSSSd_SS(callbackValue, param0Value, param1Bytes, param1Length, param2Value) return ret } @@ -1291,10 +1291,10 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSiSiSi_Si { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] (param0, param1, param2) in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() - let param0Value = param0.bridgeJSLowerParameter() - let param1Value = param1.bridgeJSLowerParameter() let param2Value = param2.bridgeJSLowerParameter() + let param1Value = param1.bridgeJSLowerParameter() + let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSiSi_Si(callbackValue, param0Value, param1Value, param2Value) return Int.bridgeJSLiftReturn(ret) #else @@ -1356,9 +1356,9 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSiSi_Si { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] (param0, param1) in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() - let param0Value = param0.bridgeJSLowerParameter() let param1Value = param1.bridgeJSLowerParameter() + let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSiSi_Si(callbackValue, param0Value, param1Value) return Int.bridgeJSLiftReturn(ret) #else @@ -1420,8 +1420,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSi_Si { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_Si(callbackValue, param0Value) return Int.bridgeJSLiftReturn(ret) #else @@ -1483,8 +1483,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSi_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSi_y(callbackValue, param0Value) #else fatalError("Only available on WebAssembly") @@ -1544,13 +1544,13 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSq13DataProcessorP_SS { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let (param0IsSome, param0ObjectId): (Int32, Int32) if let param0 { (param0IsSome, param0ObjectId) = (1, (param0 as! _BridgedSwiftProtocolExportable).bridgeJSLowerAsProtocolReturn()) } else { (param0IsSome, param0ObjectId) = (0, 0) } + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq13DataProcessorP_SS(callbackValue, param0IsSome, param0ObjectId) return String.bridgeJSLiftReturn(ret) #else @@ -1612,8 +1612,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSq5ThemeO_SS { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let ret0 = param0.bridgeJSWithLoweredParameter { (param0IsSome, param0Bytes, param0Length) in + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq5ThemeO_SS(callbackValue, param0IsSome, param0Bytes, param0Length) return ret } @@ -1678,8 +1678,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSq7GreeterC_SS { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let (param0IsSome, param0Pointer) = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_SS(callbackValue, param0IsSome, param0Pointer) return String.bridgeJSLiftReturn(ret) #else @@ -1741,8 +1741,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSq7GreeterC_Sq7GreeterC { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let (param0IsSome, param0Pointer) = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq7GreeterC_Sq7GreeterC(callbackValue, param0IsSome, param0Pointer) return Optional.bridgeJSLiftReturn(ret) #else @@ -1804,8 +1804,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSq9APIResultO_SS { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let (param0IsSome, param0CaseId) = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9APIResultO_SS(callbackValue, param0IsSome, param0CaseId) return String.bridgeJSLiftReturn(ret) #else @@ -1867,8 +1867,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSq9DirectionO_SS { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let (param0IsSome, param0Value) = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSq9DirectionO_SS(callbackValue, param0IsSome, param0Value) return String.bridgeJSLiftReturn(ret) #else @@ -1930,8 +1930,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSqSS_SS { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let ret0 = param0.bridgeJSWithLoweredParameter { (param0IsSome, param0Bytes, param0Length) in + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSS_SS(callbackValue, param0IsSome, param0Bytes, param0Length) return ret } @@ -1996,8 +1996,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsSqSi_SS { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let (param0IsSome, param0Value) = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() let ret = invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsSqSi_SS(callbackValue, param0IsSome, param0Value) return String.bridgeJSLiftReturn(ret) #else @@ -2064,8 +2064,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsYaKSS_SS { }, makeRejectClosure: { JSTypedClosure<(sending JSValue) -> Void>($0) }) { resolveRef, rejectRef in - let callbackValue = callback.bridgeJSLowerParameter() param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_SS(resolveRef, rejectRef, callbackValue, param0Bytes, param0Length) } } @@ -2135,8 +2135,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsYaKSS_y { }, makeRejectClosure: { JSTypedClosure<(sending JSValue) -> Void>($0) }) { resolveRef, rejectRef in - let callbackValue = callback.bridgeJSLowerParameter() param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSS_y(resolveRef, rejectRef, callbackValue, param0Bytes, param0Length) } } @@ -2205,8 +2205,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO { }, makeRejectClosure: { JSTypedClosure<(sending JSValue) -> Void>($0) }) { resolveRef, rejectRef in - let callbackValue = callback.bridgeJSLowerParameter() let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaKSb_18AsyncPayloadResultO(resolveRef, rejectRef, callbackValue, param0Value) } return resolved @@ -2275,8 +2275,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsYaSS_SS { }, makeRejectClosure: { JSTypedClosure<(sending JSValue) -> Void>($0) }) { resolveRef, rejectRef in - let callbackValue = callback.bridgeJSLowerParameter() param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSS_SS(resolveRef, rejectRef, callbackValue, param0Bytes, param0Length) } } @@ -2346,8 +2346,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestsYaSd_9DataPointV { }, makeRejectClosure: { JSTypedClosure<(sending JSValue) -> Void>($0) }) { resolveRef, rejectRef in - let callbackValue = callback.bridgeJSLowerParameter() let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestsYaSd_9DataPointV(resolveRef, rejectRef, callbackValue, param0Value) } return resolved @@ -2411,8 +2411,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestss11FeatureFlagO_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11FeatureFlagO_y(callbackValue, param0Bytes, param0Length) } #else @@ -2473,8 +2473,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestss11WeatherDataC_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss11WeatherDataC_y(callbackValue, param0Value) #else fatalError("Only available on WebAssembly") @@ -2534,8 +2534,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0CaseId = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss18AsyncPayloadResultO_y(callbackValue, param0CaseId) #else fatalError("Only available on WebAssembly") @@ -2595,8 +2595,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0CaseId = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss26AsyncImportedPayloadResultO_y(callbackValue, param0CaseId) #else fatalError("Only available on WebAssembly") @@ -2656,8 +2656,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestss7JSValueV_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let (param0Kind, param0Payload1, param0Payload2) = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss7JSValueV_y(callbackValue, param0Kind, param0Payload1, param0Payload2) #else fatalError("Only available on WebAssembly") @@ -2717,8 +2717,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestss9DataPointV_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let _ = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestss9DataPointV_y(callbackValue) #else fatalError("Only available on WebAssembly") @@ -2778,8 +2778,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestssSS_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() param0.bridgeJSWithLoweredParameter { (param0Bytes, param0Length) in + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSS_y(callbackValue, param0Bytes, param0Length) } #else @@ -2840,8 +2840,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestssSaSS_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let _ = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSS_y(callbackValue) #else fatalError("Only available on WebAssembly") @@ -2901,8 +2901,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestssSaSb_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let _ = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSb_y(callbackValue) #else fatalError("Only available on WebAssembly") @@ -2962,8 +2962,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestssSaSd_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let _ = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSaSd_y(callbackValue) #else fatalError("Only available on WebAssembly") @@ -3023,8 +3023,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestssSb_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSb_y(callbackValue, param0Value) #else fatalError("Only available on WebAssembly") @@ -3084,8 +3084,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestssSd_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let param0Value = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSd_y(callbackValue, param0Value) #else fatalError("Only available on WebAssembly") @@ -3145,8 +3145,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let (param0IsSome, param0CaseId) = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSq26AsyncImportedPayloadResultO_y(callbackValue, param0IsSome, param0CaseId) #else fatalError("Only available on WebAssembly") @@ -3206,8 +3206,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestssSqSS_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() param0.bridgeJSWithLoweredParameter { (param0IsSome, param0Bytes, param0Length) in + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSS_y(callbackValue, param0IsSome, param0Bytes, param0Length) } #else @@ -3268,8 +3268,8 @@ private enum _BJS_Closure_20BridgeJSRuntimeTestssSqSd_y { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let callbackValue = callback.bridgeJSLowerParameter() let (param0IsSome, param0Value) = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTestssSqSd_y(callbackValue, param0IsSome, param0Value) #else fatalError("Only available on WebAssembly") @@ -3556,8 +3556,8 @@ struct AnyArrayElementProtocol: ArrayElementProtocol, _BridgedSwiftProtocolWrapp return Int.bridgeJSLiftReturn(ret) } set { - let jsObjectValue = jsObject.bridgeJSLowerParameter() let newValueValue = newValue.bridgeJSLowerParameter() + let jsObjectValue = jsObject.bridgeJSLowerParameter() bjs_ArrayElementProtocol_value_set(jsObjectValue, newValueValue) } } @@ -3595,8 +3595,8 @@ struct AnyDataProcessor: DataProcessor, _BridgedSwiftProtocolWrapper { let jsObject: JSObject func increment(by amount: Int) -> Void { - let jsObjectValue = jsObject.bridgeJSLowerParameter() let amountValue = amount.bridgeJSLowerParameter() + let jsObjectValue = jsObject.bridgeJSLowerParameter() _extern_increment(jsObjectValue, amountValue) } @@ -3607,9 +3607,9 @@ struct AnyDataProcessor: DataProcessor, _BridgedSwiftProtocolWrapper { } func setLabelElements(_ labelPrefix: String, _ labelSuffix: String) -> Void { - let jsObjectValue = jsObject.bridgeJSLowerParameter() labelPrefix.bridgeJSWithLoweredParameter { (labelPrefixBytes, labelPrefixLength) in labelSuffix.bridgeJSWithLoweredParameter { (labelSuffixBytes, labelSuffixLength) in + let jsObjectValue = jsObject.bridgeJSLowerParameter() _extern_setLabelElements(jsObjectValue, labelPrefixBytes, labelPrefixLength, labelSuffixBytes, labelSuffixLength) } } @@ -3628,8 +3628,8 @@ struct AnyDataProcessor: DataProcessor, _BridgedSwiftProtocolWrapper { } func processGreeter(_ greeter: Greeter) -> String { - let jsObjectValue = jsObject.bridgeJSLowerParameter() let greeterPointer = greeter.bridgeJSLowerParameter() + let jsObjectValue = jsObject.bridgeJSLowerParameter() let ret = _extern_processGreeter(jsObjectValue, greeterPointer) return String.bridgeJSLiftReturn(ret) } @@ -3641,8 +3641,8 @@ struct AnyDataProcessor: DataProcessor, _BridgedSwiftProtocolWrapper { } func processOptionalGreeter(_ greeter: Optional) -> String { - let jsObjectValue = jsObject.bridgeJSLowerParameter() let (greeterIsSome, greeterPointer) = greeter.bridgeJSLowerParameter() + let jsObjectValue = jsObject.bridgeJSLowerParameter() let ret = _extern_processOptionalGreeter(jsObjectValue, greeterIsSome, greeterPointer) return String.bridgeJSLiftReturn(ret) } @@ -3654,8 +3654,8 @@ struct AnyDataProcessor: DataProcessor, _BridgedSwiftProtocolWrapper { } func handleAPIResult(_ result: Optional) -> Void { - let jsObjectValue = jsObject.bridgeJSLowerParameter() let (resultIsSome, resultCaseId) = result.bridgeJSLowerParameter() + let jsObjectValue = jsObject.bridgeJSLowerParameter() _extern_handleAPIResult(jsObjectValue, resultIsSome, resultCaseId) } @@ -3672,8 +3672,8 @@ struct AnyDataProcessor: DataProcessor, _BridgedSwiftProtocolWrapper { return Int.bridgeJSLiftReturn(ret) } set { - let jsObjectValue = jsObject.bridgeJSLowerParameter() let newValueValue = newValue.bridgeJSLowerParameter() + let jsObjectValue = jsObject.bridgeJSLowerParameter() bjs_DataProcessor_count_set(jsObjectValue, newValueValue) } } @@ -3693,8 +3693,8 @@ struct AnyDataProcessor: DataProcessor, _BridgedSwiftProtocolWrapper { return Optional.bridgeJSLiftReturnFromSideChannel() } set { - let jsObjectValue = jsObject.bridgeJSLowerParameter() newValue.bridgeJSWithLoweredParameter { (newValueIsSome, newValueBytes, newValueLength) in + let jsObjectValue = jsObject.bridgeJSLowerParameter() bjs_DataProcessor_optionalTag_set(jsObjectValue, newValueIsSome, newValueBytes, newValueLength) } } @@ -3707,8 +3707,8 @@ struct AnyDataProcessor: DataProcessor, _BridgedSwiftProtocolWrapper { return Optional.bridgeJSLiftReturnFromSideChannel() } set { - let jsObjectValue = jsObject.bridgeJSLowerParameter() let (newValueIsSome, newValueValue) = newValue.bridgeJSLowerParameter() + let jsObjectValue = jsObject.bridgeJSLowerParameter() bjs_DataProcessor_optionalCount_set(jsObjectValue, newValueIsSome, newValueValue) } } @@ -3720,8 +3720,8 @@ struct AnyDataProcessor: DataProcessor, _BridgedSwiftProtocolWrapper { return Optional.bridgeJSLiftReturn(ret) } set { - let jsObjectValue = jsObject.bridgeJSLowerParameter() let (newValueIsSome, newValueValue) = newValue.bridgeJSLowerParameter() + let jsObjectValue = jsObject.bridgeJSLowerParameter() bjs_DataProcessor_direction_set(jsObjectValue, newValueIsSome, newValueValue) } } @@ -3733,8 +3733,8 @@ struct AnyDataProcessor: DataProcessor, _BridgedSwiftProtocolWrapper { return Optional.bridgeJSLiftReturnFromSideChannel() } set { - let jsObjectValue = jsObject.bridgeJSLowerParameter() newValue.bridgeJSWithLoweredParameter { (newValueIsSome, newValueBytes, newValueLength) in + let jsObjectValue = jsObject.bridgeJSLowerParameter() bjs_DataProcessor_optionalTheme_set(jsObjectValue, newValueIsSome, newValueBytes, newValueLength) } } @@ -3747,8 +3747,8 @@ struct AnyDataProcessor: DataProcessor, _BridgedSwiftProtocolWrapper { return Optional.bridgeJSLiftReturnFromSideChannel() } set { - let jsObjectValue = jsObject.bridgeJSLowerParameter() let (newValueIsSome, newValueValue) = newValue.bridgeJSLowerParameter() + let jsObjectValue = jsObject.bridgeJSLowerParameter() bjs_DataProcessor_httpStatus_set(jsObjectValue, newValueIsSome, newValueValue) } } @@ -3760,8 +3760,8 @@ struct AnyDataProcessor: DataProcessor, _BridgedSwiftProtocolWrapper { return Optional.bridgeJSLiftReturn(ret) } set { - let jsObjectValue = jsObject.bridgeJSLowerParameter() let (newValueIsSome, newValueCaseId) = newValue.bridgeJSLowerParameter() + let jsObjectValue = jsObject.bridgeJSLowerParameter() bjs_DataProcessor_apiResult_set(jsObjectValue, newValueIsSome, newValueCaseId) } } @@ -3773,8 +3773,8 @@ struct AnyDataProcessor: DataProcessor, _BridgedSwiftProtocolWrapper { return Greeter.bridgeJSLiftReturn(ret) } set { - let jsObjectValue = jsObject.bridgeJSLowerParameter() let newValuePointer = newValue.bridgeJSLowerParameter() + let jsObjectValue = jsObject.bridgeJSLowerParameter() bjs_DataProcessor_helper_set(jsObjectValue, newValuePointer) } } @@ -3786,8 +3786,8 @@ struct AnyDataProcessor: DataProcessor, _BridgedSwiftProtocolWrapper { return Optional.bridgeJSLiftReturn(ret) } set { - let jsObjectValue = jsObject.bridgeJSLowerParameter() let (newValueIsSome, newValuePointer) = newValue.bridgeJSLowerParameter() + let jsObjectValue = jsObject.bridgeJSLowerParameter() bjs_DataProcessor_optionalHelper_set(jsObjectValue, newValueIsSome, newValuePointer) } } @@ -13349,8 +13349,8 @@ fileprivate func promise_reject_BridgeJSRuntimeTests_extern(_ promise: Int32, _ } func _$Promise_reject(_ promise: JSObject, _ value: JSValue) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let (valueKind, valuePayload1, valuePayload2) = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_reject_BridgeJSRuntimeTests(promiseValue, valueKind, valuePayload1, valuePayload2) if let error = _swift_js_take_exception() { throw error } } @@ -13370,8 +13370,8 @@ fileprivate func promise_resolve_BridgeJSRuntimeTests_SS_extern(_ promise: Int32 } func _$Promise_resolve_SS(_ promise: JSObject, _ value: String) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() value.bridgeJSWithLoweredParameter { (valueBytes, valueLength) in + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_BridgeJSRuntimeTests_SS(promiseValue, valueBytes, valueLength) } if let error = _swift_js_take_exception() { throw error } @@ -13412,8 +13412,8 @@ fileprivate func promise_resolve_BridgeJSRuntimeTests_Si_extern(_ promise: Int32 } func _$Promise_resolve_Si(_ promise: JSObject, _ value: Int) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let valueValue = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_BridgeJSRuntimeTests_Si(promiseValue, valueValue) if let error = _swift_js_take_exception() { throw error } } @@ -13433,8 +13433,8 @@ fileprivate func promise_resolve_BridgeJSRuntimeTests_Sf_extern(_ promise: Int32 } func _$Promise_resolve_Sf(_ promise: JSObject, _ value: Float) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let valueValue = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_BridgeJSRuntimeTests_Sf(promiseValue, valueValue) if let error = _swift_js_take_exception() { throw error } } @@ -13454,8 +13454,8 @@ fileprivate func promise_resolve_BridgeJSRuntimeTests_Sd_extern(_ promise: Int32 } func _$Promise_resolve_Sd(_ promise: JSObject, _ value: Double) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let valueValue = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_BridgeJSRuntimeTests_Sd(promiseValue, valueValue) if let error = _swift_js_take_exception() { throw error } } @@ -13475,8 +13475,8 @@ fileprivate func promise_resolve_BridgeJSRuntimeTests_Sb_extern(_ promise: Int32 } func _$Promise_resolve_Sb(_ promise: JSObject, _ value: Bool) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let valueValue = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_BridgeJSRuntimeTests_Sb(promiseValue, valueValue) if let error = _swift_js_take_exception() { throw error } } @@ -13496,8 +13496,8 @@ fileprivate func promise_resolve_BridgeJSRuntimeTests_7GreeterC_extern(_ promise } func _$Promise_resolve_7GreeterC(_ promise: JSObject, _ value: Greeter) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let valuePointer = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_BridgeJSRuntimeTests_7GreeterC(promiseValue, valuePointer) if let error = _swift_js_take_exception() { throw error } } @@ -13517,8 +13517,8 @@ fileprivate func promise_resolve_BridgeJSRuntimeTests_8JSObjectC_extern(_ promis } func _$Promise_resolve_8JSObjectC(_ promise: JSObject, _ value: JSObject) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let valueValue = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_BridgeJSRuntimeTests_8JSObjectC(promiseValue, valueValue) if let error = _swift_js_take_exception() { throw error } } @@ -13538,8 +13538,8 @@ fileprivate func promise_resolve_BridgeJSRuntimeTests_5ThemeO_extern(_ promise: } func _$Promise_resolve_5ThemeO(_ promise: JSObject, _ value: Theme) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() value.bridgeJSWithLoweredParameter { (valueBytes, valueLength) in + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_BridgeJSRuntimeTests_5ThemeO(promiseValue, valueBytes, valueLength) } if let error = _swift_js_take_exception() { throw error } @@ -13560,8 +13560,8 @@ fileprivate func promise_resolve_BridgeJSRuntimeTests_9DirectionO_extern(_ promi } func _$Promise_resolve_9DirectionO(_ promise: JSObject, _ value: Direction) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let valueValue = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_BridgeJSRuntimeTests_9DirectionO(promiseValue, valueValue) if let error = _swift_js_take_exception() { throw error } } @@ -13581,8 +13581,8 @@ fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq5ThemeO_extern(_ promise } func _$Promise_resolve_Sq5ThemeO(_ promise: JSObject, _ value: Optional) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() value.bridgeJSWithLoweredParameter { (valueIsSome, valueBytes, valueLength) in + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_BridgeJSRuntimeTests_Sq5ThemeO(promiseValue, valueIsSome, valueBytes, valueLength) } if let error = _swift_js_take_exception() { throw error } @@ -13603,8 +13603,8 @@ fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq9DirectionO_extern(_ pro } func _$Promise_resolve_Sq9DirectionO(_ promise: JSObject, _ value: Optional) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let (valueIsSome, valueValue) = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_BridgeJSRuntimeTests_Sq9DirectionO(promiseValue, valueIsSome, valueValue) if let error = _swift_js_take_exception() { throw error } } @@ -13624,8 +13624,8 @@ fileprivate func promise_resolve_BridgeJSRuntimeTests_Sa9DirectionO_extern(_ pro } func _$Promise_resolve_Sa9DirectionO(_ promise: JSObject, _ value: [Direction]) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let _ = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_BridgeJSRuntimeTests_Sa9DirectionO(promiseValue) if let error = _swift_js_take_exception() { throw error } } @@ -13645,8 +13645,8 @@ fileprivate func promise_resolve_BridgeJSRuntimeTests_SD9DirectionO_extern(_ pro } func _$Promise_resolve_SD9DirectionO(_ promise: JSObject, _ value: [String: Direction]) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let _ = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_BridgeJSRuntimeTests_SD9DirectionO(promiseValue) if let error = _swift_js_take_exception() { throw error } } @@ -13666,8 +13666,8 @@ fileprivate func promise_resolve_BridgeJSRuntimeTests_Sa5ThemeO_extern(_ promise } func _$Promise_resolve_Sa5ThemeO(_ promise: JSObject, _ value: [Theme]) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let _ = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_BridgeJSRuntimeTests_Sa5ThemeO(promiseValue) if let error = _swift_js_take_exception() { throw error } } @@ -13687,8 +13687,8 @@ fileprivate func promise_resolve_BridgeJSRuntimeTests_SD5ThemeO_extern(_ promise } func _$Promise_resolve_SD5ThemeO(_ promise: JSObject, _ value: [String: Theme]) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let _ = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_BridgeJSRuntimeTests_SD5ThemeO(promiseValue) if let error = _swift_js_take_exception() { throw error } } @@ -13708,8 +13708,8 @@ fileprivate func promise_resolve_BridgeJSRuntimeTests_8FileSizeO_extern(_ promis } func _$Promise_resolve_8FileSizeO(_ promise: JSObject, _ value: FileSize) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let valueValue = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_BridgeJSRuntimeTests_8FileSizeO(promiseValue, valueValue) if let error = _swift_js_take_exception() { throw error } } @@ -13729,8 +13729,8 @@ fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq8FileSizeO_extern(_ prom } func _$Promise_resolve_Sq8FileSizeO(_ promise: JSObject, _ value: Optional) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let (valueIsSome, valueValue) = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_BridgeJSRuntimeTests_Sq8FileSizeO(promiseValue, valueIsSome, valueValue) if let error = _swift_js_take_exception() { throw error } } @@ -13750,8 +13750,8 @@ fileprivate func promise_resolve_BridgeJSRuntimeTests_18AsyncPayloadResultO_exte } func _$Promise_resolve_18AsyncPayloadResultO(_ promise: JSObject, _ value: AsyncPayloadResult) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let valueCaseId = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_BridgeJSRuntimeTests_18AsyncPayloadResultO(promiseValue, valueCaseId) if let error = _swift_js_take_exception() { throw error } } @@ -13771,8 +13771,8 @@ fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq18AsyncPayloadResultO_ex } func _$Promise_resolve_Sq18AsyncPayloadResultO(_ promise: JSObject, _ value: Optional) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let (valueIsSome, valueCaseId) = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_BridgeJSRuntimeTests_Sq18AsyncPayloadResultO(promiseValue, valueIsSome, valueCaseId) if let error = _swift_js_take_exception() { throw error } } @@ -13792,8 +13792,8 @@ fileprivate func promise_resolve_BridgeJSRuntimeTests_11PublicPointV_extern(_ pr } func _$Promise_resolve_11PublicPointV(_ promise: JSObject, _ value: PublicPoint) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let valueObjectId = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_BridgeJSRuntimeTests_11PublicPointV(promiseValue, valueObjectId) if let error = _swift_js_take_exception() { throw error } } @@ -13813,8 +13813,8 @@ fileprivate func promise_resolve_BridgeJSRuntimeTests_7ContactV_extern(_ promise } func _$Promise_resolve_7ContactV(_ promise: JSObject, _ value: Contact) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let valueObjectId = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_BridgeJSRuntimeTests_7ContactV(promiseValue, valueObjectId) if let error = _swift_js_take_exception() { throw error } } @@ -13834,8 +13834,8 @@ fileprivate func promise_resolve_BridgeJSRuntimeTests_Sa11PublicPointV_extern(_ } func _$Promise_resolve_Sa11PublicPointV(_ promise: JSObject, _ value: [PublicPoint]) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let _ = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_BridgeJSRuntimeTests_Sa11PublicPointV(promiseValue) if let error = _swift_js_take_exception() { throw error } } @@ -13855,8 +13855,8 @@ fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq11PublicPointV_extern(_ } func _$Promise_resolve_Sq11PublicPointV(_ promise: JSObject, _ value: Optional) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let valueIsSome = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_BridgeJSRuntimeTests_Sq11PublicPointV(promiseValue, valueIsSome) if let error = _swift_js_take_exception() { throw error } } @@ -13876,8 +13876,8 @@ fileprivate func promise_resolve_BridgeJSRuntimeTests_SD11PublicPointV_extern(_ } func _$Promise_resolve_SD11PublicPointV(_ promise: JSObject, _ value: [String: PublicPoint]) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let _ = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_BridgeJSRuntimeTests_SD11PublicPointV(promiseValue) if let error = _swift_js_take_exception() { throw error } } @@ -13897,8 +13897,8 @@ fileprivate func promise_resolve_BridgeJSRuntimeTests_9DataPointV_extern(_ promi } func _$Promise_resolve_9DataPointV(_ promise: JSObject, _ value: DataPoint) throws(JSException) -> Void { - let promiseValue = promise.bridgeJSLowerParameter() let valueObjectId = value.bridgeJSLowerParameter() + let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_BridgeJSRuntimeTests_9DataPointV(promiseValue, valueObjectId) if let error = _swift_js_take_exception() { throw error } } @@ -15087,8 +15087,8 @@ func _$ClosureSupportImports_jsApplyBool(_ callback: JSTypedClosure<() -> Bool>) } func _$ClosureSupportImports_jsApplyInt(_ value: Int, _ transform: JSTypedClosure<(Int) -> Int>) throws(JSException) -> Int { - let valueValue = value.bridgeJSLowerParameter() let transformFuncRef = transform.bridgeJSLowerParameter() + let valueValue = value.bridgeJSLowerParameter() let ret = bjs_ClosureSupportImports_jsApplyInt_static(valueValue, transformFuncRef) if let error = _swift_js_take_exception() { throw error @@ -15097,8 +15097,8 @@ func _$ClosureSupportImports_jsApplyInt(_ value: Int, _ transform: JSTypedClosur } func _$ClosureSupportImports_jsApplyDouble(_ value: Double, _ transform: JSTypedClosure<(Double) -> Double>) throws(JSException) -> Double { - let valueValue = value.bridgeJSLowerParameter() let transformFuncRef = transform.bridgeJSLowerParameter() + let valueValue = value.bridgeJSLowerParameter() let ret = bjs_ClosureSupportImports_jsApplyDouble_static(valueValue, transformFuncRef) if let error = _swift_js_take_exception() { throw error @@ -15120,8 +15120,8 @@ func _$ClosureSupportImports_jsApplyString(_ value: String, _ transform: JSTyped } func _$ClosureSupportImports_jsApplyJSObject(_ value: JSObject, _ transform: JSTypedClosure<(JSObject) -> JSObject>) throws(JSException) -> JSObject { - let valueValue = value.bridgeJSLowerParameter() let transformFuncRef = transform.bridgeJSLowerParameter() + let valueValue = value.bridgeJSLowerParameter() let ret = bjs_ClosureSupportImports_jsApplyJSObject_static(valueValue, transformFuncRef) if let error = _swift_js_take_exception() { throw error @@ -15160,8 +15160,8 @@ func _$ClosureSupportImports_jsMakeStringToString(_ prefix: String) throws(JSExc } func _$ClosureSupportImports_jsCallTwice(_ value: Int, _ callback: JSTypedClosure<(Int) -> Void>) throws(JSException) -> Int { - let valueValue = value.bridgeJSLowerParameter() let callbackFuncRef = callback.bridgeJSLowerParameter() + let valueValue = value.bridgeJSLowerParameter() let ret = bjs_ClosureSupportImports_jsCallTwice_static(valueValue, callbackFuncRef) if let error = _swift_js_take_exception() { throw error @@ -15874,8 +15874,8 @@ func _$JsGreeter_prefix_get(_ self: JSObject) throws(JSException) -> String { } func _$JsGreeter_name_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() newValue.bridgeJSWithLoweredParameter { (newValueBytes, newValueLength) in + let selfValue = self.bridgeJSLowerParameter() bjs_JsGreeter_name_set(selfValue, newValueBytes, newValueLength) } if let error = _swift_js_take_exception() { @@ -15893,8 +15893,8 @@ func _$JsGreeter_greet(_ self: JSObject) throws(JSException) -> String { } func _$JsGreeter_changeName(_ self: JSObject, _ name: String) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() name.bridgeJSWithLoweredParameter { (nameBytes, nameLength) in + let selfValue = self.bridgeJSLowerParameter() bjs_JsGreeter_changeName(selfValue, nameBytes, nameLength) } if let error = _swift_js_take_exception() { @@ -16002,8 +16002,8 @@ func _$WeatherData_humidity_get(_ self: JSObject) throws(JSException) -> Double } func _$WeatherData_temperature_set(_ self: JSObject, _ newValue: Double) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() let newValueValue = newValue.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() bjs_WeatherData_temperature_set(selfValue, newValueValue) if let error = _swift_js_take_exception() { throw error @@ -16011,8 +16011,8 @@ func _$WeatherData_temperature_set(_ self: JSObject, _ newValue: Double) throws( } func _$WeatherData_description_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() newValue.bridgeJSWithLoweredParameter { (newValueBytes, newValueLength) in + let selfValue = self.bridgeJSLowerParameter() bjs_WeatherData_description_set(selfValue, newValueBytes, newValueLength) } if let error = _swift_js_take_exception() { @@ -16021,8 +16021,8 @@ func _$WeatherData_description_set(_ self: JSObject, _ newValue: String) throws( } func _$WeatherData_humidity_set(_ self: JSObject, _ newValue: Double) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() let newValueValue = newValue.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() bjs_WeatherData_humidity_set(selfValue, newValueValue) if let error = _swift_js_take_exception() { throw error @@ -16303,8 +16303,8 @@ fileprivate func bjs_Animal_getIsCat_extern(_ self: Int32) -> Int32 { func _$Animal_init(_ name: String, _ age: Double, _ isCat: Bool) throws(JSException) -> JSObject { let ret0 = name.bridgeJSWithLoweredParameter { (nameBytes, nameLength) in - let ageValue = age.bridgeJSLowerParameter() let isCatValue = isCat.bridgeJSLowerParameter() + let ageValue = age.bridgeJSLowerParameter() let ret = bjs_Animal_init(nameBytes, nameLength, ageValue, isCatValue) return ret } @@ -16343,8 +16343,8 @@ func _$Animal_isCat_get(_ self: JSObject) throws(JSException) -> Bool { } func _$Animal_name_set(_ self: JSObject, _ newValue: String) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() newValue.bridgeJSWithLoweredParameter { (newValueBytes, newValueLength) in + let selfValue = self.bridgeJSLowerParameter() bjs_Animal_name_set(selfValue, newValueBytes, newValueLength) } if let error = _swift_js_take_exception() { @@ -16353,8 +16353,8 @@ func _$Animal_name_set(_ self: JSObject, _ newValue: String) throws(JSException) } func _$Animal_age_set(_ self: JSObject, _ newValue: Double) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() let newValueValue = newValue.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() bjs_Animal_age_set(selfValue, newValueValue) if let error = _swift_js_take_exception() { throw error @@ -16362,8 +16362,8 @@ func _$Animal_age_set(_ self: JSObject, _ newValue: Double) throws(JSException) } func _$Animal_isCat_set(_ self: JSObject, _ newValue: Bool) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() let newValueValue = newValue.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() bjs_Animal_isCat_set(selfValue, newValueValue) if let error = _swift_js_take_exception() { throw error @@ -16451,6 +16451,98 @@ func _$jsRoundTripOptionalImportedPayloadSignal(_ value: Optional.bridgeJSLiftReturn(ret) } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsJoinOptionalArrayThenArray") +fileprivate func bjs_jsJoinOptionalArrayThenArray_extern(_ a: Int32) -> Int32 +#else +fileprivate func bjs_jsJoinOptionalArrayThenArray_extern(_ a: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsJoinOptionalArrayThenArray(_ a: Int32) -> Int32 { + return bjs_jsJoinOptionalArrayThenArray_extern(a) +} + +func _$jsJoinOptionalArrayThenArray(_ a: Optional<[Int]>, _ b: [Int]) throws(JSException) -> String { + let _ = b.bridgeJSLowerParameter() + let aIsSome = a.bridgeJSLowerParameter() + let ret = bjs_jsJoinOptionalArrayThenArray(aIsSome) + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsJoinOptionalStructThenArray") +fileprivate func bjs_jsJoinOptionalStructThenArray_extern(_ a: Int32) -> Int32 +#else +fileprivate func bjs_jsJoinOptionalStructThenArray_extern(_ a: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsJoinOptionalStructThenArray(_ a: Int32) -> Int32 { + return bjs_jsJoinOptionalStructThenArray_extern(a) +} + +func _$jsJoinOptionalStructThenArray(_ a: Optional, _ b: [Int]) throws(JSException) -> String { + let _ = b.bridgeJSLowerParameter() + let aIsSome = a.bridgeJSLowerParameter() + let ret = bjs_jsJoinOptionalStructThenArray(aIsSome) + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsJoinEnumThenArray") +fileprivate func bjs_jsJoinEnumThenArray_extern(_ a: Int32) -> Int32 +#else +fileprivate func bjs_jsJoinEnumThenArray_extern(_ a: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsJoinEnumThenArray(_ a: Int32) -> Int32 { + return bjs_jsJoinEnumThenArray_extern(a) +} + +func _$jsJoinEnumThenArray(_ a: ImportedPayloadSignal, _ b: [Int]) throws(JSException) -> String { + let _ = b.bridgeJSLowerParameter() + let aCaseId = a.bridgeJSLowerParameter() + let ret = bjs_jsJoinEnumThenArray(aCaseId) + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsJoinStringThenStackParams") +fileprivate func bjs_jsJoinStringThenStackParams_extern(_ sBytes: Int32, _ sLength: Int32, _ a: Int32) -> Int32 +#else +fileprivate func bjs_jsJoinStringThenStackParams_extern(_ sBytes: Int32, _ sLength: Int32, _ a: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsJoinStringThenStackParams(_ sBytes: Int32, _ sLength: Int32, _ a: Int32) -> Int32 { + return bjs_jsJoinStringThenStackParams_extern(sBytes, sLength, a) +} + +func _$jsJoinStringThenStackParams(_ s: String, _ a: Optional<[Int]>, _ b: [Int]) throws(JSException) -> String { + let ret0 = s.bridgeJSWithLoweredParameter { (sBytes, sLength) in + let _ = b.bridgeJSLowerParameter() + let aIsSome = a.bridgeJSLowerParameter() + let ret = bjs_jsJoinStringThenStackParams(sBytes, sLength, aIsSome) + return ret + } + let ret = ret0 + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsTranslatePoint") fileprivate func bjs_jsTranslatePoint_extern(_ point: Int32, _ dx: Int32, _ dy: Int32) -> Int32 @@ -16464,9 +16556,9 @@ fileprivate func bjs_jsTranslatePoint_extern(_ point: Int32, _ dx: Int32, _ dy: } func _$jsTranslatePoint(_ point: Point, _ dx: Int, _ dy: Int) throws(JSException) -> Point { - let pointObjectId = point.bridgeJSLowerParameter() - let dxValue = dx.bridgeJSLowerParameter() let dyValue = dy.bridgeJSLowerParameter() + let dxValue = dx.bridgeJSLowerParameter() + let pointObjectId = point.bridgeJSLowerParameter() let ret = bjs_jsTranslatePoint(pointObjectId, dxValue, dyValue) if let error = _swift_js_take_exception() { throw error @@ -16849,8 +16941,8 @@ func _$JSClassWithArrayMembers_labels_get(_ self: JSObject) throws(JSException) } func _$JSClassWithArrayMembers_numbers_set(_ self: JSObject, _ newValue: [Int]) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() let _ = newValue.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() bjs_JSClassWithArrayMembers_numbers_set(selfValue) if let error = _swift_js_take_exception() { throw error @@ -16858,8 +16950,8 @@ func _$JSClassWithArrayMembers_numbers_set(_ self: JSObject, _ newValue: [Int]) } func _$JSClassWithArrayMembers_labels_set(_ self: JSObject, _ newValue: [String]) throws(JSException) -> Void { - let selfValue = self.bridgeJSLowerParameter() let _ = newValue.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() bjs_JSClassWithArrayMembers_labels_set(selfValue) if let error = _swift_js_take_exception() { throw error @@ -16867,8 +16959,8 @@ func _$JSClassWithArrayMembers_labels_set(_ self: JSObject, _ newValue: [String] } func _$JSClassWithArrayMembers_concatNumbers(_ self: JSObject, _ values: [Int]) throws(JSException) -> [Int] { - let selfValue = self.bridgeJSLowerParameter() let _ = values.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() bjs_JSClassWithArrayMembers_concatNumbers(selfValue) if let error = _swift_js_take_exception() { throw error @@ -16877,8 +16969,8 @@ func _$JSClassWithArrayMembers_concatNumbers(_ self: JSObject, _ values: [Int]) } func _$JSClassWithArrayMembers_concatLabels(_ self: JSObject, _ values: [String]) throws(JSException) -> [String] { - let selfValue = self.bridgeJSLowerParameter() let _ = values.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() bjs_JSClassWithArrayMembers_concatLabels(selfValue) if let error = _swift_js_take_exception() { throw error @@ -16887,8 +16979,8 @@ func _$JSClassWithArrayMembers_concatLabels(_ self: JSObject, _ values: [String] } func _$JSClassWithArrayMembers_firstLabel(_ self: JSObject, _ values: [String]) throws(JSException) -> String { - let selfValue = self.bridgeJSLowerParameter() let _ = values.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() let ret = bjs_JSClassWithArrayMembers_firstLabel(selfValue) if let error = _swift_js_take_exception() { throw error diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index 451a3213d..0eac614c7 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -23281,6 +23281,199 @@ "_1" : "null" } } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsJoinOptionalArrayThenArray", + "parameters" : [ + { + "name" : "a", + "type" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + }, + "_1" : "null" + } + } + }, + { + "name" : "b", + "type" : { + "array" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsJoinOptionalStructThenArray", + "parameters" : [ + { + "name" : "a", + "type" : { + "nullable" : { + "_0" : { + "swiftStruct" : { + "_0" : "Point" + } + }, + "_1" : "null" + } + } + }, + { + "name" : "b", + "type" : { + "array" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsJoinEnumThenArray", + "parameters" : [ + { + "name" : "a", + "type" : { + "associatedValueEnum" : { + "_0" : "ImportedPayloadSignal" + } + } + }, + { + "name" : "b", + "type" : { + "array" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "jsJoinStringThenStackParams", + "parameters" : [ + { + "name" : "s", + "type" : { + "string" : { + + } + } + }, + { + "name" : "a", + "type" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + }, + "_1" : "null" + } + } + }, + { + "name" : "b", + "type" : { + "array" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + } + } + ], + "returnType" : { + "string" : { + + } + } } ], "types" : [ diff --git a/Tests/BridgeJSRuntimeTests/ImportAPITests.swift b/Tests/BridgeJSRuntimeTests/ImportAPITests.swift index 9cf77ed9d..c98ab3e61 100644 --- a/Tests/BridgeJSRuntimeTests/ImportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ImportAPITests.swift @@ -21,6 +21,16 @@ import JavaScriptKit _ value: ImportedPayloadSignal? ) throws(JSException) -> ImportedPayloadSignal? +// Parameters that push onto the shared stacks must arrive in declaration order. +@JSFunction func jsJoinOptionalArrayThenArray(_ a: [Int]?, _ b: [Int]) throws(JSException) -> String +@JSFunction func jsJoinOptionalStructThenArray(_ a: Point?, _ b: [Int]) throws(JSException) -> String +@JSFunction func jsJoinEnumThenArray(_ a: ImportedPayloadSignal, _ b: [Int]) throws(JSException) -> String +@JSFunction func jsJoinStringThenStackParams( + _ s: String, + _ a: [Int]?, + _ b: [Int] +) throws(JSException) -> String + class ImportAPITests: XCTestCase { func testRoundTripVoid() throws { try jsRoundTripVoid() @@ -184,4 +194,21 @@ class ImportAPITests: XCTestCase { let dashed = try StaticBox.with_dashes() XCTAssertEqual(try dashed.value(), 7) } + + func testStackLoweredParameterOrder() throws { + XCTAssertEqual(try jsJoinOptionalArrayThenArray([1, 2], [7, 8, 9]), "[1,2]|[7,8,9]") + XCTAssertEqual(try jsJoinOptionalArrayThenArray(nil, [7, 8, 9]), "null|[7,8,9]") + XCTAssertEqual( + try jsJoinOptionalStructThenArray(Point(x: 1, y: 2), [7, 8, 9]), + #"{"x":1,"y":2}|[7,8,9]"# + ) + XCTAssertEqual( + try jsJoinEnumThenArray(.stop(5), [7, 8, 9]), + #"{"tag":1,"param0":5}|[7,8,9]"# + ) + XCTAssertEqual( + try jsJoinStringThenStackParams("s", [1, 2], [7, 8, 9]), + #""s"|[1,2]|[7,8,9]"# + ) + } } diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index 887510e65..42a0e3ea4 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -46,6 +46,8 @@ export async function setupOptions(options, context) { } } + const joinStackParams = (...args) => args.map((v) => JSON.stringify(v)).join("|"); + return { ...options, getImports: (importsContext) => { @@ -155,6 +157,10 @@ export async function setupOptions(options, context) { return { x: (point.x | 0) + (dx | 0), y: (point.y | 0) + (dy | 0) }; }, jsRoundTripOptionalPoint: (point) => point, + jsJoinOptionalArrayThenArray: joinStackParams, + jsJoinOptionalStructThenArray: joinStackParams, + jsJoinEnumThenArray: joinStackParams, + jsJoinStringThenStackParams: joinStackParams, roundTripArrayMembers: (value) => { return value; }, From 5ce30501b47da4c343a986189ed5ddeca86701c4 Mon Sep 17 00:00:00 2001 From: Simon Leeb <52261246+sliemeobn@users.noreply.github.com> Date: Wed, 29 Jul 2026 21:48:01 +0200 Subject: [PATCH 32/50] add JS-snippet support using `from: .module("/path/to/js-module.js")` syntax (#792) --- Package.swift | 1 + .../BridgeJSCore/SwiftToSkeleton.swift | 107 ++++++- .../Sources/BridgeJSLink/BridgeJSLink.swift | 40 ++- .../ImportedJSModuleRegistry.swift | 67 ++++ .../BridgeJSSkeleton/BridgeJSSkeleton.swift | 31 +- .../Sources/BridgeJSTool/BridgeJSTool.swift | 10 +- .../BridgeJSToolInternal.swift | 6 +- .../JavaScriptModulePath.swift | 25 ++ .../BridgeJSCodegenTests.swift | 49 ++- .../BridgeJSToolTests/BridgeJSLinkTests.swift | 16 +- .../BridgeJSToolTests/DiagnosticsTests.swift | 75 +++++ .../Inputs/MacroSwift/JSImportModule.swift | 17 + .../MacroSwift/Modules/JSImportModule.mjs | 9 + .../MacroSwift/Modules/ModuleCounter.mjs | 17 + .../BridgeJSCodegenTests/JSImportModule.json | 191 +++++++++++ .../BridgeJSCodegenTests/JSImportModule.swift | 166 ++++++++++ .../BridgeJSLinkTests/JSImportModule.d.ts | 21 ++ .../BridgeJSLinkTests/JSImportModule.js | 299 ++++++++++++++++++ Plugins/PackageToJS/Sources/PackageToJS.swift | 113 ++++++- .../Sources/PackageToJSPlugin.swift | 17 +- Plugins/PackageToJS/Templates/runtime.mjs | 42 ++- .../Tests/PackagingPlannerTests.swift | 98 ++++++ .../Importing-JavaScript-into-Swift.md | 9 +- .../Importing-JS-Class.md | 24 +- .../Importing-JS-Function.md | 26 +- .../Importing-JS-Variable.md | 19 +- .../Articles/BridgeJS/Unsupported-Features.md | 8 + Sources/JavaScriptKit/Macros.swift | 8 +- .../Generated/BridgeJS.swift | 186 +++++++++++ .../Generated/JavaScript/BridgeJS.json | 199 ++++++++++++ .../JSImportModuleTests.swift | 47 +++ .../Modules/JSImportModule.mjs | 13 + .../Modules/ModuleCounter.mjs | 17 + 33 files changed, 1892 insertions(+), 81 deletions(-) create mode 100644 Plugins/BridgeJS/Sources/BridgeJSLink/ImportedJSModuleRegistry.swift create mode 100644 Plugins/BridgeJS/Sources/BridgeJSUtilities/JavaScriptModulePath.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSImportModule.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Modules/JSImportModule.mjs create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Modules/ModuleCounter.mjs create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportModule.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportModule.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.d.ts create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.js create mode 100644 Tests/BridgeJSRuntimeTests/JSImportModuleTests.swift create mode 100644 Tests/BridgeJSRuntimeTests/Modules/JSImportModule.mjs create mode 100644 Tests/BridgeJSRuntimeTests/Modules/ModuleCounter.mjs diff --git a/Package.swift b/Package.swift index 3d0f1e943..63eacf6be 100644 --- a/Package.swift +++ b/Package.swift @@ -198,6 +198,7 @@ let package = Package( "bridge-js.global.d.ts", "Generated/JavaScript", "JavaScript", + "Modules", ], swiftSettings: [ .enableExperimentalFeature("Extern") diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index 5b5155fdc..2d2a3ab6f 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -23,6 +23,8 @@ public final class SwiftToSkeleton { private var sourceFiles: [(sourceFile: SourceFileSyntax, inputFilePath: String)] = [] private var usedExternalModules = Set() + private let javaScriptModuleExists: (String) throws -> Bool + private var validatedJavaScriptModulePaths = Set() /// Non-fatal diagnostics collected during `finalize()`. These do not fail the build. public private(set) var warnings: [(file: String, diagnostic: DiagnosticError)] = [] @@ -32,12 +34,14 @@ public final class SwiftToSkeleton { moduleName: String, exposeToGlobal: Bool, externalModuleIndex: ExternalModuleIndex, - identityMode: String? = nil + identityMode: String? = nil, + javaScriptModuleExists: @escaping (String) throws -> Bool = { _ in false } ) { self.progress = progress self.moduleName = moduleName self.exposeToGlobal = exposeToGlobal self.identityMode = identityMode + self.javaScriptModuleExists = javaScriptModuleExists self.typeDeclResolver = TypeDeclResolver() self.externalModuleIndex = externalModuleIndex @@ -90,6 +94,57 @@ public final class SwiftToSkeleton { ) importCollector.walk(sourceFile) + let importOrigins = + importCollector.importedFunctions.compactMap(\.from) + + importCollector.importedTypes.compactMap(\.from) + + importCollector.importedGlobalGetters.compactMap(\.from) + let modulePaths = Set(importOrigins.compactMap(\.modulePath)) + for path in modulePaths.sorted() { + if validatedJavaScriptModulePaths.contains(path) { + continue + } + let pathNode = importCollector.importedModulePathNodes[path] ?? Syntax(sourceFile) + guard path.hasPrefix("/") else { + importCollector.errors.append( + DiagnosticError( + node: pathNode, + message: "JavaScript module paths must start with '/' to indicate the Swift target root: " + + "'\(path)'." + ) + ) + continue + } + guard !path.split(separator: "/").contains("..") else { + importCollector.errors.append( + DiagnosticError( + node: pathNode, + message: "JavaScript module paths must not contain '..': '\(path)'." + ) + ) + continue + } + let lowercasedPath = path.lowercased() + guard lowercasedPath.hasSuffix(".js") || lowercasedPath.hasSuffix(".mjs") else { + importCollector.errors.append( + DiagnosticError( + node: pathNode, + message: "JavaScript modules must use a '.js' or '.mjs' extension: '\(path)'." + ) + ) + continue + } + guard try javaScriptModuleExists(path) else { + importCollector.errors.append( + DiagnosticError( + node: pathNode, + message: "JavaScript module file was not found at '\(path)'." + ) + ) + continue + } + validatedJavaScriptModulePaths.insert(path) + } + let exportErrors = exportCollector.errors.filter { $0.severity == .error } let importErrorsFatal = importCollector.errors.filter { $0.severity == .error && !$0.message.contains("Unsupported type '") @@ -2413,6 +2468,7 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { var importedFunctions: [ImportedFunctionSkeleton] = [] var importedTypes: [ImportedTypeSkeleton] = [] var importedGlobalGetters: [ImportedGetterSkeleton] = [] + var importedModulePathNodes: [String: Syntax] = [:] var errors: [DiagnosticError] = [] private let inputFilePath: String @@ -2507,22 +2563,41 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { } return nil } + } + + private func extractJSImportFrom(from attribute: AttributeSyntax) -> JSImportFrom? { + guard let arguments = attribute.arguments?.as(LabeledExprListSyntax.self), + let argument = arguments.first(where: { $0.label?.text == "from" }) + else { + return nil + } - /// Extracts the `from` argument value from an attribute, if present. - static func extractJSImportFrom(from attribute: AttributeSyntax) -> JSImportFrom? { - guard let arguments = attribute.arguments?.as(LabeledExprListSyntax.self) else { + if let call = argument.expression.as(FunctionCallExprSyntax.self), + call.calledExpression.trimmedDescription.split(separator: ".").last == "module" + { + guard call.arguments.count == 1, + let pathExpression = call.arguments.first?.expression, + let literal = pathExpression.as(StringLiteralExprSyntax.self), + let path = literal.representedLiteralValue + else { + errors.append( + DiagnosticError( + node: call.arguments.first?.expression ?? argument.expression, + message: "JavaScript module path must be a string literal." + ) + ) return nil } - for argument in arguments { - guard argument.label?.text == "from" else { continue } - - // Accept `.global`, `JSImportFrom.global`, etc. - let description = argument.expression.trimmedDescription - let caseName = description.split(separator: ".").last.map(String.init) ?? description - return JSImportFrom(rawValue: caseName) + if importedModulePathNodes[path] == nil { + importedModulePathNodes[path] = Syntax(literal) } - return nil + return .module(path) } + + // Accept `.global`, `JSImportFrom.global`, etc. + let description = argument.expression.trimmedDescription + let caseName = description.split(separator: ".").last.map(String.init) ?? description + return caseName == "global" ? .global : nil } // MARK: - Validation Helpers @@ -2705,7 +2780,7 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { if AttributeChecker.hasJSClassAttribute(node.attributes) { let attribute = AttributeChecker.firstJSClassAttribute(node.attributes) let jsName = attribute.flatMap(AttributeChecker.extractJSName) - let from = attribute.flatMap(AttributeChecker.extractJSImportFrom) + let from = attribute.flatMap { extractJSImportFrom(from: $0) } let accessLevel = Self.bridgeAccessLevel(from: node.modifiers) enterJSClass(node.name.text, jsName: jsName, from: from, accessLevel: accessLevel) } @@ -2722,7 +2797,7 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { if AttributeChecker.hasJSClassAttribute(node.attributes) { let attribute = AttributeChecker.firstJSClassAttribute(node.attributes) let jsName = attribute.flatMap(AttributeChecker.extractJSName) - let from = attribute.flatMap(AttributeChecker.extractJSImportFrom) + let from = attribute.flatMap { extractJSImportFrom(from: $0) } let accessLevel = Self.bridgeAccessLevel(from: node.modifiers) enterJSClass(node.name.text, jsName: jsName, from: from, accessLevel: accessLevel) } @@ -2916,7 +2991,7 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { let baseName = SwiftToSkeleton.normalizeIdentifier(node.name.text) let jsName = AttributeChecker.extractJSName(from: jsFunction) - let from = AttributeChecker.extractJSImportFrom(from: jsFunction) + let from = extractJSImportFrom(from: jsFunction) let name = baseName let parameters = parseParameters(from: node.signature.parameterClause) @@ -2969,7 +3044,7 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { } let propertyName = SwiftToSkeleton.normalizeIdentifier(identifier.identifier.text) let jsName = AttributeChecker.extractJSName(from: jsGetter) - let from = AttributeChecker.extractJSImportFrom(from: jsGetter) + let from = extractJSImportFrom(from: jsGetter) let accessLevel = Self.bridgeAccessLevel(from: node.modifiers) return ImportedGetterSkeleton( name: propertyName, diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index 4706b14a4..d8a1ac780 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -16,6 +16,7 @@ public struct BridgeJSLink { let enableLifetimeTracking: Bool = false private let namespaceBuilder = NamespaceBuilder() private let intrinsicRegistry = JSIntrinsicRegistry() + private let importedModuleRegistry = ImportedJSModuleRegistry() public init( skeletons: [BridgeJSSkeleton] = [], @@ -40,10 +41,12 @@ public struct BridgeJSLink { return configIdentityMode == "pointer" } - mutating func addSkeletonFile(data: Data) throws { + @discardableResult + mutating func addSkeletonFile(data: Data) throws -> BridgeJSSkeleton { do { let unified = try JSONDecoder().decode(BridgeJSSkeleton.self, from: data) skeletons.append(unified) + return unified } catch { struct SkeletonDecodingError: Error, CustomStringConvertible { let description: String @@ -1077,6 +1080,11 @@ public struct BridgeJSLink { let printer = CodeFragmentPrinter(header: header) printer.nextLine() + printer.write(lines: importedModuleRegistry.importLines) + if !importedModuleRegistry.importLines.isEmpty { + printer.nextLine() + } + printer.write(lines: data.topLevelTypeLines) let exportedSkeletons = skeletons.compactMap(\.exported) @@ -1222,6 +1230,7 @@ public struct BridgeJSLink { public func link() throws -> (outputJs: String, outputDts: String) { intrinsicRegistry.reset() + importedModuleRegistry.configure(skeletons: skeletons) intrinsicRegistry.classNamespaces = skeletons.reduce(into: [:]) { result, unified in guard let skeleton = unified.exported else { return } for klass in skeleton.classes { @@ -1586,7 +1595,7 @@ public struct BridgeJSLink { return "\"\(Self.escapeForJavaScriptStringLiteral(name))\"" } - fileprivate static func escapeForJavaScriptStringLiteral(_ string: String) -> String { + static func escapeForJavaScriptStringLiteral(_ string: String) -> String { string .replacingOccurrences(of: "\\", with: "\\\\") .replacingOccurrences(of: "\"", with: "\\\"") @@ -3460,7 +3469,10 @@ extension BridgeJSLink { try thunkBuilder.liftParameter(param: param) } let jsName = function.jsName ?? function.name - let importRootExpr = function.from == .global ? "globalThis" : "imports" + let importRootExpr = try importedModuleRegistry.namespaceExpression( + swiftModuleName: importObjectBuilder.moduleName, + from: function.from + ) try thunkBuilder.call(name: jsName, fromObjectExpr: importRootExpr) let funcLines = thunkBuilder.renderFunction(name: function.abiName(context: nil)) @@ -3484,7 +3496,10 @@ extension BridgeJSLink { intrinsicRegistry: intrinsicRegistry ) let jsName = getter.jsName ?? getter.name - let importRootExpr = getter.from == .global ? "globalThis" : "imports" + let importRootExpr = try importedModuleRegistry.namespaceExpression( + swiftModuleName: importObjectBuilder.moduleName, + from: getter.from + ) try thunkBuilder.getImportProperty( name: jsName, fromObjectExpr: importRootExpr, @@ -3539,7 +3554,11 @@ extension BridgeJSLink { } for method in type.staticMethods { let abiName = method.abiName(context: type, operation: "static") - let (js, dts) = try renderImportedStaticMethod(context: type, method: method) + let (js, dts) = try renderImportedStaticMethod( + swiftModuleName: importObjectBuilder.moduleName, + context: type, + method: method + ) importObjectBuilder.assignToImportObject(name: abiName, function: js) importObjectBuilder.appendDts(dts) } @@ -3583,7 +3602,10 @@ extension BridgeJSLink { for param in constructor.parameters { try thunkBuilder.liftParameter(param: param) } - let importRootExpr = type.from == .global ? "globalThis" : "imports" + let importRootExpr = try importedModuleRegistry.namespaceExpression( + swiftModuleName: importObjectBuilder.moduleName, + from: type.from + ) try thunkBuilder.callConstructor( jsName: type.jsName ?? type.name, swiftTypeName: type.name, @@ -3627,6 +3649,7 @@ extension BridgeJSLink { } func renderImportedStaticMethod( + swiftModuleName: String, context: ImportedTypeSkeleton, method: ImportedFunctionSkeleton ) throws -> (js: [String], dts: [String]) { @@ -3638,7 +3661,10 @@ extension BridgeJSLink { for param in method.parameters { try thunkBuilder.liftParameter(param: param) } - let importRootExpr = context.from == .global ? "globalThis" : "imports" + let importRootExpr = try importedModuleRegistry.namespaceExpression( + swiftModuleName: swiftModuleName, + from: context.from + ) let constructorExpr = ImportedThunkBuilder.propertyAccessExpr( objectExpr: importRootExpr, propertyName: context.jsName ?? context.name diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/ImportedJSModuleRegistry.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/ImportedJSModuleRegistry.swift new file mode 100644 index 000000000..2c5716030 --- /dev/null +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/ImportedJSModuleRegistry.swift @@ -0,0 +1,67 @@ +#if canImport(BridgeJSSkeleton) +import BridgeJSSkeleton +#endif + +final class ImportedJSModuleRegistry { + struct Reference: Hashable { + let swiftModuleName: String + let path: String + + var relativeOutputPath: String { + "bridge-js-modules/\(swiftModuleName)\(path)" + } + } + + private var aliases: [Reference: String] = [:] + private(set) var references: [Reference] = [] + + func configure(skeletons: [BridgeJSSkeleton]) { + aliases.removeAll(keepingCapacity: true) + references = Self.collectReferences(skeletons: skeletons) + for (index, reference) in references.enumerated() { + aliases[reference] = "__bjs_imported_module_\(index)" + } + } + + static func collectReferences(skeletons: [BridgeJSSkeleton]) -> [Reference] { + var references = Set() + for skeleton in skeletons { + for file in skeleton.imported?.children ?? [] { + let origins = + file.functions.compactMap(\.from) + + file.globalGetters.compactMap(\.from) + + file.types.compactMap(\.from) + for case .module(let path) in origins { + references.insert(Reference(swiftModuleName: skeleton.moduleName, path: path)) + } + } + } + return references.sorted { + ($0.swiftModuleName, $0.path) < ($1.swiftModuleName, $1.path) + } + } + + func namespaceExpression(swiftModuleName: String, from: JSImportFrom?) throws -> String { + switch from { + case nil: + return "imports" + case .global: + return "globalThis" + case .module(let path): + let reference = Reference(swiftModuleName: swiftModuleName, path: path) + guard let alias = aliases[reference] else { + throw BridgeJSLinkError( + message: "Missing JavaScript module \(swiftModuleName)\(path)" + ) + } + return alias + } + } + + var importLines: [String] { + references.enumerated().map { index, reference in + let path = BridgeJSLink.escapeForJavaScriptStringLiteral(reference.relativeOutputPath) + return "import * as __bjs_imported_module_\(index) from \"./\(path)\";" + } + } +} diff --git a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift index 7f45b6c39..c70ccdd8b 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift @@ -1101,7 +1101,7 @@ public struct ExportedSkeleton: Codable { } private var asyncClosureResolveReturnTypes: [BridgeType] { - var collector = AsyncClosureReturnTypeCollector() + let collector = AsyncClosureReturnTypeCollector() var walker = BridgeSkeletonWalker(visitor: collector) walker.walk(self) return walker.visitor.returnTypes @@ -1126,8 +1126,35 @@ private struct AsyncClosureReturnTypeCollector: BridgeSkeletonVisitor { /// Controls where BridgeJS reads imported JS values from. /// /// - `global`: Read from `globalThis`. -public enum JSImportFrom: String, Codable { +/// - `module`: Read from a target-local ECMAScript module. +public enum JSImportFrom: Codable, Equatable, Sendable { case global + case module(String) + + public init(from decoder: any Decoder) throws { + let container = try decoder.singleValueContainer() + let value = try container.decode(String.self) + if value == "global" { + self = .global + } else if value.hasPrefix("/") && !value.split(separator: "/").contains("..") { + self = .module(value) + } else { + throw DecodingError.dataCorruptedError( + in: container, + debugDescription: "Unknown import origin '\(value)'. Expected \"global\" or a rooted module path." + ) + } + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.singleValueContainer() + try container.encode(modulePath ?? "global") + } + + public var modulePath: String? { + guard case .module(let path) = self else { return nil } + return path + } } public struct ImportedFunctionSkeleton: Codable { diff --git a/Plugins/BridgeJS/Sources/BridgeJSTool/BridgeJSTool.swift b/Plugins/BridgeJS/Sources/BridgeJSTool/BridgeJSTool.swift index fa8a0a273..140ebda63 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSTool/BridgeJSTool.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSTool/BridgeJSTool.swift @@ -176,7 +176,13 @@ import BridgeJSUtilities moduleName: moduleName, exposeToGlobal: config.exposeToGlobal, externalModuleIndex: externalModuleIndex, - identityMode: config.identityMode + identityMode: config.identityMode, + javaScriptModuleExists: { path in + guard let file = JavaScriptModulePath.resolve(path, relativeTo: targetDirectory) else { + return false + } + return JavaScriptModulePath.isRegularFile(at: file) + } ) for inputFile in inputFiles.sorted() { try withSpan("Parsing \(inputFile)") { @@ -396,7 +402,7 @@ private func inputSwiftFiles(targetDirectory: URL, positionalArguments: [String] if positionalArguments.isEmpty { return recursivelyCollectSwiftFiles(from: targetDirectory).map(\.path) } - return positionalArguments + return positionalArguments.filter { URL(fileURLWithPath: $0).pathExtension == "swift" } } extension Profiling { diff --git a/Plugins/BridgeJS/Sources/BridgeJSToolInternal/BridgeJSToolInternal.swift b/Plugins/BridgeJS/Sources/BridgeJSToolInternal/BridgeJSToolInternal.swift index 4a58f1972..cb6a5481c 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSToolInternal/BridgeJSToolInternal.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSToolInternal/BridgeJSToolInternal.swift @@ -122,8 +122,7 @@ import ArgumentParser var skeletonFiles: [String] func run() throws { - let (outputJs, _) = try linkSkeletons(skeletonFiles: skeletonFiles) - print(outputJs) + print(try linkSkeletons(skeletonFiles: skeletonFiles).outputJs) } } @@ -136,8 +135,7 @@ import ArgumentParser var skeletonFiles: [String] func run() throws { - let (_, outputDts) = try linkSkeletons(skeletonFiles: skeletonFiles) - print(outputDts) + print(try linkSkeletons(skeletonFiles: skeletonFiles).outputDts) } } } diff --git a/Plugins/BridgeJS/Sources/BridgeJSUtilities/JavaScriptModulePath.swift b/Plugins/BridgeJS/Sources/BridgeJSUtilities/JavaScriptModulePath.swift new file mode 100644 index 000000000..8067f7233 --- /dev/null +++ b/Plugins/BridgeJS/Sources/BridgeJSUtilities/JavaScriptModulePath.swift @@ -0,0 +1,25 @@ +import Foundation + +public enum JavaScriptModulePath { + public static func resolve(_ path: String, relativeTo targetDirectory: URL) -> URL? { + let lowercasedPath = path.lowercased() + guard path.hasPrefix("/"), + !path.split(separator: "/").contains(".."), + lowercasedPath.hasSuffix(".js") || lowercasedPath.hasSuffix(".mjs") + else { + return nil + } + + let targetRoot = targetDirectory.standardizedFileURL + let file = URL(fileURLWithPath: targetRoot.path + path).standardizedFileURL + let targetPrefix = targetRoot.path.hasSuffix("/") ? targetRoot.path : targetRoot.path + "/" + guard file.path.hasPrefix(targetPrefix) else { + return nil + } + return file + } + + public static func isRegularFile(at url: URL) -> Bool { + (try? url.resourceValues(forKeys: [.isRegularFileKey]))?.isRegularFile == true + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift index 8b8e8b8a2..263d796a6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift @@ -4,6 +4,7 @@ import SwiftParser import Testing @testable import BridgeJSCore +@testable import BridgeJSLink @testable import BridgeJSSkeleton @Suite struct BridgeJSCodegenTests { @@ -13,6 +14,44 @@ import Testing static let multifileInputsDirectory = URL(fileURLWithPath: #filePath).deletingLastPathComponent() .appendingPathComponent("Inputs").appendingPathComponent("MacroSwift").appendingPathComponent("Multifile") + @Test + func javaScriptModuleReferencesAreStoredWithoutSourceContents() throws { + let modulePath = "/Modules/math.mjs" + let swiftSource = """ + @JSFunction(from: .module("/Modules/math.mjs")) + func add(_ lhs: Int, _ rhs: Int) throws(JSException) -> Int + + @JSGetter(jsName: "version", from: .module("/Modules/math.mjs")) + var moduleVersion: String + """ + var validationCount = 0 + let generator = SwiftToSkeleton( + progress: .silent, + moduleName: "TestModule", + exposeToGlobal: false, + externalModuleIndex: .empty, + javaScriptModuleExists: { + validationCount += 1 + return $0 == modulePath + } + ) + generator.addSourceFile(Parser.parse(source: swiftSource), inputFilePath: "Imports.swift") + let skeleton = try generator.finalize() + let encoded = String(decoding: try JSONEncoder().encode(skeleton), as: UTF8.self) + let imported = try #require(skeleton.imported) + + #expect(validationCount == 1) + #expect(imported.children.flatMap(\.functions).first?.from == .module(modulePath)) + #expect(!encoded.contains(#""modules""#)) + } + + @Test + func invalidJSImportFromValueFailsToDecode() { + #expect(throws: DecodingError.self) { + try JSONDecoder().decode(JSImportFrom.self, from: Data(#""module.js""#.utf8)) + } + } + private func snapshotCodegen( skeleton: BridgeJSSkeleton, name: String, @@ -77,11 +116,19 @@ import Testing let url = Self.inputsDirectory.appendingPathComponent(input) let name = url.deletingPathExtension().lastPathComponent let sourceFile = Parser.parse(source: try String(contentsOf: url, encoding: .utf8)) + let modulePaths: Set = + input == "JSImportModule.swift" + ? [ + "/Modules/JSImportModule.mjs", + "/Modules/ModuleCounter.mjs", + ] + : [] let swiftAPI = SwiftToSkeleton( progress: .silent, moduleName: "TestModule", exposeToGlobal: false, - externalModuleIndex: .empty + externalModuleIndex: .empty, + javaScriptModuleExists: { modulePaths.contains($0) } ) swiftAPI.addSourceFile(sourceFile, inputFilePath: input) let skeleton = try swiftAPI.finalize() diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSLinkTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSLinkTests.swift index 2f3f46fdb..0445fe5e1 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSLinkTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSLinkTests.swift @@ -14,13 +14,13 @@ import Testing function: String = #function, sourceLocation: Testing.SourceLocation = #_sourceLocation ) throws { - let (outputJs, outputDts) = try bridgeJSLink.link() + let output = try bridgeJSLink.link() try assertSnapshot( name: name, filePath: filePath, function: function, sourceLocation: sourceLocation, - input: outputJs.data(using: .utf8)!, + input: output.outputJs.data(using: .utf8)!, fileExtension: "js" ) try assertSnapshot( @@ -28,7 +28,7 @@ import Testing filePath: filePath, function: function, sourceLocation: sourceLocation, - input: outputDts.data(using: .utf8)!, + input: output.outputDts.data(using: .utf8)!, fileExtension: "d.ts" ) } @@ -49,11 +49,19 @@ import Testing let name = url.deletingPathExtension().lastPathComponent let sourceFile = Parser.parse(source: try String(contentsOf: url, encoding: .utf8)) + let modulePaths: Set = + input == "JSImportModule.swift" + ? [ + "/Modules/JSImportModule.mjs", + "/Modules/ModuleCounter.mjs", + ] + : [] let importSwift = SwiftToSkeleton( progress: .silent, moduleName: "TestModule", exposeToGlobal: false, - externalModuleIndex: .empty + externalModuleIndex: .empty, + javaScriptModuleExists: { modulePaths.contains($0) } ) importSwift.addSourceFile(sourceFile, inputFilePath: "\(name).swift") let importResult = try importSwift.finalize() diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift index 79ea47ebd..e8cf963e3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift @@ -1,3 +1,4 @@ +import Foundation import SwiftParser import SwiftSyntax import Testing @@ -6,6 +7,80 @@ import Testing @testable import BridgeJSSkeleton @Suite struct DiagnosticsTests { + private func moduleDiagnostics(source: String) -> BridgeJSCoreDiagnosticError? { + let swiftAPI = SwiftToSkeleton( + progress: .silent, + moduleName: "TestModule", + exposeToGlobal: false, + externalModuleIndex: .empty + ) + swiftAPI.addSourceFile(Parser.parse(source: source), inputFilePath: "test.swift") + do { + _ = try swiftAPI.finalize() + return nil + } catch let error as BridgeJSCoreDiagnosticError { + return error + } catch { + Issue.record("Unexpected error: \(error)") + return nil + } + } + + @Test + func missingJavaScriptModuleProducesDiagnostic() throws { + let source = """ + let unrelated = 0 + @JSFunction(from: .module("/missing.js")) func imported() throws(JSException) + """ + let diagnostics = try #require(moduleDiagnostics(source: source)) + #expect(diagnostics.description.contains("JavaScript module file was not found at '/missing.js'")) + #expect(diagnostics.description.contains("test.swift:2:27:")) + } + + @Test + func javaScriptModulePathMustStartAtTargetRoot() throws { + let source = """ + let unrelated = 0 + @JSFunction(from: .module("missing.js")) func imported() throws(JSException) + """ + let diagnostics = try #require(moduleDiagnostics(source: source)) + #expect(diagnostics.description.contains("JavaScript module paths must start with '/'")) + #expect(diagnostics.description.contains("test.swift:2:27:")) + } + + @Test + func javaScriptModulePathMustNotTraverse() throws { + let source = """ + let unrelated = 0 + @JSFunction(from: .module("/../missing.js")) func imported() throws(JSException) + """ + let diagnostics = try #require(moduleDiagnostics(source: source)) + #expect(diagnostics.description.contains("JavaScript module paths must not contain '..'")) + #expect(diagnostics.description.contains("test.swift:2:27:")) + } + + @Test + func javaScriptModulePathMustUseSupportedExtension() throws { + let source = """ + let unrelated = 0 + @JSFunction(from: .module("/module.ts")) func imported() throws(JSException) + """ + let diagnostics = try #require(moduleDiagnostics(source: source)) + #expect(diagnostics.description.contains("JavaScript modules must use a '.js' or '.mjs' extension")) + #expect(diagnostics.description.contains("test.swift:2:27:")) + } + + @Test + func javaScriptModulePathMustBeStringLiteral() throws { + let source = """ + let modulePath = "/module.js" + @JSFunction(from: .module(modulePath)) func imported() throws(JSException) + """ + let diagnostics = try #require(moduleDiagnostics(source: source)) + #expect(diagnostics.description.contains("JavaScript module path must be a string literal.")) + #expect(diagnostics.description.contains("test.swift:2:27:")) + } + /// Returns the first parameter's type node from a function in the source (the first `@JS func`-like decl), for pinpointing diagnostics. private func firstParameterTypeNode(source: String) -> TypeSyntax? { let tree = Parser.parse(source: source) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSImportModule.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSImportModule.swift new file mode 100644 index 000000000..3fd9d79e7 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSImportModule.swift @@ -0,0 +1,17 @@ +@JSFunction(from: .module("/Modules/JSImportModule.mjs")) +func moduleAdd(_ lhs: Int, _ rhs: Int) throws(JSException) -> Int + +@JSFunction(jsName: "renamedFunction", from: .module("/Modules/JSImportModule.mjs")) +func moduleRenamed() throws(JSException) -> String + +@JSGetter(jsName: "version", from: .module("/Modules/JSImportModule.mjs")) +var moduleVersion: String + +@JSClass(from: .module("/Modules/ModuleCounter.mjs")) +struct ModuleCounter { + @JSFunction init(_ value: Int) throws(JSException) + @JSFunction static func create(_ value: Int) throws(JSException) -> ModuleCounter + @JSFunction func increment() throws(JSException) -> Int + @JSGetter var value: Int + @JSSetter func setValue(_ value: Int) throws(JSException) +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Modules/JSImportModule.mjs b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Modules/JSImportModule.mjs new file mode 100644 index 000000000..3107e222f --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Modules/JSImportModule.mjs @@ -0,0 +1,9 @@ +export function moduleAdd(lhs, rhs) { + return lhs + rhs; +} + +export function renamedFunction() { + return "renamed"; +} + +export const version = "1.0"; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Modules/ModuleCounter.mjs b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Modules/ModuleCounter.mjs new file mode 100644 index 000000000..5a33b7ffa --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Modules/ModuleCounter.mjs @@ -0,0 +1,17 @@ +export class ModuleCounter { + constructor(value) { + this.value = value; + } + + static create(value) { + return new ModuleCounter(value); + } + + increment() { + return ++this.value; + } + + setValue(value) { + this.value = value; + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportModule.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportModule.json new file mode 100644 index 000000000..d90e88f1d --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportModule.json @@ -0,0 +1,191 @@ +{ + "imported" : { + "children" : [ + { + "functions" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "from" : "\/Modules\/JSImportModule.mjs", + "name" : "moduleAdd", + "parameters" : [ + { + "name" : "lhs", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "name" : "rhs", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "from" : "\/Modules\/JSImportModule.mjs", + "jsName" : "renamedFunction", + "name" : "moduleRenamed", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "globalGetters" : [ + { + "accessLevel" : "internal", + "from" : "\/Modules\/JSImportModule.mjs", + "jsName" : "version", + "name" : "moduleVersion", + "type" : { + "string" : { + + } + } + } + ], + "types" : [ + { + "accessLevel" : "internal", + "constructor" : { + "accessLevel" : "internal", + "parameters" : [ + { + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ] + }, + "from" : "\/Modules\/ModuleCounter.mjs", + "getters" : [ + { + "accessLevel" : "internal", + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "methods" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "increment", + "parameters" : [ + + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "name" : "ModuleCounter", + "setters" : [ + { + "accessLevel" : "internal", + "functionName" : "value_set", + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "staticMethods" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "create", + "parameters" : [ + { + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "jsObject" : { + "_0" : "ModuleCounter" + } + } + } + ] + } + ] + } + ] + }, + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportModule.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportModule.swift new file mode 100644 index 000000000..dc22aceb9 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportModule.swift @@ -0,0 +1,166 @@ +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_moduleVersion_get") +fileprivate func bjs_moduleVersion_get_extern() -> Int32 +#else +fileprivate func bjs_moduleVersion_get_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_moduleVersion_get() -> Int32 { + return bjs_moduleVersion_get_extern() +} + +func _$moduleVersion_get() throws(JSException) -> String { + let ret = bjs_moduleVersion_get() + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_moduleAdd") +fileprivate func bjs_moduleAdd_extern(_ lhs: Int32, _ rhs: Int32) -> Int32 +#else +fileprivate func bjs_moduleAdd_extern(_ lhs: Int32, _ rhs: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_moduleAdd(_ lhs: Int32, _ rhs: Int32) -> Int32 { + return bjs_moduleAdd_extern(lhs, rhs) +} + +func _$moduleAdd(_ lhs: Int, _ rhs: Int) throws(JSException) -> Int { + let rhsValue = rhs.bridgeJSLowerParameter() + let lhsValue = lhs.bridgeJSLowerParameter() + let ret = bjs_moduleAdd(lhsValue, rhsValue) + if let error = _swift_js_take_exception() { + throw error + } + return Int.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_moduleRenamed") +fileprivate func bjs_moduleRenamed_extern() -> Int32 +#else +fileprivate func bjs_moduleRenamed_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_moduleRenamed() -> Int32 { + return bjs_moduleRenamed_extern() +} + +func _$moduleRenamed() throws(JSException) -> String { + let ret = bjs_moduleRenamed() + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_ModuleCounter_init") +fileprivate func bjs_ModuleCounter_init_extern(_ value: Int32) -> Int32 +#else +fileprivate func bjs_ModuleCounter_init_extern(_ value: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ModuleCounter_init(_ value: Int32) -> Int32 { + return bjs_ModuleCounter_init_extern(value) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_ModuleCounter_create_static") +fileprivate func bjs_ModuleCounter_create_static_extern(_ value: Int32) -> Int32 +#else +fileprivate func bjs_ModuleCounter_create_static_extern(_ value: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ModuleCounter_create_static(_ value: Int32) -> Int32 { + return bjs_ModuleCounter_create_static_extern(value) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_ModuleCounter_value_get") +fileprivate func bjs_ModuleCounter_value_get_extern(_ self: Int32) -> Int32 +#else +fileprivate func bjs_ModuleCounter_value_get_extern(_ self: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ModuleCounter_value_get(_ self: Int32) -> Int32 { + return bjs_ModuleCounter_value_get_extern(self) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_ModuleCounter_value_set") +fileprivate func bjs_ModuleCounter_value_set_extern(_ self: Int32, _ newValue: Int32) -> Void +#else +fileprivate func bjs_ModuleCounter_value_set_extern(_ self: Int32, _ newValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ModuleCounter_value_set(_ self: Int32, _ newValue: Int32) -> Void { + return bjs_ModuleCounter_value_set_extern(self, newValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_ModuleCounter_increment") +fileprivate func bjs_ModuleCounter_increment_extern(_ self: Int32) -> Int32 +#else +fileprivate func bjs_ModuleCounter_increment_extern(_ self: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ModuleCounter_increment(_ self: Int32) -> Int32 { + return bjs_ModuleCounter_increment_extern(self) +} + +func _$ModuleCounter_init(_ value: Int) throws(JSException) -> JSObject { + let valueValue = value.bridgeJSLowerParameter() + let ret = bjs_ModuleCounter_init(valueValue) + if let error = _swift_js_take_exception() { + throw error + } + return JSObject.bridgeJSLiftReturn(ret) +} + +func _$ModuleCounter_create(_ value: Int) throws(JSException) -> ModuleCounter { + let valueValue = value.bridgeJSLowerParameter() + let ret = bjs_ModuleCounter_create_static(valueValue) + if let error = _swift_js_take_exception() { + throw error + } + return ModuleCounter.bridgeJSLiftReturn(ret) +} + +func _$ModuleCounter_value_get(_ self: JSObject) throws(JSException) -> Int { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_ModuleCounter_value_get(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return Int.bridgeJSLiftReturn(ret) +} + +func _$ModuleCounter_value_set(_ self: JSObject, _ newValue: Int) throws(JSException) -> Void { + let newValueValue = newValue.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() + bjs_ModuleCounter_value_set(selfValue, newValueValue) + if let error = _swift_js_take_exception() { + throw error + } +} + +func _$ModuleCounter_increment(_ self: JSObject) throws(JSException) -> Int { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_ModuleCounter_increment(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return Int.bridgeJSLiftReturn(ret) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.d.ts new file mode 100644 index 000000000..624691d83 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.d.ts @@ -0,0 +1,21 @@ +// 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`. + +export interface ModuleCounter { + increment(): number; + value: number; +} +export type Exports = { +} +export type Imports = { +} +export function createInstantiator(options: { + imports: Imports; +}, swift: any): Promise<{ + addImports: (importObject: WebAssembly.Imports) => void; + setInstance: (instance: WebAssembly.Instance) => void; + createExports: (instance: WebAssembly.Instance) => Exports; +}>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.js new file mode 100644 index 000000000..cb4767f03 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.js @@ -0,0 +1,299 @@ +// 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`. + +import * as __bjs_imported_module_0 from "./bridge-js-modules/TestModule/Modules/JSImportModule.mjs"; +import * as __bjs_imported_module_1 from "./bridge-js-modules/TestModule/Modules/ModuleCounter.mjs"; + +export async function createInstantiator(options, swift) { + let instance; + let memory; + let setException; + let decodeString; + const textDecoder = new TextDecoder("utf-8"); + const textEncoder = new TextEncoder("utf-8"); + let tmpRetString; + let tmpRetBytes; + let tmpRetException; + let tmpRetOptionalBool; + let tmpRetOptionalInt; + let tmpRetOptionalFloat; + let tmpRetOptionalDouble; + let tmpRetOptionalHeapObject; + let strStack = []; + let i32Stack = []; + let i64Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; + let taStack = []; + const enumHelpers = {}; + const structHelpers = {}; + + let _exports = null; + let bjs = null; + + return { + /** + * @param {WebAssembly.Imports} importObject + */ + addImports: (importObject, importsContext) => { + bjs = {}; + importObject["bjs"] = bjs; + bjs["swift_js_return_string"] = function(ptr, len) { + tmpRetString = decodeString(ptr, len); + } + bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { + const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); + bytes.set(source); + } + bjs["swift_js_make_js_string"] = function(ptr, len) { + return swift.memory.retain(decodeString(ptr, len)); + } + bjs["swift_js_init_memory_with_result"] = function(ptr, len) { + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); + target.set(tmpRetBytes); + tmpRetBytes = undefined; + } + bjs["swift_js_throw"] = function(id) { + tmpRetException = swift.memory.retainByRef(id); + } + bjs["swift_js_retain"] = function(id) { + return swift.memory.retainByRef(id); + } + bjs["swift_js_release"] = function(id) { + swift.memory.release(id); + } + bjs["swift_js_push_i32"] = function(v) { + i32Stack.push(v | 0); + } + bjs["swift_js_push_f32"] = function(v) { + f32Stack.push(Math.fround(v)); + } + bjs["swift_js_push_f64"] = function(v) { + f64Stack.push(v); + } + bjs["swift_js_push_string"] = function(ptr, len) { + const value = decodeString(ptr, len); + strStack.push(value); + } + bjs["swift_js_pop_i32"] = function() { + return i32Stack.pop(); + } + bjs["swift_js_pop_f32"] = function() { + return f32Stack.pop(); + } + bjs["swift_js_pop_f64"] = function() { + return f64Stack.pop(); + } + bjs["swift_js_push_pointer"] = function(pointer) { + ptrStack.push(pointer); + } + bjs["swift_js_pop_pointer"] = function() { + return ptrStack.pop(); + } + bjs["swift_js_push_i64"] = function(v) { + i64Stack.push(v); + } + bjs["swift_js_pop_i64"] = function() { + return i64Stack.pop(); + } + const taCtors = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array]; + bjs["swift_js_push_typed_array"] = function(kind, ptr, count) { + const Ctor = taCtors[kind]; + const byteLen = count * Ctor.BYTES_PER_ELEMENT; + const copy = memory.buffer.slice(ptr, ptr + byteLen); + taStack.push(Array.from(new Ctor(copy))); + } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } + bjs["swift_js_return_optional_bool"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalBool = null; + } else { + tmpRetOptionalBool = value !== 0; + } + } + bjs["swift_js_return_optional_int"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalInt = null; + } else { + tmpRetOptionalInt = value | 0; + } + } + bjs["swift_js_return_optional_float"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalFloat = null; + } else { + tmpRetOptionalFloat = Math.fround(value); + } + } + bjs["swift_js_return_optional_double"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalDouble = null; + } else { + tmpRetOptionalDouble = value; + } + } + bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = decodeString(ptr, len); + } + } + bjs["swift_js_return_optional_object"] = function(isSome, objectId) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = swift.memory.getObject(objectId); + } + } + bjs["swift_js_return_optional_heap_object"] = function(isSome, pointer) { + if (isSome === 0) { + tmpRetOptionalHeapObject = null; + } else { + tmpRetOptionalHeapObject = pointer; + } + } + bjs["swift_js_get_optional_int_presence"] = function() { + return tmpRetOptionalInt != null ? 1 : 0; + } + bjs["swift_js_get_optional_int_value"] = function() { + const value = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; + return value; + } + bjs["swift_js_get_optional_string"] = function() { + const str = tmpRetString; + tmpRetString = undefined; + if (str == null) { + return -1; + } else { + const bytes = textEncoder.encode(str); + tmpRetBytes = bytes; + return bytes.length; + } + } + bjs["swift_js_get_optional_float_presence"] = function() { + return tmpRetOptionalFloat != null ? 1 : 0; + } + bjs["swift_js_get_optional_float_value"] = function() { + const value = tmpRetOptionalFloat; + tmpRetOptionalFloat = undefined; + return value; + } + bjs["swift_js_get_optional_double_presence"] = function() { + return tmpRetOptionalDouble != null ? 1 : 0; + } + bjs["swift_js_get_optional_double_value"] = function() { + const value = tmpRetOptionalDouble; + tmpRetOptionalDouble = undefined; + return value; + } + bjs["swift_js_get_optional_heap_object_pointer"] = function() { + const pointer = tmpRetOptionalHeapObject; + tmpRetOptionalHeapObject = undefined; + return pointer || 0; + } + bjs["swift_js_closure_unregister"] = function(funcRef) {} + const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; + TestModule["bjs_moduleVersion_get"] = function bjs_moduleVersion_get() { + try { + let ret = __bjs_imported_module_0.version; + tmpRetBytes = textEncoder.encode(ret); + return tmpRetBytes.length; + } catch (error) { + setException(error); + } + } + TestModule["bjs_moduleAdd"] = function bjs_moduleAdd(lhs, rhs) { + try { + let ret = __bjs_imported_module_0.moduleAdd(lhs, rhs); + return ret; + } catch (error) { + setException(error); + return 0 + } + } + TestModule["bjs_moduleRenamed"] = function bjs_moduleRenamed() { + try { + let ret = __bjs_imported_module_0.renamedFunction(); + tmpRetBytes = textEncoder.encode(ret); + return tmpRetBytes.length; + } catch (error) { + setException(error); + } + } + TestModule["bjs_ModuleCounter_init"] = function bjs_ModuleCounter_init(value) { + try { + return swift.memory.retain(new __bjs_imported_module_1.ModuleCounter(value)); + } catch (error) { + setException(error); + return 0 + } + } + TestModule["bjs_ModuleCounter_value_get"] = function bjs_ModuleCounter_value_get(self) { + try { + let ret = swift.memory.getObject(self).value; + return ret; + } catch (error) { + setException(error); + return 0 + } + } + TestModule["bjs_ModuleCounter_value_set"] = function bjs_ModuleCounter_value_set(self, newValue) { + try { + swift.memory.getObject(self).value = newValue; + } catch (error) { + setException(error); + } + } + TestModule["bjs_ModuleCounter_create_static"] = function bjs_ModuleCounter_create_static(value) { + try { + let ret = __bjs_imported_module_1.ModuleCounter.create(value); + return swift.memory.retain(ret); + } catch (error) { + setException(error); + return 0 + } + } + TestModule["bjs_ModuleCounter_increment"] = function bjs_ModuleCounter_increment(self) { + try { + let ret = swift.memory.getObject(self).increment(); + return ret; + } catch (error) { + setException(error); + return 0 + } + } + }, + setInstance: (i) => { + instance = i; + memory = instance.exports.memory; + + decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + + setException = (error) => { + instance.exports._swift_js_exception.value = swift.memory.retain(error) + } + }, + /** @param {WebAssembly.Instance} instance */ + createExports: (instance) => { + const js = swift.memory.heap; + const exports = { + }; + _exports = exports; + return exports; + }, + } +} \ No newline at end of file diff --git a/Plugins/PackageToJS/Sources/PackageToJS.swift b/Plugins/PackageToJS/Sources/PackageToJS.swift index ff3e2ce5a..d86a34fa1 100644 --- a/Plugins/PackageToJS/Sources/PackageToJS.swift +++ b/Plugins/PackageToJS/Sources/PackageToJS.swift @@ -273,6 +273,7 @@ struct PackageToJSError: Swift.Error, CustomStringConvertible { protocol PackagingSystem { func createDirectory(atPath: String) throws + func removeItemIfExists(atPath: String) throws func syncFile(from: String, to: String) throws func writeFile(atPath: String, content: Data) throws @@ -281,6 +282,12 @@ protocol PackagingSystem { } extension PackagingSystem { + func removeItemIfExists(atPath: String) throws { + if FileManager.default.fileExists(atPath: atPath) { + try FileManager.default.removeItem(atPath: atPath) + } + } + func createDirectory(atPath: String) throws { guard !FileManager.default.fileExists(atPath: atPath) else { return } try FileManager.default.createDirectory( @@ -387,8 +394,18 @@ private func runCommand(_ command: URL, _ arguments: [String]) throws { } } +struct BridgeJSSkeletonInput { + let source: URL + let targetDirectory: URL +} + /// Plans the build for packaging. struct PackagingPlanner { + struct JavaScriptModuleInput { + let source: BuildPath + let relativeOutputPath: String + } + /// The options for packaging let options: PackageToJS.PackageOptions /// The package ID of the package that this plugin is running on @@ -398,7 +415,7 @@ struct PackagingPlanner { /// The path of this file itself, used to capture changes of planner code let selfPath: BuildPath /// The BridgeJS API skeletons source files - let skeletons: [BuildPath] + let skeletons: [BridgeJSSkeletonInput] /// The directory for the final output let outputDir: BuildPath /// The directory for intermediate files @@ -419,7 +436,7 @@ struct PackagingPlanner { packageId: String, intermediatesDir: BuildPath, selfPackageDir: BuildPath, - skeletons: [BuildPath], + skeletons: [BridgeJSSkeletonInput], outputDir: BuildPath, wasmProductArtifact: BuildPath, wasmFilename: String, @@ -594,24 +611,49 @@ struct PackagingPlanner { ) packageInputs.append(packageJsonTask) - if skeletons.count > 0 { + if !skeletons.isEmpty { + let bridge = try loadBridgeJS() + let skeletonFiles = skeletons.map { BuildPath(absolute: $0.source.path) } let bridgeJs = outputDir.appending(path: "bridge-js.js") let bridgeDts = outputDir.appending(path: "bridge-js.d.ts") + let bridgeModules = outputDir.appending(path: "bridge-js-modules") packageInputs.append( - make.addTask(inputFiles: skeletons + [selfPath], output: bridgeJs) { _, scope in - var link = BridgeJSLink( - sharedMemory: Self.isSharedMemoryEnabled(triple: triple) + make.addTask(inputFiles: skeletonFiles + [selfPath], output: bridgeJs) { _, scope in + let output = try bridge.link.link() + try system.writeFile( + atPath: scope.resolve(path: bridgeJs).path, + content: Data(output.outputJs.utf8) ) - - // Decode skeleton format - for skeletonPath in skeletons { - let data = try Data(contentsOf: URL(fileURLWithPath: scope.resolve(path: skeletonPath).path)) - try link.addSkeletonFile(data: data) + try system.writeFile( + atPath: scope.resolve(path: bridgeDts).path, + content: Data(output.outputDts.utf8) + ) + } + ) + let bridgeModulesStamp = intermediatesDir.appending(path: "bridge-js-modules.stamp") + packageInputs.append( + make.addTask( + inputFiles: skeletonFiles + bridge.modules.map(\.source) + [selfPath], + inputTasks: [outputDirTask, intermediatesDirTask], + output: bridgeModulesStamp + ) { _, scope in + let modulesDirectory = scope.resolve(path: bridgeModules) + try system.removeItemIfExists(atPath: modulesDirectory.path) + if !bridge.modules.isEmpty { + try system.createDirectory(atPath: modulesDirectory.path) } - - let (outputJs, outputDts) = try link.link() - try system.writeFile(atPath: scope.resolve(path: bridgeJs).path, content: Data(outputJs.utf8)) - try system.writeFile(atPath: scope.resolve(path: bridgeDts).path, content: Data(outputDts.utf8)) + for module in bridge.modules { + let destination = scope.resolve(path: outputDir.appending(path: module.relativeOutputPath)) + try system.createDirectory(atPath: destination.deletingLastPathComponent().path) + try system.syncFile( + from: scope.resolve(path: module.source).path, + to: destination.path + ) + } + try system.writeFile( + atPath: scope.resolve(path: bridgeModulesStamp).path, + content: Data() + ) } ) } @@ -645,6 +687,47 @@ struct PackagingPlanner { return (packageInputs, outputDirTask, intermediatesDirTask, packageJsonTask) } + private func loadBridgeJS() throws -> ( + link: BridgeJSLink, + modules: [JavaScriptModuleInput] + ) { + var link = BridgeJSLink( + sharedMemory: Self.isSharedMemoryEnabled(triple: triple) + ) + var moduleSources: [String: BuildPath] = [:] + + for input in skeletons { + let skeleton = try link.addSkeletonFile(data: Data(contentsOf: input.source)) + for reference in ImportedJSModuleRegistry.collectReferences(skeletons: [skeleton]) { + guard + let sourceURL = JavaScriptModulePath.resolve( + reference.path, + relativeTo: input.targetDirectory + ), + JavaScriptModulePath.isRegularFile(at: sourceURL) + else { + throw PackageToJSError( + "JavaScript module file was not found at '\(reference.path)' in target '\(skeleton.moduleName)'." + ) + } + let source = BuildPath(absolute: sourceURL.path) + if let existing = moduleSources[reference.relativeOutputPath], existing != source { + throw PackageToJSError( + "Conflicting JavaScript module sources for '\(reference.relativeOutputPath)'." + ) + } + moduleSources[reference.relativeOutputPath] = source + } + } + + return ( + link, + moduleSources.sorted { $0.key < $1.key }.map { + JavaScriptModuleInput(source: $0.value, relativeOutputPath: $0.key) + } + ) + } + /// Construct the test build plan and return the root task key func planTestBuild( make: inout MiniMake diff --git a/Plugins/PackageToJS/Sources/PackageToJSPlugin.swift b/Plugins/PackageToJS/Sources/PackageToJSPlugin.swift index 7686372f9..cc16de20a 100644 --- a/Plugins/PackageToJS/Sources/PackageToJSPlugin.swift +++ b/Plugins/PackageToJS/Sources/PackageToJSPlugin.swift @@ -704,7 +704,7 @@ class SkeletonCollector { private var visitedProducts: Set = [] private var visitedTargets: Set = [] - var skeletons: [URL] = [] + var skeletons: [BridgeJSSkeletonInput] = [] let skeletonFile = "BridgeJS.json" let context: PluginContext @@ -712,7 +712,7 @@ class SkeletonCollector { self.context = context } - func collectFromProduct(name: String) -> [URL] { + func collectFromProduct(name: String) -> [BridgeJSSkeletonInput] { guard let product = context.package.products.first(where: { $0.name == name }) else { return [] } @@ -720,7 +720,7 @@ class SkeletonCollector { return skeletons } - func collectFromTests() -> [URL] { + func collectFromTests() -> [BridgeJSSkeletonInput] { let tests = context.package.targets.filter { guard let target = $0 as? SwiftSourceModuleTarget else { return false } return target.kind == .test @@ -758,7 +758,12 @@ class SkeletonCollector { ] for skeletonURL in candidates { if FileManager.default.fileExists(atPath: skeletonURL.path) { - skeletons.append(skeletonURL) + skeletons.append( + BridgeJSSkeletonInput( + source: skeletonURL, + targetDirectory: target.directoryURL + ) + ) } } } @@ -788,7 +793,7 @@ extension PackagingPlanner { options: PackageToJS.PackageOptions, context: PluginContext, selfPackage: Package, - skeletons: [URL], + skeletons: [BridgeJSSkeletonInput], outputDir: URL, wasmProductArtifact: URL, wasmFilename: String @@ -803,7 +808,7 @@ extension PackagingPlanner { absolute: context.pluginWorkDirectoryURL.appending(path: outputBaseName + ".tmp").path ), selfPackageDir: BuildPath(absolute: selfPackage.directoryURL.path), - skeletons: skeletons.map { BuildPath(absolute: $0.path) }, + skeletons: skeletons, outputDir: BuildPath(absolute: outputDir.path), wasmProductArtifact: BuildPath(absolute: wasmProductArtifact.path), wasmFilename: wasmFilename, diff --git a/Plugins/PackageToJS/Templates/runtime.mjs b/Plugins/PackageToJS/Templates/runtime.mjs index daf4f3ab0..b0be54bb4 100644 --- a/Plugins/PackageToJS/Templates/runtime.mjs +++ b/Plugins/PackageToJS/Templates/runtime.mjs @@ -49,13 +49,15 @@ const decode = (kind, payload1, payload2, objectSpace) => { // Note: // `decodeValues` assumes that the size of RawJSValue is 16. const decodeArray = (ptr, length, memory, objectSpace) => { + const basePtr = ptr >>> 0; + const count = length >>> 0; // fast path for empty array - if (length === 0) { + if (count === 0) { return []; } let result = []; - for (let index = 0; index < length; index++) { - const base = ptr + 16 * index; + for (let index = 0; index < count; index++) { + const base = basePtr + 16 * index; const kind = memory.getUint32(base, true); const payload1 = memory.getUint32(base + 4, true); const payload2 = memory.getFloat64(base + 8, true); @@ -69,25 +71,27 @@ const decodeArray = (ptr, length, memory, objectSpace) => { // This function should be used only when kind flag is stored in memory. const write = (value, kind_ptr, payload1_ptr, payload2_ptr, is_exception, memory, objectSpace) => { const kind = writeAndReturnKindBits(value, payload1_ptr, payload2_ptr, is_exception, memory, objectSpace); - memory.setUint32(kind_ptr, kind, true); + memory.setUint32(kind_ptr >>> 0, kind, true); }; const writeAndReturnKindBits = (value, payload1_ptr, payload2_ptr, is_exception, memory, objectSpace) => { const exceptionBit = (is_exception ? 1 : 0) << 31; + const payload1Offset = payload1_ptr >>> 0; + const payload2Offset = payload2_ptr >>> 0; if (value === null) { return exceptionBit | 4 /* Kind.Null */; } const writeRef = (kind) => { - memory.setUint32(payload1_ptr, objectSpace.retain(value), true); + memory.setUint32(payload1Offset, objectSpace.retain(value), true); return exceptionBit | kind; }; const type = typeof value; switch (type) { case "boolean": { - memory.setUint32(payload1_ptr, value ? 1 : 0, true); + memory.setUint32(payload1Offset, value ? 1 : 0, true); return exceptionBit | 0 /* Kind.Boolean */; } case "number": { - memory.setFloat64(payload2_ptr, value, true); + memory.setFloat64(payload2Offset, value, true); return exceptionBit | 2 /* Kind.Number */; } case "string": { @@ -114,9 +118,11 @@ const writeAndReturnKindBits = (value, payload1_ptr, payload2_ptr, is_exception, throw new Error("Unreachable"); }; function decodeObjectRefs(ptr, length, memory) { - const result = new Array(length); - for (let i = 0; i < length; i++) { - result[i] = memory.getUint32(ptr + 4 * i, true); + const basePtr = ptr >>> 0; + const count = length >>> 0; + const result = new Array(count); + for (let i = 0; i < count; i++) { + result[i] = memory.getUint32(basePtr + 4 * i, true); } return result; } @@ -617,25 +623,29 @@ class SwiftRuntime { const memory = this.memory; const bytes = this.textEncoder.encode(memory.getObject(ref)); const bytes_ptr = memory.retain(bytes); - this.getDataView().setUint32(bytes_ptr_result, bytes_ptr, true); + this.getDataView().setUint32(bytes_ptr_result >>> 0, bytes_ptr, true); return bytes.length; }, swjs_decode_string: // NOTE: TextDecoder can't decode typed arrays backed by SharedArrayBuffer this.options.sharedMemory == true ? (bytes_ptr, length) => { - const bytes = this.getUint8Array().slice(bytes_ptr, bytes_ptr + length); + const bytesOffset = bytes_ptr >>> 0; + const byteLength = length >>> 0; + const bytes = this.getUint8Array().slice(bytesOffset, bytesOffset + byteLength); const string = this.textDecoder.decode(bytes); return this.memory.retain(string); } : (bytes_ptr, length) => { - const bytes = this.getUint8Array().subarray(bytes_ptr, bytes_ptr + length); + const bytesOffset = bytes_ptr >>> 0; + const byteLength = length >>> 0; + const bytes = this.getUint8Array().subarray(bytesOffset, bytesOffset + byteLength); const string = this.textDecoder.decode(bytes); return this.memory.retain(string); }, swjs_load_string: (ref, buffer) => { const bytes = this.memory.getObject(ref); - this.getUint8Array().set(bytes, buffer); + this.getUint8Array().set(bytes, buffer >>> 0); }, swjs_call_function: (ref, argv, argc, payload1_ptr, payload2_ptr) => { const memory = this.memory; @@ -739,7 +749,7 @@ class SwiftRuntime { // See https://github.com/swiftwasm/swift/issues/5599 return this.memory.retain(new ArrayType()); } - const array = new ArrayType(this.wasmMemory.buffer, elementsPtr, length); + const array = new ArrayType(this.wasmMemory.buffer, elementsPtr >>> 0, length >>> 0); // Call `.slice()` to copy the memory return this.memory.retain(array.slice()); }, @@ -750,7 +760,7 @@ class SwiftRuntime { const memory = this.memory; const typedArray = memory.getObject(ref); const bytes = new Uint8Array(typedArray.buffer); - this.getUint8Array().set(bytes, buffer); + this.getUint8Array().set(bytes, buffer >>> 0); }, swjs_release: (ref) => { this.memory.release(ref); diff --git a/Plugins/PackageToJS/Tests/PackagingPlannerTests.swift b/Plugins/PackageToJS/Tests/PackagingPlannerTests.swift index 3e0d67a3e..e5f04402a 100644 --- a/Plugins/PackageToJS/Tests/PackagingPlannerTests.swift +++ b/Plugins/PackageToJS/Tests/PackagingPlannerTests.swift @@ -9,10 +9,16 @@ import Testing } class TestPackagingSystem: PackagingSystem { var npmInstallCalls: [String] = [] + var writtenFiles: [String] = [] func npmInstall(packageDir: String) throws { npmInstallCalls.append(packageDir) } + func writeFile(atPath: String, content: Data) throws { + writtenFiles.append(atPath) + try content.write(to: URL(fileURLWithPath: atPath)) + } + func wasmOpt(_ arguments: [String], input: String, output: String) throws { try FileManager.default.copyItem( at: URL(fileURLWithPath: input), @@ -110,4 +116,96 @@ import Testing return root } } + + @Test func editingJavaScriptModuleOnlyResyncsModules() throws { + try withTemporaryDirectory { temporaryDirectory, _ in + let skeleton = temporaryDirectory.appending(path: "BridgeJS.json") + let module = temporaryDirectory.appending(path: "module.mjs") + let wasm = temporaryDirectory.appending(path: "main.wasm") + let plannerSource = temporaryDirectory.appending(path: "PackageToJS.swift") + let output = temporaryDirectory.appending(path: "output") + let intermediates = temporaryDirectory.appending(path: "intermediates") + + let bridgeSkeleton = BridgeJSSkeleton( + moduleName: "TestModule", + imported: ImportedModuleSkeleton( + children: [ + ImportedFileSkeleton( + functions: [ + ImportedFunctionSkeleton( + name: "value", + from: .module("/module.mjs"), + parameters: [], + returnType: .void + ) + ], + types: [] + ) + ] + ) + ) + try JSONEncoder().encode(bridgeSkeleton).write(to: skeleton) + try Data("export const value = 1;\n".utf8).write(to: module) + try Data([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]).write(to: wasm) + try Data().write(to: plannerSource) + + let system = TestPackagingSystem() + let planner = PackagingPlanner( + options: PackageToJS.PackageOptions(), + packageId: "test", + intermediatesDir: BuildPath(absolute: intermediates.path), + selfPackageDir: BuildPath( + absolute: URL(fileURLWithPath: #filePath) + .deletingLastPathComponent() + .deletingLastPathComponent() + .deletingLastPathComponent() + .deletingLastPathComponent() + .path + ), + skeletons: [ + .init( + source: skeleton, + targetDirectory: temporaryDirectory + ) + ], + outputDir: BuildPath(absolute: output.path), + wasmProductArtifact: BuildPath(absolute: wasm.path), + wasmFilename: "main.wasm", + configuration: "debug", + triple: "wasm32-unknown-wasi", + selfPath: BuildPath(absolute: plannerSource.path), + system: system + ) + var make = MiniMake(printProgress: { _, _ in }) + let root = try planner.planBuild( + make: &make, + buildOptions: PackageToJS.BuildOptions( + product: "test", + noOptimize: false, + debugInfoFormat: .none, + packageOptions: PackageToJS.PackageOptions() + ) + ) + let scope = MiniMake.VariableScope(variables: [:]) + + try make.build(output: root, scope: scope) + + let copiedModule = output.appending( + path: "bridge-js-modules/TestModule/module.mjs" + ) + #expect(try String(contentsOf: copiedModule, encoding: .utf8) == "export const value = 1;\n") + let initialLinkCount = system.writtenFiles.filter { $0.hasSuffix("/bridge-js.js") }.count + #expect(initialLinkCount == 1) + + try Data("export const value = 2;\n".utf8).write(to: module) + try FileManager.default.setAttributes( + [.modificationDate: Date().addingTimeInterval(10)], + ofItemAtPath: module.path + ) + try make.build(output: root, scope: scope) + + #expect(try String(contentsOf: copiedModule, encoding: .utf8) == "export const value = 2;\n") + #expect(system.writtenFiles.filter { $0.hasSuffix("/bridge-js.js") }.count == initialLinkCount) + } + } } diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript-into-Swift.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript-into-Swift.md index 14fccbfc1..6d06d4339 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript-into-Swift.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript-into-Swift.md @@ -8,7 +8,7 @@ Learn how to make JavaScript APIs callable from your Swift code using macro-anno > Tip: You can quickly preview what interfaces will be exposed on the Swift/JavaScript/TypeScript sides using the [BridgeJS Playground](https://swiftwasm.org/JavaScriptKit/PlayBridgeJS/). -You can import JavaScript APIs into Swift in two ways: +You can define JavaScript bindings for Swift in two ways: 1. **Annotate Swift with macros** - Use `@JSFunction`, `@JSClass`, `@JSGetter`, and `@JSSetter` to declare bindings directly in Swift. No TypeScript required. Prefer this to get started. 2. **Generate bindings from TypeScript** - Use a `bridge-js.d.ts` file; the BridgeJS plugin generates the same macro-annotated Swift. See when you have existing `.d.ts` definitions or many APIs to bind. @@ -25,10 +25,13 @@ Add the BridgeJS plugin and enable the Extern feature as described in for an example. ```swift import JavaScriptKit @@ -95,4 +98,4 @@ exports.run(); - - -- \ No newline at end of file +- diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Class.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Class.md index 4302e0e49..185b47d1f 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Class.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Class.md @@ -24,6 +24,28 @@ import JavaScriptKit If the class is on `globalThis`, add `from: .global` to `@JSClass` and omit the type from `getImports()` in the next step. +For a class shipped as an ECMAScript module, put the origin on `@JSClass`: + +```javascript +// JavaScript/greeter.js +export class Greeter { + constructor(name) { this.name = name; } + static named(name) { return new Greeter(name); } + greet() { return `Hello, ${this.name}!`; } +} +``` + +```swift +@JSClass(from: .module("/JavaScript/greeter.js")) +struct Greeter { + @JSFunction init(_ name: String) throws(JSException) + @JSFunction static func named(_ name: String) throws(JSException) -> Greeter + @JSFunction func greet() throws(JSException) -> String +} +``` + +The path's leading `/` denotes the Swift target root, not the filesystem root. The module's named class export is the root for construction and static methods. Instance methods, getters, and setters operate on the wrapped object and must not specify their own `from:` argument. Use `jsName` on `@JSClass` to select a differently named class export. JavaScript inheritance may be implemented normally in the module; the Swift declaration describes the API visible on the exported class and its instances. + ### 2. Wire the JavaScript side **If you chose injection:** Implement the class in JavaScript and pass it in `getImports()`. @@ -47,7 +69,7 @@ const { exports } = await init({ }); ``` -**If you chose global:** Do not pass the class in `getImports()`; the runtime will resolve it from `globalThis`. +**If you chose global or module-backed lookup:** Do not pass the class in `getImports()`; the runtime resolves it from `globalThis` or the copied module. ## Macro options diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Function.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Function.md index 64475acfa..c57aeda03 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Function.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Function.md @@ -17,6 +17,30 @@ import JavaScriptKit To bind a function that lives on the JavaScript global object (e.g. `parseInt`, `setTimeout`), add `from: .global`. Use `jsName` when the Swift name differs from the JavaScript name - see the ``JSFunction(jsName:from:)`` API reference for options. +To ship the function with the Swift target, put it in a `.js` or `.mjs` ECMAScript module and use a target-rooted path: + +```javascript +// JavaScript/math.js +export function add(a, b) { return a + b; } +``` + +```swift +@JSFunction(from: .module("/JavaScript/math.js")) +func add(_ a: Double, _ b: Double) throws(JSException) -> Double +``` + +The leading `/` denotes the Swift target root, not the filesystem root. BridgeJS copies explicitly referenced modules into the generated PackageToJS package. Multiple declarations may reference the same file; it is copied and imported only once. `jsName` selects a differently named export, otherwise BridgeJS uses the normalized Swift name. + +SwiftPM does not know what to do with `.js`/`.mjs` files inside a target, so exclude the directory holding them to avoid an "unhandled files" warning: + +```swift +.target( + name: "MyApp", + exclude: ["JavaScript"], + plugins: [.plugin(name: "BridgeJS", package: "JavaScriptKit")] +) +``` + ### 2. Provide the implementation at initialization Return the corresponding function(s) in the object passed to `getImports()` when initializing the WebAssembly module. @@ -35,7 +59,7 @@ const { exports } = await init({ }); ``` -If you used `from: .global`, do not pass the function in `getImports()`; the runtime resolves it from `globalThis`. +If you used `from: .global` or `.module`, do not pass the function in `getImports()`. Module-only bindings do not require `getImports()` at all. ### 3. Handle errors diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Variable.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Variable.md index 044ebbe52..6825875dd 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Variable.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Variable.md @@ -17,6 +17,20 @@ import JavaScriptKit To bind a variable that is not on `globalThis`, omit `from: .global` and supply the value in `getImports()` in the next step. Use `jsName` when the Swift name differs from the JavaScript property name - see the ``JSGetter(jsName:from:)`` API reference. +A top-level getter can also read a named export from a target-rooted module: + +```javascript +// JavaScript/config.js +export const environment = "production"; +``` + +```swift +@JSGetter(jsName: "environment", from: .module("/JavaScript/config.js")) +var currentEnvironment: String +``` + +The path's leading `/` denotes the Swift target root, not the filesystem root. Module exports are read-only through this API. Top-level `@JSSetter` remains unsupported. + ### 2. Add a setter for writable variables (optional) If the JavaScript property is writable and you need to set it from Swift, add a corresponding `@JSSetter` function. Property setters are exposed as functions (e.g. `setMyConfig(_:)`) because Swift property setters cannot `throw`. @@ -28,7 +42,7 @@ If the JavaScript property is writable and you need to set it from Swift, add a ### 3. Provide the value at initialization (injected only) -If you did **not** use `from: .global`, pass the value in the object returned by `getImports()` when initializing the WebAssembly module. +If you omitted `from`, pass the value in the object returned by `getImports()` when initializing the WebAssembly module. ```javascript // index.js @@ -43,13 +57,14 @@ const { exports } = await init({ }); ``` -If you used `from: .global`, do not pass the variable in `getImports()`; the runtime reads it from `globalThis`. +If you used `from: .global` or `.module`, do not pass the variable in `getImports()`; the runtime resolves it from `globalThis` or the copied module. ## Supported features | Feature | Status | |:--|:--| | Read-only global (e.g. `document`, `console`) | ✅ | +| Read-only module export | ✅ | | Writable global | ✅ (`@JSSetter`) | | Injected variable (via `getImports()`) | ✅ | diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Unsupported-Features.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Unsupported-Features.md index 83213aca1..238bc8687 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Unsupported-Features.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Unsupported-Features.md @@ -6,6 +6,14 @@ Limitations and unsupported patterns when using BridgeJS. BridgeJS generates glue code per Swift target (module). Some patterns that are valid in Swift or TypeScript are not supported across the bridge today. This article summarizes the main limitations so you can design your APIs accordingly. +## File-backed JavaScript modules + +Files referenced by `JSImportFrom.module` must be nonempty `.js` or `.mjs` paths beginning with `/`. This leading slash denotes the Swift target root, not the filesystem root. Files must remain within that Swift target. Only explicitly referenced files are copied. BridgeJS does not discover or rewrite an imported module's dependency graph, so referenced files should currently be self-contained. + +Generated packages use static ECMAScript module imports. This works with the existing PackageToJS browser and Node ESM entry points. CommonJS and classic non-module script output are not generated or translated. + +Module origins apply to top-level `@JSFunction`, top-level `@JSGetter`, and an entire `@JSClass`. Per-member origins, top-level setters, inline JavaScript source, package-root-relative paths, and per-member module overrides are not supported. + ## Type usage crossing module boundary ### Exporting Swift: extending types from another Swift module diff --git a/Sources/JavaScriptKit/Macros.swift b/Sources/JavaScriptKit/Macros.swift index 191cf15d6..7a1bb4091 100644 --- a/Sources/JavaScriptKit/Macros.swift +++ b/Sources/JavaScriptKit/Macros.swift @@ -9,8 +9,11 @@ public enum JSEnumStyle: String { /// Controls where BridgeJS reads imported JS values from. /// /// - `global`: Read from `globalThis`. -public enum JSImportFrom: String { +/// - `module`: Read a named export from an ECMAScript module file rooted at the Swift target. +public enum JSImportFrom { case global + /// Read from an ECMAScript module file using a `/`-prefixed path rooted at the Swift target directory. + case module(String) } /// A macro that exposes Swift functions, classes, and methods to JavaScript. @@ -141,6 +144,7 @@ public macro JS( /// /// - Parameter from: Selects where the property is read from. /// Use `.global` to read from `globalThis` (e.g. `console`, `document`). +/// Use `.module("/path/to/module.js")` to read a named export from a file rooted at the Swift target. @attached(accessor) public macro JSGetter(jsName: String? = nil, from: JSImportFrom? = nil) = #externalMacro(module: "BridgeJSMacros", type: "JSGetterMacro") @@ -180,6 +184,7 @@ public macro JSSetter(jsName: String? = nil, from: JSImportFrom? = nil) = /// If not provided, the Swift function name is used. /// - Parameter from: Selects where the function is looked up from. /// Use `.global` to call a function on `globalThis` (e.g. `setTimeout`). +/// Use `.module("/path/to/module.js")` to call a named export from a file rooted at the Swift target. @attached(body) public macro JSFunction(jsName: String? = nil, from: JSImportFrom? = nil) = #externalMacro(module: "BridgeJSMacros", type: "JSFunctionMacro") @@ -204,6 +209,7 @@ public macro JSFunction(jsName: String? = nil, from: JSImportFrom? = nil) = /// /// - Parameter from: Selects where the constructor is looked up from. /// Use `.global` to construct globals like `WebSocket` via `globalThis`. +/// Use `.module("/path/to/module.js")` to construct a named class export from a file rooted at the Swift target. @attached(member, names: named(jsObject), named(init(unsafelyWrapping:))) @attached(extension, conformances: _JSBridgedClass) public macro JSClass(jsName: String? = nil, from: JSImportFrom? = nil) = diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 201c80e22..39de49ca0 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -17010,6 +17010,192 @@ func _$JSClassSupportImports_makeJSClassWithArrayMembers(_ numbers: [Int], _ lab return JSClassWithArrayMembers.bridgeJSLiftReturn(ret) } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_moduleVersion_get") +fileprivate func bjs_moduleVersion_get_extern() -> Int32 +#else +fileprivate func bjs_moduleVersion_get_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_moduleVersion_get() -> Int32 { + return bjs_moduleVersion_get_extern() +} + +func _$moduleVersion_get() throws(JSException) -> String { + let ret = bjs_moduleVersion_get() + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_moduleAdd") +fileprivate func bjs_moduleAdd_extern(_ lhs: Int32, _ rhs: Int32) -> Int32 +#else +fileprivate func bjs_moduleAdd_extern(_ lhs: Int32, _ rhs: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_moduleAdd(_ lhs: Int32, _ rhs: Int32) -> Int32 { + return bjs_moduleAdd_extern(lhs, rhs) +} + +func _$moduleAdd(_ lhs: Int, _ rhs: Int) throws(JSException) -> Int { + let rhsValue = rhs.bridgeJSLowerParameter() + let lhsValue = lhs.bridgeJSLowerParameter() + let ret = bjs_moduleAdd(lhsValue, rhsValue) + if let error = _swift_js_take_exception() { + throw error + } + return Int.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_moduleRenamed") +fileprivate func bjs_moduleRenamed_extern() -> Int32 +#else +fileprivate func bjs_moduleRenamed_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_moduleRenamed() -> Int32 { + return bjs_moduleRenamed_extern() +} + +func _$moduleRenamed() throws(JSException) -> String { + let ret = bjs_moduleRenamed() + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_moduleThrow") +fileprivate func bjs_moduleThrow_extern() -> Void +#else +fileprivate func bjs_moduleThrow_extern() -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_moduleThrow() -> Void { + return bjs_moduleThrow_extern() +} + +func _$moduleThrow() throws(JSException) -> Void { + bjs_moduleThrow() + if let error = _swift_js_take_exception() { + throw error + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ModuleCounter_init") +fileprivate func bjs_ModuleCounter_init_extern(_ value: Int32) -> Int32 +#else +fileprivate func bjs_ModuleCounter_init_extern(_ value: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ModuleCounter_init(_ value: Int32) -> Int32 { + return bjs_ModuleCounter_init_extern(value) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ModuleCounter_create_static") +fileprivate func bjs_ModuleCounter_create_static_extern(_ value: Int32) -> Int32 +#else +fileprivate func bjs_ModuleCounter_create_static_extern(_ value: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ModuleCounter_create_static(_ value: Int32) -> Int32 { + return bjs_ModuleCounter_create_static_extern(value) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ModuleCounter_value_get") +fileprivate func bjs_ModuleCounter_value_get_extern(_ self: Int32) -> Int32 +#else +fileprivate func bjs_ModuleCounter_value_get_extern(_ self: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ModuleCounter_value_get(_ self: Int32) -> Int32 { + return bjs_ModuleCounter_value_get_extern(self) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ModuleCounter_value_set") +fileprivate func bjs_ModuleCounter_value_set_extern(_ self: Int32, _ newValue: Int32) -> Void +#else +fileprivate func bjs_ModuleCounter_value_set_extern(_ self: Int32, _ newValue: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ModuleCounter_value_set(_ self: Int32, _ newValue: Int32) -> Void { + return bjs_ModuleCounter_value_set_extern(self, newValue) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ModuleCounter_increment") +fileprivate func bjs_ModuleCounter_increment_extern(_ self: Int32) -> Int32 +#else +fileprivate func bjs_ModuleCounter_increment_extern(_ self: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ModuleCounter_increment(_ self: Int32) -> Int32 { + return bjs_ModuleCounter_increment_extern(self) +} + +func _$ModuleCounter_init(_ value: Int) throws(JSException) -> JSObject { + let valueValue = value.bridgeJSLowerParameter() + let ret = bjs_ModuleCounter_init(valueValue) + if let error = _swift_js_take_exception() { + throw error + } + return JSObject.bridgeJSLiftReturn(ret) +} + +func _$ModuleCounter_create(_ value: Int) throws(JSException) -> ModuleCounter { + let valueValue = value.bridgeJSLowerParameter() + let ret = bjs_ModuleCounter_create_static(valueValue) + if let error = _swift_js_take_exception() { + throw error + } + return ModuleCounter.bridgeJSLiftReturn(ret) +} + +func _$ModuleCounter_value_get(_ self: JSObject) throws(JSException) -> Int { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_ModuleCounter_value_get(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return Int.bridgeJSLiftReturn(ret) +} + +func _$ModuleCounter_value_set(_ self: JSObject, _ newValue: Int) throws(JSException) -> Void { + let newValueValue = newValue.bridgeJSLowerParameter() + let selfValue = self.bridgeJSLowerParameter() + bjs_ModuleCounter_value_set(selfValue, newValueValue) + if let error = _swift_js_take_exception() { + throw error + } +} + +func _$ModuleCounter_increment(_ self: JSObject) throws(JSException) -> Int { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_ModuleCounter_increment(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return Int.bridgeJSLiftReturn(ret) +} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_JSTypedArrayImports_jsCreateUint8Array_static") fileprivate func bjs_JSTypedArrayImports_jsCreateUint8Array_static_extern() -> Int32 diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index 0eac614c7..e0c30c428 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -24174,6 +24174,205 @@ } ] }, + { + "functions" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "from" : "\/Modules\/JSImportModule.mjs", + "name" : "moduleAdd", + "parameters" : [ + { + "name" : "lhs", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "name" : "rhs", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "from" : "\/Modules\/JSImportModule.mjs", + "jsName" : "renamedFunction", + "name" : "moduleRenamed", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "from" : "\/Modules\/JSImportModule.mjs", + "name" : "moduleThrow", + "parameters" : [ + + ], + "returnType" : { + "void" : { + + } + } + } + ], + "globalGetters" : [ + { + "accessLevel" : "internal", + "from" : "\/Modules\/JSImportModule.mjs", + "jsName" : "version", + "name" : "moduleVersion", + "type" : { + "string" : { + + } + } + } + ], + "types" : [ + { + "accessLevel" : "internal", + "constructor" : { + "accessLevel" : "internal", + "parameters" : [ + { + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ] + }, + "from" : "\/Modules\/ModuleCounter.mjs", + "getters" : [ + { + "accessLevel" : "internal", + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "methods" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "increment", + "parameters" : [ + + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "name" : "ModuleCounter", + "setters" : [ + { + "accessLevel" : "internal", + "functionName" : "value_set", + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "staticMethods" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "create", + "parameters" : [ + { + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "jsObject" : { + "_0" : "ModuleCounter" + } + } + } + ] + } + ] + }, { "functions" : [ diff --git a/Tests/BridgeJSRuntimeTests/JSImportModuleTests.swift b/Tests/BridgeJSRuntimeTests/JSImportModuleTests.swift new file mode 100644 index 000000000..4cc228328 --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/JSImportModuleTests.swift @@ -0,0 +1,47 @@ +import JavaScriptKit +import XCTest + +@JSFunction(from: .module("/Modules/JSImportModule.mjs")) +func moduleAdd(_ lhs: Int, _ rhs: Int) throws(JSException) -> Int + +@JSFunction(jsName: "renamedFunction", from: .module("/Modules/JSImportModule.mjs")) +func moduleRenamed() throws(JSException) -> String + +@JSFunction(from: .module("/Modules/JSImportModule.mjs")) +func moduleThrow() throws(JSException) + +@JSGetter(jsName: "version", from: .module("/Modules/JSImportModule.mjs")) +var moduleVersion: String + +@JSClass(from: .module("/Modules/ModuleCounter.mjs")) +struct ModuleCounter { + @JSFunction init(_ value: Int) throws(JSException) + @JSFunction static func create(_ value: Int) throws(JSException) -> ModuleCounter + @JSFunction func increment() throws(JSException) -> Int + @JSGetter var value: Int + @JSSetter func setValue(_ value: Int) throws(JSException) +} + +final class JSImportModuleTests: XCTestCase { + func testModuleFunctionAndGetter() throws { + XCTAssertEqual(try moduleAdd(20, 22), 42) + XCTAssertEqual(try moduleRenamed(), "loaded from a module") + XCTAssertEqual(try moduleVersion, "module-v1") + } + + func testModuleFunctionPropagatesJavaScriptException() { + XCTAssertThrowsError(try moduleThrow()) { error in + XCTAssertTrue(error is JSException) + } + } + + func testModuleClassStaticAndInstanceAPIs() throws { + let constructed = try ModuleCounter(3) + XCTAssertEqual(try constructed.increment(), 4) + try constructed.setValue(9) + XCTAssertEqual(try constructed.value, 9) + + let created = try ModuleCounter.create(40) + XCTAssertEqual(try created.increment(), 41) + } +} diff --git a/Tests/BridgeJSRuntimeTests/Modules/JSImportModule.mjs b/Tests/BridgeJSRuntimeTests/Modules/JSImportModule.mjs new file mode 100644 index 000000000..834537e10 --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/Modules/JSImportModule.mjs @@ -0,0 +1,13 @@ +export function moduleAdd(lhs, rhs) { + return lhs + rhs; +} + +export function renamedFunction() { + return "loaded from a module"; +} + +export function moduleThrow() { + throw new Error("module failure"); +} + +export const version = "module-v1"; diff --git a/Tests/BridgeJSRuntimeTests/Modules/ModuleCounter.mjs b/Tests/BridgeJSRuntimeTests/Modules/ModuleCounter.mjs new file mode 100644 index 000000000..5a33b7ffa --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/Modules/ModuleCounter.mjs @@ -0,0 +1,17 @@ +export class ModuleCounter { + constructor(value) { + this.value = value; + } + + static create(value) { + return new ModuleCounter(value); + } + + increment() { + return ++this.value; + } + + setValue(value) { + this.value = value; + } +} From e53155dc358e85db61b7ff5b1000cb6ed4a53a2d Mon Sep 17 00:00:00 2001 From: Yuta Saito Date: Mon, 3 Aug 2026 13:14:29 +0100 Subject: [PATCH 33/50] BridgeJS: import from external ECMAScript modules, and split snippet origins (#795) * BridgeJS: support importing from external ECMAScript modules Extend `from: .module(...)` to accept bare specifiers like `node:path` or an npm package, add `jsName: .default` for default exports, and emit named imports so a wrong export name now fails at module-link time instead of at call time. * BridgeJS: fix named-import regressions found in review Do not require a module export for a wrapper-only `@JSClass`, since a named import is a link-time requirement and nothing looks that name up; accept `jsName: nil` and the explicit `.name(...)` spelling; and validate the tagged `from` form like the plain-string form. * BridgeJS: split snippet and external module import origins Use `from: .snippet("/my-file.js")` for a JavaScript file shipped with the Swift target and `from: .module("node:path")` for an external module, so each keeps its own validation and each mistaken form points at the other. The skeleton encoding is unchanged. * BridgeJS: tag both snippet and module origins in the skeleton Encode `.snippet` as `{"kind":"snippet","path":...}` alongside the existing tagged module form, so the JSON mirrors the Swift cases and a snippet path can no longer encode into a shape that fails to decode. --- .../BridgeJSCore/SwiftToSkeleton.swift | 229 +++++++++++-- .../Sources/BridgeJSLink/BridgeJSLink.swift | 53 +-- .../ImportedJSModuleRegistry.swift | 221 ++++++++++-- .../BridgeJSSkeleton/BridgeJSSkeleton.swift | 97 +++++- .../BridgeJSCodegenTests.swift | 87 ++++- .../BridgeJSToolTests/BridgeJSLinkTests.swift | 19 +- .../BridgeJSToolTests/DiagnosticsTests.swift | 162 ++++++++- .../ImportedJSModuleRegistryTests.swift | 222 ++++++++++++ .../MacroSwift/JSImportBareModule.swift | 22 ++ .../JSImportBareModuleFallback.swift | 12 + .../Inputs/MacroSwift/JSImportModule.swift | 8 +- .../JSImportBareModule.json | 232 +++++++++++++ .../JSImportBareModule.swift | 192 +++++++++++ .../JSImportBareModuleFallback.json | 95 ++++++ .../JSImportBareModuleFallback.swift | 66 ++++ .../BridgeJSCodegenTests/JSImportModule.json | 20 +- .../BridgeJSLinkTests/JSImportBareModule.d.ts | 21 ++ .../BridgeJSLinkTests/JSImportBareModule.js | 315 ++++++++++++++++++ .../JSImportBareModuleFallback.d.ts | 17 + .../JSImportBareModuleFallback.js | 259 ++++++++++++++ .../BridgeJSLinkTests/JSImportModule.js | 14 +- Plugins/PackageToJS/Sources/PackageToJS.swift | 5 +- .../Tests/PackagingPlannerTests.swift | 163 ++++++++- .../Importing-JavaScript-into-Swift.md | 2 +- .../Importing-JS-Class.md | 14 +- .../Importing-JS-Function.md | 14 +- .../Importing-JS-Variable.md | 14 +- .../Articles/BridgeJS/Unsupported-Features.md | 21 +- Sources/JavaScriptKit/Macros.swift | 58 +++- .../Generated/BridgeJS.swift | 113 +++++++ .../Generated/JavaScript/BridgeJS.json | 158 ++++++++- .../JSImportBareModuleTests.swift | 40 +++ .../JSImportModuleTests.swift | 10 +- .../Modules/DefaultExport.mjs | 6 + 34 files changed, 2817 insertions(+), 164 deletions(-) create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/ImportedJSModuleRegistryTests.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSImportBareModule.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSImportBareModuleFallback.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportBareModule.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportBareModule.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportBareModuleFallback.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportBareModuleFallback.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModule.d.ts create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModule.js create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModuleFallback.d.ts create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModuleFallback.js create mode 100644 Tests/BridgeJSRuntimeTests/JSImportBareModuleTests.swift create mode 100644 Tests/BridgeJSRuntimeTests/Modules/DefaultExport.mjs diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index 2d2a3ab6f..d327de307 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -98,8 +98,12 @@ public final class SwiftToSkeleton { importCollector.importedFunctions.compactMap(\.from) + importCollector.importedTypes.compactMap(\.from) + importCollector.importedGlobalGetters.compactMap(\.from) - let modulePaths = Set(importOrigins.compactMap(\.modulePath)) - for path in modulePaths.sorted() { + // Only snippet paths are validated here. Bare module specifiers are resolved + // by the JavaScript host (a bundler, an import map, or Node's `node_modules` + // lookup), so there is nothing we can check without rejecting setups that + // legitimately work. + let snippetPaths = Set(importOrigins.compactMap(\.snippetPath)) + for path in snippetPaths.sorted() { if validatedJavaScriptModulePaths.contains(path) { continue } @@ -108,8 +112,8 @@ public final class SwiftToSkeleton { importCollector.errors.append( DiagnosticError( node: pathNode, - message: "JavaScript module paths must start with '/' to indicate the Swift target root: " - + "'\(path)'." + message: "JavaScript snippet paths must start with '/' to indicate the Swift target root: " + + "'\(path)'. For an external module, use 'from: .module(\"\(path)\")' instead." ) ) continue @@ -118,7 +122,7 @@ public final class SwiftToSkeleton { importCollector.errors.append( DiagnosticError( node: pathNode, - message: "JavaScript module paths must not contain '..': '\(path)'." + message: "JavaScript snippet paths must not contain '..': '\(path)'." ) ) continue @@ -128,7 +132,7 @@ public final class SwiftToSkeleton { importCollector.errors.append( DiagnosticError( node: pathNode, - message: "JavaScript modules must use a '.js' or '.mjs' extension: '\(path)'." + message: "JavaScript snippets must use a '.js' or '.mjs' extension: '\(path)'." ) ) continue @@ -137,7 +141,7 @@ public final class SwiftToSkeleton { importCollector.errors.append( DiagnosticError( node: pathNode, - message: "JavaScript module file was not found at '\(path)'." + message: "JavaScript snippet file was not found at '\(path)'." ) ) continue @@ -2548,20 +2552,124 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { } } - /// Extracts the `jsName` argument value from an attribute, if present. - static func extractJSName(from attribute: AttributeSyntax) -> String? { - guard let arguments = attribute.arguments?.as(LabeledExprListSyntax.self) else { + } + + /// The result of reading a `jsName:` argument. + struct ExtractedJSName { + /// The JavaScript member name to look up. + /// + /// `.default` normalizes to `"default"`: in ECMAScript a module's default + /// export *is* its `default` named export, so no separate representation + /// is needed downstream. + let memberName: String + /// True when the source spelled `.default` rather than a string literal. + let isDefaultExportSpelling: Bool + } + + /// Extracts the `jsName` argument value from an attribute, if present. + private func extractJSName(from attribute: AttributeSyntax) -> ExtractedJSName? { + guard let arguments = attribute.arguments?.as(LabeledExprListSyntax.self), + let argument = arguments.first(where: { $0.label?.text == "jsName" }) + else { + return nil + } + + if let stringLiteral = argument.expression.as(StringLiteralExprSyntax.self), + let value = stringLiteral.representedLiteralValue + { + return ExtractedJSName(memberName: value, isDefaultExportSpelling: false) + } + + // An explicit `jsName: nil` means the same as omitting the argument. + if argument.expression.is(NilLiteralExprSyntax.self) { + return nil + } + + // Accept the explicit `.name("...")` spelling of a plain member name. + if let call = argument.expression.as(FunctionCallExprSyntax.self), + call.calledExpression.trimmedDescription.split(separator: ".").last == "name" + { + guard call.arguments.count == 1, + let literal = call.arguments.first?.expression.as(StringLiteralExprSyntax.self), + let value = literal.representedLiteralValue + else { + errors.append( + DiagnosticError( + node: call.arguments.first?.expression ?? argument.expression, + message: "jsName must be a string literal or '.default'." + ) + ) return nil } - for argument in arguments { - if argument.label?.text == "jsName", - let stringLiteral = argument.expression.as(StringLiteralExprSyntax.self), - let segment = stringLiteral.segments.first?.as(StringSegmentSyntax.self) - { - return segment.content.text - } - } - return nil + return ExtractedJSName(memberName: value, isDefaultExportSpelling: false) + } + + // Accept `.default`, `JSName.default`, and the backticked spellings. + let description = argument.expression.trimmedDescription + let caseName = description.split(separator: ".").last.map(String.init) ?? description + if caseName == "default" || caseName == "`default`" { + return ExtractedJSName(memberName: "default", isDefaultExportSpelling: true) + } + + errors.append( + DiagnosticError( + node: argument.expression, + message: "jsName must be a string literal or '.default'." + ) + ) + return nil + } + + /// Validates that a `jsName: .default` spelling appears somewhere it can mean something. + /// + /// `.default` names the default export of an ECMAScript module, so it only makes + /// sense on a top-level declaration that has a `from: .module(...)` origin. + private func validateDefaultExportUsage( + _ extracted: ExtractedJSName?, + from: JSImportFrom?, + node: some SyntaxProtocol, + isSetter: Bool = false + ) { + guard let extracted, extracted.isDefaultExportSpelling else { return } + + if isSetter { + errors.append( + DiagnosticError( + node: node, + message: "'jsName: .default' is not supported on @JSSetter; " + + "ECMAScript module bindings are read-only." + ) + ) + return + } + if case .jsClassBody = state { + errors.append( + DiagnosticError( + node: node, + message: "'jsName: .default' is not supported on a class member; " + + "members have no module origin. Did you mean jsName: \"default\"?" + ) + ) + return + } + switch from { + case .module, .snippet: + return + case .global: + errors.append( + DiagnosticError( + node: node, + message: "'jsName: .default' requires 'from: .module(...)' or 'from: .snippet(...)'; " + + "globalThis has no default export." + ) + ) + case nil: + errors.append( + DiagnosticError( + node: node, + message: "'jsName: .default' requires 'from: .module(...)' or 'from: .snippet(...)'." + ) + ) } } @@ -2573,8 +2681,10 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { } if let call = argument.expression.as(FunctionCallExprSyntax.self), - call.calledExpression.trimmedDescription.split(separator: ".").last == "module" + let caseName = call.calledExpression.trimmedDescription.split(separator: ".").last, + caseName == "module" || caseName == "snippet" { + let isSnippet = caseName == "snippet" guard call.arguments.count == 1, let pathExpression = call.arguments.first?.expression, let literal = pathExpression.as(StringLiteralExprSyntax.self), @@ -2583,13 +2693,53 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { errors.append( DiagnosticError( node: call.arguments.first?.expression ?? argument.expression, - message: "JavaScript module path must be a string literal." + message: isSnippet + ? "JavaScript snippet path must be a string literal." + : "JavaScript module specifier must be a string literal." + ) + ) + return nil + } + guard !path.isEmpty else { + errors.append( + DiagnosticError( + node: literal, + message: isSnippet + ? "JavaScript snippet path must not be empty." + : "JavaScript module specifier must not be empty." ) ) return nil } - if importedModulePathNodes[path] == nil { - importedModulePathNodes[path] = Syntax(literal) + if isSnippet { + // Full validation of the path happens in `finalize()`, where the file + // can also be checked for existence. + if importedModulePathNodes[path] == nil { + importedModulePathNodes[path] = Syntax(literal) + } + return .snippet(path) + } + guard !path.hasPrefix("/") else { + errors.append( + DiagnosticError( + node: literal, + message: "'\(path)' looks like a file in this target. " + + "Use 'from: .snippet(\"\(path)\")' for a JavaScript file you ship with the target, " + + "and 'from: .module(...)' for an external module (e.g. 'node:path')." + ) + ) + return nil + } + guard !path.hasPrefix("./"), !path.hasPrefix("../"), path != ".", path != ".." else { + errors.append( + DiagnosticError( + node: literal, + message: "Relative JavaScript module specifiers are not supported: '\(path)'. " + + "Use 'from: .snippet(\"/path/to/file.js\")' for a file in this target, " + + "or a bare specifier for an external module (e.g. 'node:path')." + ) + ) + return nil } return .module(path) } @@ -2645,7 +2795,9 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { return nil } - let jsName = AttributeChecker.extractJSName(from: jsSetter) + let extractedJSName = extractJSName(from: jsSetter) + validateDefaultExportUsage(extractedJSName, from: nil, node: node, isSetter: true) + let jsName = extractedJSName?.memberName let parameters = node.signature.parameterClause.parameters guard let firstParam = parameters.first else { @@ -2779,10 +2931,16 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { override func visit(_ node: StructDeclSyntax) -> SyntaxVisitorContinueKind { if AttributeChecker.hasJSClassAttribute(node.attributes) { let attribute = AttributeChecker.firstJSClassAttribute(node.attributes) - let jsName = attribute.flatMap(AttributeChecker.extractJSName) + let extractedJSName = attribute.flatMap { extractJSName(from: $0) } let from = attribute.flatMap { extractJSImportFrom(from: $0) } + validateDefaultExportUsage(extractedJSName, from: from, node: node) let accessLevel = Self.bridgeAccessLevel(from: node.modifiers) - enterJSClass(node.name.text, jsName: jsName, from: from, accessLevel: accessLevel) + enterJSClass( + node.name.text, + jsName: extractedJSName?.memberName, + from: from, + accessLevel: accessLevel + ) } return .visitChildren } @@ -2796,10 +2954,16 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { override func visit(_ node: ClassDeclSyntax) -> SyntaxVisitorContinueKind { if AttributeChecker.hasJSClassAttribute(node.attributes) { let attribute = AttributeChecker.firstJSClassAttribute(node.attributes) - let jsName = attribute.flatMap(AttributeChecker.extractJSName) + let extractedJSName = attribute.flatMap { extractJSName(from: $0) } let from = attribute.flatMap { extractJSImportFrom(from: $0) } + validateDefaultExportUsage(extractedJSName, from: from, node: node) let accessLevel = Self.bridgeAccessLevel(from: node.modifiers) - enterJSClass(node.name.text, jsName: jsName, from: from, accessLevel: accessLevel) + enterJSClass( + node.name.text, + jsName: extractedJSName?.memberName, + from: from, + accessLevel: accessLevel + ) } return .visitChildren } @@ -2990,8 +3154,10 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { } let baseName = SwiftToSkeleton.normalizeIdentifier(node.name.text) - let jsName = AttributeChecker.extractJSName(from: jsFunction) + let extractedJSName = extractJSName(from: jsFunction) let from = extractJSImportFrom(from: jsFunction) + validateDefaultExportUsage(extractedJSName, from: from, node: node) + let jsName = extractedJSName?.memberName let name = baseName let parameters = parseParameters(from: node.signature.parameterClause) @@ -3043,12 +3209,13 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { return nil } let propertyName = SwiftToSkeleton.normalizeIdentifier(identifier.identifier.text) - let jsName = AttributeChecker.extractJSName(from: jsGetter) + let extractedJSName = extractJSName(from: jsGetter) let from = extractJSImportFrom(from: jsGetter) + validateDefaultExportUsage(extractedJSName, from: from, node: node) let accessLevel = Self.bridgeAccessLevel(from: node.modifiers) return ImportedGetterSkeleton( name: propertyName, - jsName: jsName, + jsName: extractedJSName?.memberName, from: from, type: propertyType, documentation: nil, diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index d8a1ac780..1b6300595 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -2515,7 +2515,13 @@ extension BridgeJSLink { } func callConstructor(jsName: String, swiftTypeName: String, fromObjectExpr: String) throws { - let ctorExpr = Self.propertyAccessExpr(objectExpr: fromObjectExpr, propertyName: jsName) + try callConstructor( + ctorExpr: Self.propertyAccessExpr(objectExpr: fromObjectExpr, propertyName: jsName), + swiftTypeName: swiftTypeName + ) + } + + func callConstructor(ctorExpr: String, swiftTypeName: String) throws { let call = "new \(ctorExpr)(\(parameterForwardings.joined(separator: ", ")))" let type: BridgeType = .jsObject(swiftTypeName) let loweringFragment = try IntrinsicJSFragment.lowerReturn(type: type, context: context) @@ -2580,12 +2586,18 @@ extension BridgeJSLink { } func getImportProperty(name: String, fromObjectExpr: String, returnType: BridgeType) throws { + try getImportProperty( + accessExpr: Self.propertyAccessExpr(objectExpr: fromObjectExpr, propertyName: name), + returnType: returnType + ) + } + + func getImportProperty(accessExpr expr: String, returnType: BridgeType) throws { if returnType == .void { throw BridgeJSLinkError(message: "Void is not supported for imported JS properties") } let loweringFragment = try IntrinsicJSFragment.lowerReturn(type: returnType, context: context) - let expr = Self.propertyAccessExpr(objectExpr: fromObjectExpr, propertyName: name) let returnExpr: String? if loweringFragment.parameters.count == 0 { @@ -2623,8 +2635,7 @@ extension BridgeJSLink { } static func propertyAccessExpr(objectExpr: String, propertyName: String) -> String { - if propertyName.range(of: #"^[$A-Z_][0-9A-Z_$]*$"#, options: [.regularExpression, .caseInsensitive]) != nil - { + if ImportedJSModuleRegistry.isValidJSIdentifier(propertyName) { return "\(objectExpr).\(propertyName)" } let escapedName = BridgeJSLink.escapeForJavaScriptStringLiteral(propertyName) @@ -3469,12 +3480,13 @@ extension BridgeJSLink { try thunkBuilder.liftParameter(param: param) } let jsName = function.jsName ?? function.name - let importRootExpr = try importedModuleRegistry.namespaceExpression( + let calleeExpr = try importedModuleRegistry.memberExpression( swiftModuleName: importObjectBuilder.moduleName, - from: function.from + from: function.from, + memberName: jsName ) - try thunkBuilder.call(name: jsName, fromObjectExpr: importRootExpr) + try thunkBuilder.call(calleeExpr: calleeExpr) let funcLines = thunkBuilder.renderFunction(name: function.abiName(context: nil)) if function.from == nil { importObjectBuilder.appendDts( @@ -3496,13 +3508,13 @@ extension BridgeJSLink { intrinsicRegistry: intrinsicRegistry ) let jsName = getter.jsName ?? getter.name - let importRootExpr = try importedModuleRegistry.namespaceExpression( + let accessExpr = try importedModuleRegistry.memberExpression( swiftModuleName: importObjectBuilder.moduleName, - from: getter.from + from: getter.from, + memberName: jsName ) try thunkBuilder.getImportProperty( - name: jsName, - fromObjectExpr: importRootExpr, + accessExpr: accessExpr, returnType: getter.type ) let abiName = getter.abiName(context: nil) @@ -3602,14 +3614,14 @@ extension BridgeJSLink { for param in constructor.parameters { try thunkBuilder.liftParameter(param: param) } - let importRootExpr = try importedModuleRegistry.namespaceExpression( + let ctorExpr = try importedModuleRegistry.memberExpression( swiftModuleName: importObjectBuilder.moduleName, - from: type.from + from: type.from, + memberName: type.jsName ?? type.name ) try thunkBuilder.callConstructor( - jsName: type.jsName ?? type.name, - swiftTypeName: type.name, - fromObjectExpr: importRootExpr + ctorExpr: ctorExpr, + swiftTypeName: type.name ) let abiName = constructor.abiName(context: type) let funcLines = thunkBuilder.renderFunction(name: abiName) @@ -3661,13 +3673,10 @@ extension BridgeJSLink { for param in method.parameters { try thunkBuilder.liftParameter(param: param) } - let importRootExpr = try importedModuleRegistry.namespaceExpression( + let constructorExpr = try importedModuleRegistry.memberExpression( swiftModuleName: swiftModuleName, - from: context.from - ) - let constructorExpr = ImportedThunkBuilder.propertyAccessExpr( - objectExpr: importRootExpr, - propertyName: context.jsName ?? context.name + from: context.from, + memberName: context.jsName ?? context.name ) try thunkBuilder.callStaticMethod(on: constructorExpr, name: method.jsName ?? method.name) diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/ImportedJSModuleRegistry.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/ImportedJSModuleRegistry.swift index 2c5716030..96efcd1d4 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/ImportedJSModuleRegistry.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/ImportedJSModuleRegistry.swift @@ -2,8 +2,24 @@ import BridgeJSSkeleton #endif +import Foundation + final class ImportedJSModuleRegistry { - struct Reference: Hashable { + /// A JavaScript module that imported declarations are read from. + /// + /// A `snippet` reference is a file inside a Swift target, which packaging copies + /// into the generated output. A `module` reference is a bare specifier resolved by + /// the JavaScript host (a bundler, an import map, or Node's `node_modules` lookup), + /// so it has no file and nothing to copy. Because a bare specifier names the same + /// module no matter which Swift module mentions it — and ECMAScript caches module + /// instances — it is keyed by specifier alone and shared across targets. + enum Reference: Hashable { + case snippet(swiftModuleName: String, path: String) + case module(specifier: String) + } + + /// A JavaScript file shipped in a Swift target that packaging must copy into the output. + struct SnippetFile: Hashable { let swiftModuleName: String let path: String @@ -12,56 +28,211 @@ final class ImportedJSModuleRegistry { } } - private var aliases: [Reference: String] = [:] + private struct Binding { + let index: Int + /// Member names looked up on this module, sorted for stable output. + let members: [String] + /// Whether every member name is a valid JavaScript identifier, and so can be + /// reached with a named import instead of a namespace property lookup. + let usesNamedImports: Bool + } + + private var bindings: [Reference: Binding] = [:] private(set) var references: [Reference] = [] + /// The snippet files packaging must copy, in deterministic order. + var snippetFiles: [SnippetFile] { + references.compactMap { reference in + guard case .snippet(let swiftModuleName, let path) = reference else { return nil } + return SnippetFile(swiftModuleName: swiftModuleName, path: path) + } + } + func configure(skeletons: [BridgeJSSkeleton]) { - aliases.removeAll(keepingCapacity: true) + bindings.removeAll(keepingCapacity: true) references = Self.collectReferences(skeletons: skeletons) + + var membersByReference: [Reference: Set] = [:] + for skeleton in skeletons { + Self.forEachMemberLookup(skeleton: skeleton) { reference, memberName in + membersByReference[reference, default: []].insert(memberName) + } + } + for (index, reference) in references.enumerated() { - aliases[reference] = "__bjs_imported_module_\(index)" + let members = (membersByReference[reference] ?? []).sorted() + // A reference with no member lookups keeps the namespace form: a named import + // is a hard link-time requirement, so importing a name nothing references + // would fail the whole module load if the module does not export it. + bindings[reference] = Binding( + index: index, + members: members, + usesNamedImports: !members.isEmpty && members.allSatisfy(Self.isValidJSIdentifier) + ) } } static func collectReferences(skeletons: [BridgeJSSkeleton]) -> [Reference] { var references = Set() for skeleton in skeletons { - for file in skeleton.imported?.children ?? [] { - let origins = - file.functions.compactMap(\.from) - + file.globalGetters.compactMap(\.from) - + file.types.compactMap(\.from) - for case .module(let path) in origins { - references.insert(Reference(swiftModuleName: skeleton.moduleName, path: path)) - } + forEachOrigin(skeleton: skeleton) { reference in + references.insert(reference) } } - return references.sorted { - ($0.swiftModuleName, $0.path) < ($1.swiftModuleName, $1.path) + return references.sorted(by: isOrderedBefore) + } + + static func collectSnippetFiles(skeletons: [BridgeJSSkeleton]) -> [SnippetFile] { + collectReferences(skeletons: skeletons).compactMap { reference in + guard case .snippet(let swiftModuleName, let path) = reference else { return nil } + return SnippetFile(swiftModuleName: swiftModuleName, path: path) } } - func namespaceExpression(swiftModuleName: String, from: JSImportFrom?) throws -> String { + /// Visits every module origin mentioned by the skeleton, whether or not code + /// generation looks a member up on it. + /// + /// This is what decides which modules are imported at all, and for snippets which + /// files packaging copies. It stays broader than `forEachMemberLookup` so + /// that a module mentioned only by a wrapper-only `@JSClass` is still imported, + /// preserving its side effects. + private static func forEachOrigin( + skeleton: BridgeJSSkeleton, + _ body: (Reference) -> Void + ) { + func visit(from: JSImportFrom?) { + guard let reference = Self.reference(swiftModuleName: skeleton.moduleName, from: from) else { return } + body(reference) + } + for file in skeleton.imported?.children ?? [] { + for function in file.functions { visit(from: function.from) } + for getter in file.globalGetters { visit(from: getter.from) } + for type in file.types { visit(from: type.from) } + } + } + + /// Visits every module member lookup that code generation will emit. + /// + /// The member name taken here must match what the corresponding emitter in + /// `BridgeJSLink` looks up, and must not include names it never emits: a named + /// import is a hard link-time requirement, so recording a member that no + /// generated code references would make the module fail to load whenever the + /// module does not happen to export that name. + /// + /// A class contributes a single binding that serves both its constructor and its + /// static methods, and only when it has one of those. Instance methods, getters, + /// and setters contribute nothing because they go through an already-constructed + /// instance, so a wrapper-only `@JSClass` needs no export from the module at all. + private static func forEachMemberLookup( + skeleton: BridgeJSSkeleton, + _ body: (Reference, String) -> Void + ) { + func visit(from: JSImportFrom?, memberName: String) { + guard let reference = Self.reference(swiftModuleName: skeleton.moduleName, from: from) else { return } + body(reference, memberName) + } + for file in skeleton.imported?.children ?? [] { + for function in file.functions { + visit(from: function.from, memberName: function.jsName ?? function.name) + } + for getter in file.globalGetters { + visit(from: getter.from, memberName: getter.jsName ?? getter.name) + } + for type in file.types { + guard type.constructor != nil || !type.staticMethods.isEmpty else { continue } + visit(from: type.from, memberName: type.jsName ?? type.name) + } + } + } + + private static func reference(swiftModuleName: String, from: JSImportFrom?) -> Reference? { + switch from { + case .snippet(let path): + return .snippet(swiftModuleName: swiftModuleName, path: path) + case .module(let specifier): + return .module(specifier: specifier) + case .global, nil: + return nil + } + } + + private static func isOrderedBefore(_ lhs: Reference, _ rhs: Reference) -> Bool { + switch (lhs, rhs) { + case (.snippet(let lhsModule, let lhsPath), .snippet(let rhsModule, let rhsPath)): + return (lhsModule, lhsPath) < (rhsModule, rhsPath) + case (.module(let lhsSpecifier), .module(let rhsSpecifier)): + return lhsSpecifier < rhsSpecifier + case (.snippet, .module): + return true + case (.module, .snippet): + return false + } + } + + /// Whether `name` can appear as a bare identifier in generated JavaScript. + static func isValidJSIdentifier(_ name: String) -> Bool { + name.range(of: #"^[$A-Z_][0-9A-Z_$]*$"#, options: [.regularExpression, .caseInsensitive]) != nil + } + + /// Returns the JavaScript expression that evaluates to `memberName` of the given origin. + func memberExpression( + swiftModuleName: String, + from: JSImportFrom?, + memberName: String + ) throws -> String { switch from { case nil: - return "imports" + return BridgeJSLink.ImportedThunkBuilder.propertyAccessExpr(objectExpr: "imports", propertyName: memberName) case .global: - return "globalThis" - case .module(let path): - let reference = Reference(swiftModuleName: swiftModuleName, path: path) - guard let alias = aliases[reference] else { + return BridgeJSLink.ImportedThunkBuilder.propertyAccessExpr( + objectExpr: "globalThis", + propertyName: memberName + ) + case .snippet, .module: + guard let reference = Self.reference(swiftModuleName: swiftModuleName, from: from), + let binding = bindings[reference] + else { throw BridgeJSLinkError( - message: "Missing JavaScript module \(swiftModuleName)\(path)" + message: + "Missing JavaScript module \(swiftModuleName)\(from?.snippetPath ?? from?.moduleSpecifier ?? "")" ) } - return alias + if binding.usesNamedImports { + return Self.namedImportBinding(index: binding.index, memberName: memberName) + } + return BridgeJSLink.ImportedThunkBuilder.propertyAccessExpr( + objectExpr: Self.namespaceAlias(index: binding.index), + propertyName: memberName + ) } } + private static func namespaceAlias(index: Int) -> String { + "__bjs_imported_module_\(index)" + } + + private static func namedImportBinding(index: Int, memberName: String) -> String { + "__bjs_import_\(index)_\(memberName)" + } + var importLines: [String] { - references.enumerated().map { index, reference in - let path = BridgeJSLink.escapeForJavaScriptStringLiteral(reference.relativeOutputPath) - return "import * as __bjs_imported_module_\(index) from \"./\(path)\";" + references.compactMap { reference in + guard let binding = bindings[reference] else { return nil } + let specifier: String + switch reference { + case .snippet(let swiftModuleName, let path): + let output = SnippetFile(swiftModuleName: swiftModuleName, path: path).relativeOutputPath + specifier = "./" + BridgeJSLink.escapeForJavaScriptStringLiteral(output) + case .module(let moduleSpecifier): + specifier = BridgeJSLink.escapeForJavaScriptStringLiteral(moduleSpecifier) + } + guard binding.usesNamedImports else { + return "import * as \(Self.namespaceAlias(index: binding.index)) from \"\(specifier)\";" + } + let clauses = binding.members.map { + "\($0) as \(Self.namedImportBinding(index: binding.index, memberName: $0))" + } + return "import { \(clauses.joined(separator: ", ")) } from \"\(specifier)\";" } } } diff --git a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift index c70ccdd8b..5507f39c2 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift @@ -1126,35 +1126,108 @@ private struct AsyncClosureReturnTypeCollector: BridgeSkeletonVisitor { /// Controls where BridgeJS reads imported JS values from. /// /// - `global`: Read from `globalThis`. -/// - `module`: Read from a target-local ECMAScript module. +/// - `snippet`: Read from a `/`-rooted JavaScript file inside the Swift target, +/// which packaging copies into the generated output. +/// - `module`: Read from an external ECMAScript module named by a bare specifier +/// that the JavaScript host resolves (e.g. `node:path`, `lodash/fp`). +/// +/// `.global` encodes as the string `"global"`; the other two encode as tagged +/// objects that name their kind, so the JSON mirrors the Swift cases and is +/// readable without knowing that a `/`-prefixed string means one thing and any +/// other string means another. A plain string is never used for a specifier, +/// which also avoids colliding with the `"global"` sentinel — `global` is itself +/// a valid npm package name. public enum JSImportFrom: Codable, Equatable, Sendable { case global + case snippet(String) case module(String) + private enum CodingKeys: String, CodingKey { + case kind, path, specifier + } + public init(from decoder: any Decoder) throws { - let container = try decoder.singleValueContainer() - let value = try container.decode(String.self) - if value == "global" { + if let container = try? decoder.singleValueContainer(), let value = try? container.decode(String.self) { + guard value == "global" else { + throw DecodingError.dataCorruptedError( + in: container, + debugDescription: "Unknown import origin '\(value)'. Expected \"global\"." + ) + } self = .global - } else if value.hasPrefix("/") && !value.split(separator: "/").contains("..") { - self = .module(value) - } else { + return + } + let container = try decoder.container(keyedBy: CodingKeys.self) + let kind = try container.decode(String.self, forKey: .kind) + switch kind { + case "snippet": + let path = try container.decode(String.self, forKey: .path) + // A snippet names a file we resolve inside the Swift target, so it must be + // rooted there and must not traverse out of it. + guard path.hasPrefix("/"), !path.split(separator: "/").contains("..") else { + throw DecodingError.dataCorruptedError( + forKey: .path, + in: container, + debugDescription: "Snippet path '\(path)' must start with '/' and must not contain '..'." + ) + } + self = .snippet(path) + case "module": + let specifier = try container.decode(String.self, forKey: .specifier) + // A bare specifier is resolved by the JavaScript host, so almost anything is + // legal, but the shapes that can never work are rejected here as well as at + // parse time: an empty specifier, a relative one, and a rooted path. + guard !specifier.isEmpty else { + throw DecodingError.dataCorruptedError( + forKey: .specifier, + in: container, + debugDescription: "Module specifier must not be empty." + ) + } + guard !specifier.hasPrefix("."), !specifier.hasPrefix("/") else { + throw DecodingError.dataCorruptedError( + forKey: .specifier, + in: container, + debugDescription: "Module specifier '\(specifier)' must not be a path. Use a snippet instead." + ) + } + self = .module(specifier) + default: throw DecodingError.dataCorruptedError( + forKey: .kind, in: container, - debugDescription: "Unknown import origin '\(value)'. Expected \"global\" or a rooted module path." + debugDescription: "Unknown import origin kind '\(kind)'. Expected \"snippet\" or \"module\"." ) } } public func encode(to encoder: any Encoder) throws { - var container = encoder.singleValueContainer() - try container.encode(modulePath ?? "global") + switch self { + case .global: + var container = encoder.singleValueContainer() + try container.encode("global") + case .snippet(let path): + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode("snippet", forKey: .kind) + try container.encode(path, forKey: .path) + case .module(let specifier): + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode("module", forKey: .kind) + try container.encode(specifier, forKey: .specifier) + } } - public var modulePath: String? { - guard case .module(let path) = self else { return nil } + /// The path of a target-local JavaScript file, rooted at the Swift target directory. + public var snippetPath: String? { + guard case .snippet(let path) = self else { return nil } return path } + + /// The bare specifier of an external ECMAScript module, resolved by the JavaScript host. + public var moduleSpecifier: String? { + guard case .module(let specifier) = self else { return nil } + return specifier + } } public struct ImportedFunctionSkeleton: Codable { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift index 263d796a6..60b2fd485 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift @@ -18,10 +18,10 @@ import Testing func javaScriptModuleReferencesAreStoredWithoutSourceContents() throws { let modulePath = "/Modules/math.mjs" let swiftSource = """ - @JSFunction(from: .module("/Modules/math.mjs")) + @JSFunction(from: .snippet("/Modules/math.mjs")) func add(_ lhs: Int, _ rhs: Int) throws(JSException) -> Int - @JSGetter(jsName: "version", from: .module("/Modules/math.mjs")) + @JSGetter(jsName: "version", from: .snippet("/Modules/math.mjs")) var moduleVersion: String """ var validationCount = 0 @@ -41,7 +41,7 @@ import Testing let imported = try #require(skeleton.imported) #expect(validationCount == 1) - #expect(imported.children.flatMap(\.functions).first?.from == .module(modulePath)) + #expect(imported.children.flatMap(\.functions).first?.from == .snippet(modulePath)) #expect(!encoded.contains(#""modules""#)) } @@ -50,6 +50,68 @@ import Testing #expect(throws: DecodingError.self) { try JSONDecoder().decode(JSImportFrom.self, from: Data(#""module.js""#.utf8)) } + // A bare path string is no longer an origin at all; snippets are tagged. + #expect(throws: DecodingError.self) { + try JSONDecoder().decode(JSImportFrom.self, from: Data(#""/Modules/utils.mjs""#.utf8)) + } + } + + @Test(arguments: [ + JSImportFrom.global, + JSImportFrom.snippet("/Modules/utils.mjs"), + JSImportFrom.module("node:path"), + JSImportFrom.module("@scope/package/sub"), + // A package literally named "global" is why specifiers are encoded as tagged + // objects rather than plain strings: a plain string would be indistinguishable + // from the `.global` sentinel. + JSImportFrom.module("global"), + JSImportFrom.module("#internal"), + JSImportFrom.module("https://esm.sh/lodash@4"), + ]) + func jsImportFromRoundTrips(origin: JSImportFrom) throws { + let encoded = try JSONEncoder().encode(origin) + #expect(try JSONDecoder().decode(JSImportFrom.self, from: encoded) == origin) + } + + @Test + func originsEncodeToTheirDocumentedShapes() throws { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + #expect(String(data: try encoder.encode(JSImportFrom.global), encoding: .utf8) == #""global""#) + #expect( + String(data: try encoder.encode(JSImportFrom.snippet("/a.js")), encoding: .utf8) + == #"{"kind":"snippet","path":"\/a.js"}"# + ) + #expect( + String(data: try encoder.encode(JSImportFrom.module("node:path")), encoding: .utf8) + == #"{"kind":"module","specifier":"node:path"}"# + ) + } + + @Test + func unknownJSImportFromKindFailsToDecode() { + #expect(throws: DecodingError.self) { + try JSONDecoder().decode( + JSImportFrom.self, + from: Data(#"{"kind": "somethingElse", "specifier": "x"}"#.utf8) + ) + } + } + + /// The keyed form must reject what the string form rejects, so a specifier cannot reach + /// code generation through the tagged object that the plain-string path would refuse. + @Test(arguments: [ + #"{"kind": "module", "specifier": ""}"#, + #"{"kind": "module", "specifier": "./relative.mjs"}"#, + #"{"kind": "module", "specifier": "/../../escape.mjs"}"#, + #"{"kind": "snippet", "path": "node:path"}"#, + #"{"kind": "snippet", "path": "/../../escape.mjs"}"#, + #"{"kind": "snippet", "path": "relative.mjs"}"#, + ]) + func invalidKeyedJSImportFromFailsToDecode(json: String) { + #expect(throws: DecodingError.self) { + try JSONDecoder().decode(JSImportFrom.self, from: Data(json.utf8)) + } } private func snapshotCodegen( @@ -105,6 +167,17 @@ import Testing ) } + /// Target-local JavaScript module files that each input pretends to have on disk. + static let existingModulePaths: [String: Set] = [ + "JSImportModule.swift": [ + "/Modules/JSImportModule.mjs", + "/Modules/ModuleCounter.mjs", + ], + "JSImportBareModule.swift": [ + "/Modules/DefaultExport.mjs" + ], + ] + static func collectInputs() -> [String] { let fileManager = FileManager.default let inputs = try! fileManager.contentsOfDirectory(atPath: Self.inputsDirectory.path) @@ -116,13 +189,7 @@ import Testing let url = Self.inputsDirectory.appendingPathComponent(input) let name = url.deletingPathExtension().lastPathComponent let sourceFile = Parser.parse(source: try String(contentsOf: url, encoding: .utf8)) - let modulePaths: Set = - input == "JSImportModule.swift" - ? [ - "/Modules/JSImportModule.mjs", - "/Modules/ModuleCounter.mjs", - ] - : [] + let modulePaths = Self.existingModulePaths[input] ?? [] let swiftAPI = SwiftToSkeleton( progress: .silent, moduleName: "TestModule", diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSLinkTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSLinkTests.swift index 0445fe5e1..642debedc 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSLinkTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSLinkTests.swift @@ -37,6 +37,17 @@ import Testing "Inputs" ).appendingPathComponent("MacroSwift") + /// Target-local JavaScript module files that each input pretends to have on disk. + static let existingModulePaths: [String: Set] = [ + "JSImportModule.swift": [ + "/Modules/JSImportModule.mjs", + "/Modules/ModuleCounter.mjs", + ], + "JSImportBareModule.swift": [ + "/Modules/DefaultExport.mjs" + ], + ] + static func collectInputs(extension: String) -> [String] { let fileManager = FileManager.default let inputs = try! fileManager.contentsOfDirectory(atPath: Self.inputsDirectory.path) @@ -49,13 +60,7 @@ import Testing let name = url.deletingPathExtension().lastPathComponent let sourceFile = Parser.parse(source: try String(contentsOf: url, encoding: .utf8)) - let modulePaths: Set = - input == "JSImportModule.swift" - ? [ - "/Modules/JSImportModule.mjs", - "/Modules/ModuleCounter.mjs", - ] - : [] + let modulePaths = Self.existingModulePaths[input] ?? [] let importSwift = SwiftToSkeleton( progress: .silent, moduleName: "TestModule", diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift index e8cf963e3..316d51b41 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift @@ -30,44 +30,180 @@ import Testing func missingJavaScriptModuleProducesDiagnostic() throws { let source = """ let unrelated = 0 - @JSFunction(from: .module("/missing.js")) func imported() throws(JSException) + @JSFunction(from: .snippet("/missing.js")) func imported() throws(JSException) """ let diagnostics = try #require(moduleDiagnostics(source: source)) - #expect(diagnostics.description.contains("JavaScript module file was not found at '/missing.js'")) - #expect(diagnostics.description.contains("test.swift:2:27:")) + #expect(diagnostics.description.contains("JavaScript snippet file was not found at '/missing.js'")) + #expect(diagnostics.description.contains("test.swift:2:28:")) } @Test - func javaScriptModulePathMustStartAtTargetRoot() throws { + func bareJavaScriptModuleSpecifierIsAccepted() throws { let source = """ let unrelated = 0 - @JSFunction(from: .module("missing.js")) func imported() throws(JSException) + @JSFunction(jsName: "basename", from: .module("node:path")) func imported() throws(JSException) + """ + #expect(moduleDiagnostics(source: source) == nil) + } + + @Test + func relativeJavaScriptModuleSpecifierIsRejected() throws { + let source = """ + let unrelated = 0 + @JSFunction(from: .module("./missing.js")) func imported() throws(JSException) """ let diagnostics = try #require(moduleDiagnostics(source: source)) - #expect(diagnostics.description.contains("JavaScript module paths must start with '/'")) + #expect(diagnostics.description.contains("Relative JavaScript module specifiers are not supported")) #expect(diagnostics.description.contains("test.swift:2:27:")) } + @Test + func emptyJavaScriptModuleSpecifierIsRejected() throws { + let source = """ + let unrelated = 0 + @JSFunction(from: .module("")) func imported() throws(JSException) + """ + let diagnostics = try #require(moduleDiagnostics(source: source)) + #expect(diagnostics.description.contains("JavaScript module specifier must not be empty.")) + } + + @Test + func defaultExportRequiresModuleOrigin() throws { + let source = """ + let unrelated = 0 + @JSFunction(jsName: .default) func imported() throws(JSException) + """ + let diagnostics = try #require(moduleDiagnostics(source: source)) + #expect( + diagnostics.description.contains( + "'jsName: .default' requires 'from: .module(...)' or 'from: .snippet(...)'." + ) + ) + } + + @Test + func defaultExportIsRejectedForGlobalOrigin() throws { + let source = """ + let unrelated = 0 + @JSFunction(jsName: .default, from: .global) func imported() throws(JSException) + """ + let diagnostics = try #require(moduleDiagnostics(source: source)) + #expect(diagnostics.description.contains("globalThis has no default export")) + } + + @Test + func defaultExportIsRejectedForSetter() throws { + let source = """ + @JSClass(from: .module("node:fs")) struct Wrapper { + @JSSetter(jsName: .default) func setValue(_ value: Int) throws(JSException) + } + """ + let diagnostics = try #require(moduleDiagnostics(source: source)) + #expect(diagnostics.description.contains("ECMAScript module bindings are read-only")) + } + + @Test + func defaultExportIsRejectedForClassMember() throws { + let source = """ + @JSClass(from: .module("node:fs")) struct Wrapper { + @JSFunction(jsName: .default) func value() throws(JSException) -> Int + } + """ + let diagnostics = try #require(moduleDiagnostics(source: source)) + #expect(diagnostics.description.contains("is not supported on a class member")) + } + + /// `jsName: nil` is valid Swift and means the same as omitting the argument. + @Test + func explicitNilJSNameIsAccepted() throws { + let source = """ + let unrelated = 0 + @JSFunction(jsName: nil, from: .global) func imported() throws(JSException) + """ + #expect(moduleDiagnostics(source: source) == nil) + } + + /// `JSName.name(_:)` is public and documented, so its explicit spelling must work. + @Test + func explicitNameCaseSpellingIsAccepted() throws { + let source = """ + let unrelated = 0 + @JSFunction(jsName: .name("basename"), from: .module("node:path")) func imported() throws(JSException) + """ + #expect(moduleDiagnostics(source: source) == nil) + } + + @Test + func jsNameMustBeStringLiteralOrDefault() throws { + let source = """ + let name = "basename" + @JSFunction(jsName: name, from: .module("node:path")) func imported() throws(JSException) + """ + let diagnostics = try #require(moduleDiagnostics(source: source)) + #expect(diagnostics.description.contains("jsName must be a string literal or '.default'.")) + } + + /// A rooted path in `.module(...)` is the most likely mistake now that the two cases + /// are separate, so it must point at `.snippet(...)` rather than being passed to the + /// JavaScript resolver where it would fail much later. + @Test + func rootedPathInModuleSuggestsSnippet() throws { + let source = """ + let unrelated = 0 + @JSFunction(from: .module("/Modules/utils.mjs")) func imported() throws(JSException) + """ + let diagnostics = try #require(moduleDiagnostics(source: source)) + #expect(diagnostics.description.contains("looks like a file in this target")) + #expect(diagnostics.description.contains(#"from: .snippet("/Modules/utils.mjs")"#)) + } + + /// The reverse mistake: a bare specifier in `.snippet(...)` must point at `.module(...)`. + @Test + func bareSpecifierInSnippetSuggestsModule() throws { + let source = """ + let unrelated = 0 + @JSFunction(from: .snippet("node:path")) func imported() throws(JSException) + """ + let diagnostics = try #require(moduleDiagnostics(source: source)) + #expect(diagnostics.description.contains("JavaScript snippet paths must start with '/'")) + #expect(diagnostics.description.contains(#"from: .module("node:path")"#)) + } + + /// A snippet origin may also name a default export. + @Test + func defaultExportIsAcceptedForSnippetOrigin() throws { + let source = """ + let unrelated = 0 + @JSGetter(jsName: .default, from: .snippet("/Modules/utils.mjs")) var value: JSObject + """ + let diagnostics = try #require(moduleDiagnostics(source: source)) + // The file does not exist in this fixture, so the missing file must be the only + // complaint. Match on the diagnostic wording, not on `.default` itself, since the + // rendered diagnostic echoes the source line back. + #expect(diagnostics.description.contains("JavaScript snippet file was not found")) + #expect(!diagnostics.description.contains("requires 'from:")) + } + @Test func javaScriptModulePathMustNotTraverse() throws { let source = """ let unrelated = 0 - @JSFunction(from: .module("/../missing.js")) func imported() throws(JSException) + @JSFunction(from: .snippet("/../missing.js")) func imported() throws(JSException) """ let diagnostics = try #require(moduleDiagnostics(source: source)) - #expect(diagnostics.description.contains("JavaScript module paths must not contain '..'")) - #expect(diagnostics.description.contains("test.swift:2:27:")) + #expect(diagnostics.description.contains("JavaScript snippet paths must not contain '..'")) + #expect(diagnostics.description.contains("test.swift:2:28:")) } @Test func javaScriptModulePathMustUseSupportedExtension() throws { let source = """ let unrelated = 0 - @JSFunction(from: .module("/module.ts")) func imported() throws(JSException) + @JSFunction(from: .snippet("/module.ts")) func imported() throws(JSException) """ let diagnostics = try #require(moduleDiagnostics(source: source)) - #expect(diagnostics.description.contains("JavaScript modules must use a '.js' or '.mjs' extension")) - #expect(diagnostics.description.contains("test.swift:2:27:")) + #expect(diagnostics.description.contains("JavaScript snippets must use a '.js' or '.mjs' extension")) + #expect(diagnostics.description.contains("test.swift:2:28:")) } @Test @@ -77,7 +213,7 @@ import Testing @JSFunction(from: .module(modulePath)) func imported() throws(JSException) """ let diagnostics = try #require(moduleDiagnostics(source: source)) - #expect(diagnostics.description.contains("JavaScript module path must be a string literal.")) + #expect(diagnostics.description.contains("JavaScript module specifier must be a string literal.")) #expect(diagnostics.description.contains("test.swift:2:27:")) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/ImportedJSModuleRegistryTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/ImportedJSModuleRegistryTests.swift new file mode 100644 index 000000000..16c28be95 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/ImportedJSModuleRegistryTests.swift @@ -0,0 +1,222 @@ +import Foundation +import Testing + +@testable import BridgeJSLink +@testable import BridgeJSSkeleton + +/// Covers module-origin behavior that the single-Swift-module snapshot tests cannot reach: +/// how references from *several* Swift modules are deduplicated, ordered, and named. +@Suite struct ImportedJSModuleRegistryTests { + private func skeleton( + moduleName: String, + functions: [ImportedFunctionSkeleton] = [], + types: [ImportedTypeSkeleton] = [] + ) -> BridgeJSSkeleton { + BridgeJSSkeleton( + moduleName: moduleName, + imported: ImportedModuleSkeleton( + children: [ImportedFileSkeleton(functions: functions, types: types)] + ) + ) + } + + private func function( + _ name: String, + jsName: String? = nil, + from: JSImportFrom + ) -> ImportedFunctionSkeleton { + ImportedFunctionSkeleton( + name: name, + jsName: jsName, + from: from, + parameters: [], + returnType: .void + ) + } + + private func importLines(_ skeletons: [BridgeJSSkeleton]) throws -> [String] { + var link = BridgeJSLink(sharedMemory: false) + let encoder = JSONEncoder() + for skeleton in skeletons { + _ = try link.addSkeletonFile(data: try encoder.encode(skeleton)) + } + let js = try link.link().outputJs + return js.split(separator: "\n").map(String.init).filter { $0.hasPrefix("import ") } + } + + /// A bare specifier names the same module regardless of which Swift module mentions it, + /// so two Swift modules must share one import and one binding. + @Test func bareSpecifierIsSharedAcrossSwiftModules() throws { + let lines = try importLines([ + skeleton(moduleName: "Alpha", functions: [function("a", jsName: "basename", from: .module("node:path"))]), + skeleton(moduleName: "Beta", functions: [function("b", jsName: "dirname", from: .module("node:path"))]), + ]) + #expect(lines.count == 1) + #expect(lines[0].contains("from \"node:path\"")) + #expect(lines[0].contains("basename as ")) + #expect(lines[0].contains("dirname as ")) + } + + /// A local path is only meaningful relative to its Swift target, so the same path in two + /// Swift modules must stay two separate copies with two separate imports. + @Test func localPathIsNotSharedAcrossSwiftModules() throws { + let lines = try importLines([ + skeleton(moduleName: "Alpha", functions: [function("a", from: .snippet("/utils.mjs"))]), + skeleton(moduleName: "Beta", functions: [function("b", from: .snippet("/utils.mjs"))]), + ]) + #expect(lines.count == 2) + #expect(lines.contains { $0.contains("bridge-js-modules/Alpha/utils.mjs") }) + #expect(lines.contains { $0.contains("bridge-js-modules/Beta/utils.mjs") }) + } + + /// A named import is a hard link-time requirement, so a class whose module export is + /// never looked up must not produce one. A wrapper-only `@JSClass` has no constructor + /// and no static methods, so nothing references the module's export of that name and + /// the module need not export it at all; requiring it would fail the whole module load. + @Test func wrapperOnlyClassDoesNotRequireANamedExport() throws { + let lines = try importLines([ + skeleton( + moduleName: "Alpha", + types: [ + ImportedTypeSkeleton( + name: "Wrapper", + from: .module("some-pkg"), + methods: [ + ImportedFunctionSkeleton(name: "read", parameters: [], returnType: .void) + ] + ) + ] + ) + ]) + #expect(lines.count == 1) + #expect(lines[0].hasPrefix("import * as ")) + #expect(!lines[0].contains("Wrapper as ")) + } + + /// A class with a constructor does have its export looked up, so it keeps a named import. + @Test func classWithConstructorUsesANamedImport() throws { + let lines = try importLines([ + skeleton( + moduleName: "Alpha", + types: [ + ImportedTypeSkeleton( + name: "Wrapper", + from: .module("some-pkg"), + constructor: ImportedConstructorSkeleton(parameters: []) + ) + ] + ) + ]) + #expect(lines == [#"import { Wrapper as __bjs_import_0_Wrapper } from "some-pkg";"#]) + } + + /// A class with only static methods also looks its export up. + @Test func classWithOnlyStaticMethodsUsesANamedImport() throws { + let lines = try importLines([ + skeleton( + moduleName: "Alpha", + types: [ + ImportedTypeSkeleton( + name: "Wrapper", + from: .module("some-pkg"), + staticMethods: [ + ImportedFunctionSkeleton(name: "create", parameters: [], returnType: .void) + ] + ) + ] + ) + ]) + #expect(lines == [#"import { Wrapper as __bjs_import_0_Wrapper } from "some-pkg";"#]) + } + + /// Local references are emitted before bare ones, each group sorted, so that the numbered + /// aliases in generated JavaScript are stable across runs. + @Test func referencesAreOrderedDeterministically() throws { + let lines = try importLines([ + skeleton( + moduleName: "Alpha", + functions: [ + function("z", jsName: "zeta", from: .module("zzz-package")), + function("a", jsName: "alpha", from: .module("aaa-package")), + function("l", from: .snippet("/local.mjs")), + ] + ) + ]) + #expect(lines.count == 3) + #expect(lines[0].contains("/local.mjs")) + #expect(lines[1].contains("aaa-package")) + #expect(lines[2].contains("zzz-package")) + } + + /// A class and a free function on the same specifier share one import line. + @Test func classAndFunctionOnSameSpecifierShareOneImport() throws { + let lines = try importLines([ + skeleton( + moduleName: "Alpha", + functions: [function("a", jsName: "helper", from: .module("pkg"))], + types: [ + ImportedTypeSkeleton( + name: "Widget", + from: .module("pkg"), + constructor: ImportedConstructorSkeleton(parameters: []) + ) + ] + ) + ]) + #expect(lines.count == 1) + #expect(lines[0].contains("helper as ")) + #expect(lines[0].contains("Widget as ")) + } + + /// One non-identifier export name degrades its own origin to a namespace import without + /// affecting any other origin in the same program. + @Test func namespaceFallbackIsScopedToOneOrigin() throws { + let lines = try importLines([ + skeleton( + moduleName: "Alpha", + functions: [ + function("a", jsName: "kebab-case", from: .module("weird-package")), + function("b", jsName: "join", from: .module("node:path")), + ] + ) + ]) + let weird = try #require(lines.first { $0.contains("weird-package") }) + let node = try #require(lines.first { $0.contains("node:path") }) + #expect(weird.hasPrefix("import * as ")) + #expect(node.hasPrefix("import { join as ")) + } + + /// Because a bare specifier is shared across Swift modules, its member names form a union. + /// A non-identifier name contributed by one Swift module therefore degrades the shared + /// import for the other module too. That is intended — one specifier means one import + /// statement — but it is worth pinning so the behavior is not changed by accident. + @Test func nonIdentifierNameInOneSwiftModuleDegradesTheSharedImport() throws { + let lines = try importLines([ + skeleton(moduleName: "Alpha", functions: [function("a", jsName: "join", from: .module("node:path"))]), + skeleton(moduleName: "Beta", functions: [function("b", jsName: "odd-name", from: .module("node:path"))]), + ]) + #expect(lines.count == 1) + #expect(lines[0].hasPrefix("import * as ")) + } + + /// A reserved word is a legal ECMAScript export name, and `default` is how the default + /// export is spelled, so both must survive as named imports. + @Test(arguments: ["default", "class", "import"]) + func reservedWordExportNamesUseNamedImports(memberName: String) throws { + let lines = try importLines([ + skeleton(moduleName: "Alpha", functions: [function("a", jsName: memberName, from: .module("pkg"))]) + ]) + #expect(lines.count == 1) + #expect(lines[0].hasPrefix("import { \(memberName) as ")) + } + + /// A specifier is embedded in a JavaScript string literal, so quotes and backslashes in it + /// must be escaped rather than terminating the literal. + @Test func specifierIsEscapedInTheImportLine() throws { + let lines = try importLines([ + skeleton(moduleName: "Alpha", functions: [function("a", jsName: "x", from: .module("pk\"g\\y"))]) + ]) + #expect(lines.count == 1) + #expect(lines[0].hasSuffix(#"from "pk\"g\\y";"#)) + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSImportBareModule.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSImportBareModule.swift new file mode 100644 index 000000000..968b700e4 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSImportBareModule.swift @@ -0,0 +1,22 @@ +@JSFunction(jsName: "basename", from: .module("node:path")) +func nodeBasename(_ path: String) throws(JSException) -> String + +@JSFunction(jsName: "dirname", from: .module("node:path")) +func nodeDirname(_ path: String) throws(JSException) -> String + +@JSGetter(jsName: "version", from: .module("some-package")) +var packageVersion: String + +@JSFunction(jsName: .default, from: .module("default-export-package")) +func callDefaultExport(_ value: Int) throws(JSException) -> Int + +@JSGetter(jsName: .default, from: .snippet("/Modules/DefaultExport.mjs")) +var localDefaultExport: JSObject + +@JSClass(jsName: "File", from: .module("@scope/package")) +struct ScopedFile { + @JSFunction init(_ value: Int) throws(JSException) + @JSFunction static func create(_ value: Int) throws(JSException) -> ScopedFile + @JSFunction func read() throws(JSException) -> Int + @JSGetter var size: Int +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSImportBareModuleFallback.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSImportBareModuleFallback.swift new file mode 100644 index 000000000..78671e33e --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSImportBareModuleFallback.swift @@ -0,0 +1,12 @@ +// `weird-package` needs a member name that is not a valid JavaScript identifier, so +// the whole origin falls back to a namespace import. `node:path` in the same file +// keeps using named imports, proving the fallback is per-origin. + +@JSFunction(jsName: "kebab-case-function", from: .module("weird-package")) +func kebabCaseFunction() throws(JSException) -> Int + +@JSGetter(jsName: "dashed-property", from: .module("weird-package")) +var dashedProperty: String + +@JSFunction(jsName: "join", from: .module("node:path")) +func joinPaths(_ lhs: String, _ rhs: String) throws(JSException) -> String diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSImportModule.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSImportModule.swift index 3fd9d79e7..091ac7911 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSImportModule.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSImportModule.swift @@ -1,13 +1,13 @@ -@JSFunction(from: .module("/Modules/JSImportModule.mjs")) +@JSFunction(from: .snippet("/Modules/JSImportModule.mjs")) func moduleAdd(_ lhs: Int, _ rhs: Int) throws(JSException) -> Int -@JSFunction(jsName: "renamedFunction", from: .module("/Modules/JSImportModule.mjs")) +@JSFunction(jsName: "renamedFunction", from: .snippet("/Modules/JSImportModule.mjs")) func moduleRenamed() throws(JSException) -> String -@JSGetter(jsName: "version", from: .module("/Modules/JSImportModule.mjs")) +@JSGetter(jsName: "version", from: .snippet("/Modules/JSImportModule.mjs")) var moduleVersion: String -@JSClass(from: .module("/Modules/ModuleCounter.mjs")) +@JSClass(from: .snippet("/Modules/ModuleCounter.mjs")) struct ModuleCounter { @JSFunction init(_ value: Int) throws(JSException) @JSFunction static func create(_ value: Int) throws(JSException) -> ModuleCounter diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportBareModule.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportBareModule.json new file mode 100644 index 000000000..5aebf1ac7 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportBareModule.json @@ -0,0 +1,232 @@ +{ + "imported" : { + "children" : [ + { + "functions" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "from" : { + "kind" : "module", + "specifier" : "node:path" + }, + "jsName" : "basename", + "name" : "nodeBasename", + "parameters" : [ + { + "name" : "path", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "from" : { + "kind" : "module", + "specifier" : "node:path" + }, + "jsName" : "dirname", + "name" : "nodeDirname", + "parameters" : [ + { + "name" : "path", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "from" : { + "kind" : "module", + "specifier" : "default-export-package" + }, + "jsName" : "default", + "name" : "callDefaultExport", + "parameters" : [ + { + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "globalGetters" : [ + { + "accessLevel" : "internal", + "from" : { + "kind" : "module", + "specifier" : "some-package" + }, + "jsName" : "version", + "name" : "packageVersion", + "type" : { + "string" : { + + } + } + }, + { + "accessLevel" : "internal", + "from" : { + "kind" : "snippet", + "path" : "\/Modules\/DefaultExport.mjs" + }, + "jsName" : "default", + "name" : "localDefaultExport", + "type" : { + "jsObject" : { + + } + } + } + ], + "types" : [ + { + "accessLevel" : "internal", + "constructor" : { + "accessLevel" : "internal", + "parameters" : [ + { + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ] + }, + "from" : { + "kind" : "module", + "specifier" : "@scope\/package" + }, + "getters" : [ + { + "accessLevel" : "internal", + "name" : "size", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "jsName" : "File", + "methods" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "read", + "parameters" : [ + + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "name" : "ScopedFile", + "setters" : [ + + ], + "staticMethods" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "name" : "create", + "parameters" : [ + { + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "jsObject" : { + "_0" : "ScopedFile" + } + } + } + ] + } + ] + } + ] + }, + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportBareModule.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportBareModule.swift new file mode 100644 index 000000000..4baf8d0f0 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportBareModule.swift @@ -0,0 +1,192 @@ +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_packageVersion_get") +fileprivate func bjs_packageVersion_get_extern() -> Int32 +#else +fileprivate func bjs_packageVersion_get_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_packageVersion_get() -> Int32 { + return bjs_packageVersion_get_extern() +} + +func _$packageVersion_get() throws(JSException) -> String { + let ret = bjs_packageVersion_get() + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_localDefaultExport_get") +fileprivate func bjs_localDefaultExport_get_extern() -> Int32 +#else +fileprivate func bjs_localDefaultExport_get_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_localDefaultExport_get() -> Int32 { + return bjs_localDefaultExport_get_extern() +} + +func _$localDefaultExport_get() throws(JSException) -> JSObject { + let ret = bjs_localDefaultExport_get() + if let error = _swift_js_take_exception() { + throw error + } + return JSObject.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_nodeBasename") +fileprivate func bjs_nodeBasename_extern(_ pathBytes: Int32, _ pathLength: Int32) -> Int32 +#else +fileprivate func bjs_nodeBasename_extern(_ pathBytes: Int32, _ pathLength: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_nodeBasename(_ pathBytes: Int32, _ pathLength: Int32) -> Int32 { + return bjs_nodeBasename_extern(pathBytes, pathLength) +} + +func _$nodeBasename(_ path: String) throws(JSException) -> String { + let ret0 = path.bridgeJSWithLoweredParameter { (pathBytes, pathLength) in + let ret = bjs_nodeBasename(pathBytes, pathLength) + return ret + } + let ret = ret0 + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_nodeDirname") +fileprivate func bjs_nodeDirname_extern(_ pathBytes: Int32, _ pathLength: Int32) -> Int32 +#else +fileprivate func bjs_nodeDirname_extern(_ pathBytes: Int32, _ pathLength: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_nodeDirname(_ pathBytes: Int32, _ pathLength: Int32) -> Int32 { + return bjs_nodeDirname_extern(pathBytes, pathLength) +} + +func _$nodeDirname(_ path: String) throws(JSException) -> String { + let ret0 = path.bridgeJSWithLoweredParameter { (pathBytes, pathLength) in + let ret = bjs_nodeDirname(pathBytes, pathLength) + return ret + } + let ret = ret0 + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_callDefaultExport") +fileprivate func bjs_callDefaultExport_extern(_ value: Int32) -> Int32 +#else +fileprivate func bjs_callDefaultExport_extern(_ value: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_callDefaultExport(_ value: Int32) -> Int32 { + return bjs_callDefaultExport_extern(value) +} + +func _$callDefaultExport(_ value: Int) throws(JSException) -> Int { + let valueValue = value.bridgeJSLowerParameter() + let ret = bjs_callDefaultExport(valueValue) + if let error = _swift_js_take_exception() { + throw error + } + return Int.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_ScopedFile_init") +fileprivate func bjs_ScopedFile_init_extern(_ value: Int32) -> Int32 +#else +fileprivate func bjs_ScopedFile_init_extern(_ value: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ScopedFile_init(_ value: Int32) -> Int32 { + return bjs_ScopedFile_init_extern(value) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_ScopedFile_create_static") +fileprivate func bjs_ScopedFile_create_static_extern(_ value: Int32) -> Int32 +#else +fileprivate func bjs_ScopedFile_create_static_extern(_ value: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ScopedFile_create_static(_ value: Int32) -> Int32 { + return bjs_ScopedFile_create_static_extern(value) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_ScopedFile_size_get") +fileprivate func bjs_ScopedFile_size_get_extern(_ self: Int32) -> Int32 +#else +fileprivate func bjs_ScopedFile_size_get_extern(_ self: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ScopedFile_size_get(_ self: Int32) -> Int32 { + return bjs_ScopedFile_size_get_extern(self) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_ScopedFile_read") +fileprivate func bjs_ScopedFile_read_extern(_ self: Int32) -> Int32 +#else +fileprivate func bjs_ScopedFile_read_extern(_ self: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ScopedFile_read(_ self: Int32) -> Int32 { + return bjs_ScopedFile_read_extern(self) +} + +func _$ScopedFile_init(_ value: Int) throws(JSException) -> JSObject { + let valueValue = value.bridgeJSLowerParameter() + let ret = bjs_ScopedFile_init(valueValue) + if let error = _swift_js_take_exception() { + throw error + } + return JSObject.bridgeJSLiftReturn(ret) +} + +func _$ScopedFile_create(_ value: Int) throws(JSException) -> ScopedFile { + let valueValue = value.bridgeJSLowerParameter() + let ret = bjs_ScopedFile_create_static(valueValue) + if let error = _swift_js_take_exception() { + throw error + } + return ScopedFile.bridgeJSLiftReturn(ret) +} + +func _$ScopedFile_size_get(_ self: JSObject) throws(JSException) -> Int { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_ScopedFile_size_get(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return Int.bridgeJSLiftReturn(ret) +} + +func _$ScopedFile_read(_ self: JSObject) throws(JSException) -> Int { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_ScopedFile_read(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return Int.bridgeJSLiftReturn(ret) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportBareModuleFallback.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportBareModuleFallback.json new file mode 100644 index 000000000..451d21402 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportBareModuleFallback.json @@ -0,0 +1,95 @@ +{ + "imported" : { + "children" : [ + { + "functions" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "from" : { + "kind" : "module", + "specifier" : "weird-package" + }, + "jsName" : "kebab-case-function", + "name" : "kebabCaseFunction", + "parameters" : [ + + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "from" : { + "kind" : "module", + "specifier" : "node:path" + }, + "jsName" : "join", + "name" : "joinPaths", + "parameters" : [ + { + "name" : "lhs", + "type" : { + "string" : { + + } + } + }, + { + "name" : "rhs", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + } + } + ], + "globalGetters" : [ + { + "accessLevel" : "internal", + "from" : { + "kind" : "module", + "specifier" : "weird-package" + }, + "jsName" : "dashed-property", + "name" : "dashedProperty", + "type" : { + "string" : { + + } + } + } + ], + "types" : [ + + ] + } + ] + }, + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportBareModuleFallback.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportBareModuleFallback.swift new file mode 100644 index 000000000..7780b5eb0 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportBareModuleFallback.swift @@ -0,0 +1,66 @@ +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_dashedProperty_get") +fileprivate func bjs_dashedProperty_get_extern() -> Int32 +#else +fileprivate func bjs_dashedProperty_get_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_dashedProperty_get() -> Int32 { + return bjs_dashedProperty_get_extern() +} + +func _$dashedProperty_get() throws(JSException) -> String { + let ret = bjs_dashedProperty_get() + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_kebabCaseFunction") +fileprivate func bjs_kebabCaseFunction_extern() -> Int32 +#else +fileprivate func bjs_kebabCaseFunction_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_kebabCaseFunction() -> Int32 { + return bjs_kebabCaseFunction_extern() +} + +func _$kebabCaseFunction() throws(JSException) -> Int { + let ret = bjs_kebabCaseFunction() + if let error = _swift_js_take_exception() { + throw error + } + return Int.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_joinPaths") +fileprivate func bjs_joinPaths_extern(_ lhsBytes: Int32, _ lhsLength: Int32, _ rhsBytes: Int32, _ rhsLength: Int32) -> Int32 +#else +fileprivate func bjs_joinPaths_extern(_ lhsBytes: Int32, _ lhsLength: Int32, _ rhsBytes: Int32, _ rhsLength: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_joinPaths(_ lhsBytes: Int32, _ lhsLength: Int32, _ rhsBytes: Int32, _ rhsLength: Int32) -> Int32 { + return bjs_joinPaths_extern(lhsBytes, lhsLength, rhsBytes, rhsLength) +} + +func _$joinPaths(_ lhs: String, _ rhs: String) throws(JSException) -> String { + let ret0 = lhs.bridgeJSWithLoweredParameter { (lhsBytes, lhsLength) in + let ret1 = rhs.bridgeJSWithLoweredParameter { (rhsBytes, rhsLength) in + let ret = bjs_joinPaths(lhsBytes, lhsLength, rhsBytes, rhsLength) + return ret + } + return ret1 + } + let ret = ret0 + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportModule.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportModule.json index d90e88f1d..3d886fb9d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportModule.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSImportModule.json @@ -10,7 +10,10 @@ "isStatic" : false, "isThrows" : true }, - "from" : "\/Modules\/JSImportModule.mjs", + "from" : { + "kind" : "snippet", + "path" : "\/Modules\/JSImportModule.mjs" + }, "name" : "moduleAdd", "parameters" : [ { @@ -52,7 +55,10 @@ "isStatic" : false, "isThrows" : true }, - "from" : "\/Modules\/JSImportModule.mjs", + "from" : { + "kind" : "snippet", + "path" : "\/Modules\/JSImportModule.mjs" + }, "jsName" : "renamedFunction", "name" : "moduleRenamed", "parameters" : [ @@ -68,7 +74,10 @@ "globalGetters" : [ { "accessLevel" : "internal", - "from" : "\/Modules\/JSImportModule.mjs", + "from" : { + "kind" : "snippet", + "path" : "\/Modules\/JSImportModule.mjs" + }, "jsName" : "version", "name" : "moduleVersion", "type" : { @@ -97,7 +106,10 @@ } ] }, - "from" : "\/Modules\/ModuleCounter.mjs", + "from" : { + "kind" : "snippet", + "path" : "\/Modules\/ModuleCounter.mjs" + }, "getters" : [ { "accessLevel" : "internal", diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModule.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModule.d.ts new file mode 100644 index 000000000..a6267bd31 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModule.d.ts @@ -0,0 +1,21 @@ +// 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`. + +export interface ScopedFile { + read(): number; + readonly size: number; +} +export type Exports = { +} +export type Imports = { +} +export function createInstantiator(options: { + imports: Imports; +}, swift: any): Promise<{ + addImports: (importObject: WebAssembly.Imports) => void; + setInstance: (instance: WebAssembly.Instance) => void; + createExports: (instance: WebAssembly.Instance) => Exports; +}>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModule.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModule.js new file mode 100644 index 000000000..1c995923a --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModule.js @@ -0,0 +1,315 @@ +// 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`. + +import { default as __bjs_import_0_default } from "./bridge-js-modules/TestModule/Modules/DefaultExport.mjs"; +import { File as __bjs_import_1_File } from "@scope/package"; +import { default as __bjs_import_2_default } from "default-export-package"; +import { basename as __bjs_import_3_basename, dirname as __bjs_import_3_dirname } from "node:path"; +import { version as __bjs_import_4_version } from "some-package"; + +export async function createInstantiator(options, swift) { + let instance; + let memory; + let setException; + let decodeString; + const textDecoder = new TextDecoder("utf-8"); + const textEncoder = new TextEncoder("utf-8"); + let tmpRetString; + let tmpRetBytes; + let tmpRetException; + let tmpRetOptionalBool; + let tmpRetOptionalInt; + let tmpRetOptionalFloat; + let tmpRetOptionalDouble; + let tmpRetOptionalHeapObject; + let strStack = []; + let i32Stack = []; + let i64Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; + let taStack = []; + const enumHelpers = {}; + const structHelpers = {}; + + let _exports = null; + let bjs = null; + + return { + /** + * @param {WebAssembly.Imports} importObject + */ + addImports: (importObject, importsContext) => { + bjs = {}; + importObject["bjs"] = bjs; + bjs["swift_js_return_string"] = function(ptr, len) { + tmpRetString = decodeString(ptr, len); + } + bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { + const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); + bytes.set(source); + } + bjs["swift_js_make_js_string"] = function(ptr, len) { + return swift.memory.retain(decodeString(ptr, len)); + } + bjs["swift_js_init_memory_with_result"] = function(ptr, len) { + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); + target.set(tmpRetBytes); + tmpRetBytes = undefined; + } + bjs["swift_js_throw"] = function(id) { + tmpRetException = swift.memory.retainByRef(id); + } + bjs["swift_js_retain"] = function(id) { + return swift.memory.retainByRef(id); + } + bjs["swift_js_release"] = function(id) { + swift.memory.release(id); + } + bjs["swift_js_push_i32"] = function(v) { + i32Stack.push(v | 0); + } + bjs["swift_js_push_f32"] = function(v) { + f32Stack.push(Math.fround(v)); + } + bjs["swift_js_push_f64"] = function(v) { + f64Stack.push(v); + } + bjs["swift_js_push_string"] = function(ptr, len) { + const value = decodeString(ptr, len); + strStack.push(value); + } + bjs["swift_js_pop_i32"] = function() { + return i32Stack.pop(); + } + bjs["swift_js_pop_f32"] = function() { + return f32Stack.pop(); + } + bjs["swift_js_pop_f64"] = function() { + return f64Stack.pop(); + } + bjs["swift_js_push_pointer"] = function(pointer) { + ptrStack.push(pointer); + } + bjs["swift_js_pop_pointer"] = function() { + return ptrStack.pop(); + } + bjs["swift_js_push_i64"] = function(v) { + i64Stack.push(v); + } + bjs["swift_js_pop_i64"] = function() { + return i64Stack.pop(); + } + const taCtors = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array]; + bjs["swift_js_push_typed_array"] = function(kind, ptr, count) { + const Ctor = taCtors[kind]; + const byteLen = count * Ctor.BYTES_PER_ELEMENT; + const copy = memory.buffer.slice(ptr, ptr + byteLen); + taStack.push(Array.from(new Ctor(copy))); + } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } + bjs["swift_js_return_optional_bool"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalBool = null; + } else { + tmpRetOptionalBool = value !== 0; + } + } + bjs["swift_js_return_optional_int"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalInt = null; + } else { + tmpRetOptionalInt = value | 0; + } + } + bjs["swift_js_return_optional_float"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalFloat = null; + } else { + tmpRetOptionalFloat = Math.fround(value); + } + } + bjs["swift_js_return_optional_double"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalDouble = null; + } else { + tmpRetOptionalDouble = value; + } + } + bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = decodeString(ptr, len); + } + } + bjs["swift_js_return_optional_object"] = function(isSome, objectId) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = swift.memory.getObject(objectId); + } + } + bjs["swift_js_return_optional_heap_object"] = function(isSome, pointer) { + if (isSome === 0) { + tmpRetOptionalHeapObject = null; + } else { + tmpRetOptionalHeapObject = pointer; + } + } + bjs["swift_js_get_optional_int_presence"] = function() { + return tmpRetOptionalInt != null ? 1 : 0; + } + bjs["swift_js_get_optional_int_value"] = function() { + const value = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; + return value; + } + bjs["swift_js_get_optional_string"] = function() { + const str = tmpRetString; + tmpRetString = undefined; + if (str == null) { + return -1; + } else { + const bytes = textEncoder.encode(str); + tmpRetBytes = bytes; + return bytes.length; + } + } + bjs["swift_js_get_optional_float_presence"] = function() { + return tmpRetOptionalFloat != null ? 1 : 0; + } + bjs["swift_js_get_optional_float_value"] = function() { + const value = tmpRetOptionalFloat; + tmpRetOptionalFloat = undefined; + return value; + } + bjs["swift_js_get_optional_double_presence"] = function() { + return tmpRetOptionalDouble != null ? 1 : 0; + } + bjs["swift_js_get_optional_double_value"] = function() { + const value = tmpRetOptionalDouble; + tmpRetOptionalDouble = undefined; + return value; + } + bjs["swift_js_get_optional_heap_object_pointer"] = function() { + const pointer = tmpRetOptionalHeapObject; + tmpRetOptionalHeapObject = undefined; + return pointer || 0; + } + bjs["swift_js_closure_unregister"] = function(funcRef) {} + const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; + TestModule["bjs_packageVersion_get"] = function bjs_packageVersion_get() { + try { + let ret = __bjs_import_4_version; + tmpRetBytes = textEncoder.encode(ret); + return tmpRetBytes.length; + } catch (error) { + setException(error); + } + } + TestModule["bjs_localDefaultExport_get"] = function bjs_localDefaultExport_get() { + try { + let ret = __bjs_import_0_default; + return swift.memory.retain(ret); + } catch (error) { + setException(error); + return 0 + } + } + TestModule["bjs_nodeBasename"] = function bjs_nodeBasename(pathBytes, pathCount) { + try { + const string = decodeString(pathBytes, pathCount); + let ret = __bjs_import_3_basename(string); + tmpRetBytes = textEncoder.encode(ret); + return tmpRetBytes.length; + } catch (error) { + setException(error); + } + } + TestModule["bjs_nodeDirname"] = function bjs_nodeDirname(pathBytes, pathCount) { + try { + const string = decodeString(pathBytes, pathCount); + let ret = __bjs_import_3_dirname(string); + tmpRetBytes = textEncoder.encode(ret); + return tmpRetBytes.length; + } catch (error) { + setException(error); + } + } + TestModule["bjs_callDefaultExport"] = function bjs_callDefaultExport(value) { + try { + let ret = __bjs_import_2_default(value); + return ret; + } catch (error) { + setException(error); + return 0 + } + } + TestModule["bjs_ScopedFile_init"] = function bjs_ScopedFile_init(value) { + try { + return swift.memory.retain(new __bjs_import_1_File(value)); + } catch (error) { + setException(error); + return 0 + } + } + TestModule["bjs_ScopedFile_size_get"] = function bjs_ScopedFile_size_get(self) { + try { + let ret = swift.memory.getObject(self).size; + return ret; + } catch (error) { + setException(error); + return 0 + } + } + TestModule["bjs_ScopedFile_create_static"] = function bjs_ScopedFile_create_static(value) { + try { + let ret = __bjs_import_1_File.create(value); + return swift.memory.retain(ret); + } catch (error) { + setException(error); + return 0 + } + } + TestModule["bjs_ScopedFile_read"] = function bjs_ScopedFile_read(self) { + try { + let ret = swift.memory.getObject(self).read(); + return ret; + } catch (error) { + setException(error); + return 0 + } + } + }, + setInstance: (i) => { + instance = i; + memory = instance.exports.memory; + + decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + + setException = (error) => { + instance.exports._swift_js_exception.value = swift.memory.retain(error) + } + }, + /** @param {WebAssembly.Instance} instance */ + createExports: (instance) => { + const js = swift.memory.heap; + const exports = { + }; + _exports = exports; + return exports; + }, + } +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModuleFallback.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModuleFallback.d.ts new file mode 100644 index 000000000..818d57a9d --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModuleFallback.d.ts @@ -0,0 +1,17 @@ +// 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`. + +export type Exports = { +} +export type Imports = { +} +export function createInstantiator(options: { + imports: Imports; +}, swift: any): Promise<{ + addImports: (importObject: WebAssembly.Imports) => void; + setInstance: (instance: WebAssembly.Instance) => void; + createExports: (instance: WebAssembly.Instance) => Exports; +}>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModuleFallback.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModuleFallback.js new file mode 100644 index 000000000..038374240 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModuleFallback.js @@ -0,0 +1,259 @@ +// 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`. + +import { join as __bjs_import_0_join } from "node:path"; +import * as __bjs_imported_module_1 from "weird-package"; + +export async function createInstantiator(options, swift) { + let instance; + let memory; + let setException; + let decodeString; + const textDecoder = new TextDecoder("utf-8"); + const textEncoder = new TextEncoder("utf-8"); + let tmpRetString; + let tmpRetBytes; + let tmpRetException; + let tmpRetOptionalBool; + let tmpRetOptionalInt; + let tmpRetOptionalFloat; + let tmpRetOptionalDouble; + let tmpRetOptionalHeapObject; + let strStack = []; + let i32Stack = []; + let i64Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; + let taStack = []; + const enumHelpers = {}; + const structHelpers = {}; + + let _exports = null; + let bjs = null; + + return { + /** + * @param {WebAssembly.Imports} importObject + */ + addImports: (importObject, importsContext) => { + bjs = {}; + importObject["bjs"] = bjs; + bjs["swift_js_return_string"] = function(ptr, len) { + tmpRetString = decodeString(ptr, len); + } + bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { + const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); + bytes.set(source); + } + bjs["swift_js_make_js_string"] = function(ptr, len) { + return swift.memory.retain(decodeString(ptr, len)); + } + bjs["swift_js_init_memory_with_result"] = function(ptr, len) { + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); + target.set(tmpRetBytes); + tmpRetBytes = undefined; + } + bjs["swift_js_throw"] = function(id) { + tmpRetException = swift.memory.retainByRef(id); + } + bjs["swift_js_retain"] = function(id) { + return swift.memory.retainByRef(id); + } + bjs["swift_js_release"] = function(id) { + swift.memory.release(id); + } + bjs["swift_js_push_i32"] = function(v) { + i32Stack.push(v | 0); + } + bjs["swift_js_push_f32"] = function(v) { + f32Stack.push(Math.fround(v)); + } + bjs["swift_js_push_f64"] = function(v) { + f64Stack.push(v); + } + bjs["swift_js_push_string"] = function(ptr, len) { + const value = decodeString(ptr, len); + strStack.push(value); + } + bjs["swift_js_pop_i32"] = function() { + return i32Stack.pop(); + } + bjs["swift_js_pop_f32"] = function() { + return f32Stack.pop(); + } + bjs["swift_js_pop_f64"] = function() { + return f64Stack.pop(); + } + bjs["swift_js_push_pointer"] = function(pointer) { + ptrStack.push(pointer); + } + bjs["swift_js_pop_pointer"] = function() { + return ptrStack.pop(); + } + bjs["swift_js_push_i64"] = function(v) { + i64Stack.push(v); + } + bjs["swift_js_pop_i64"] = function() { + return i64Stack.pop(); + } + const taCtors = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array]; + bjs["swift_js_push_typed_array"] = function(kind, ptr, count) { + const Ctor = taCtors[kind]; + const byteLen = count * Ctor.BYTES_PER_ELEMENT; + const copy = memory.buffer.slice(ptr, ptr + byteLen); + taStack.push(Array.from(new Ctor(copy))); + } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } + bjs["swift_js_return_optional_bool"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalBool = null; + } else { + tmpRetOptionalBool = value !== 0; + } + } + bjs["swift_js_return_optional_int"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalInt = null; + } else { + tmpRetOptionalInt = value | 0; + } + } + bjs["swift_js_return_optional_float"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalFloat = null; + } else { + tmpRetOptionalFloat = Math.fround(value); + } + } + bjs["swift_js_return_optional_double"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalDouble = null; + } else { + tmpRetOptionalDouble = value; + } + } + bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = decodeString(ptr, len); + } + } + bjs["swift_js_return_optional_object"] = function(isSome, objectId) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = swift.memory.getObject(objectId); + } + } + bjs["swift_js_return_optional_heap_object"] = function(isSome, pointer) { + if (isSome === 0) { + tmpRetOptionalHeapObject = null; + } else { + tmpRetOptionalHeapObject = pointer; + } + } + bjs["swift_js_get_optional_int_presence"] = function() { + return tmpRetOptionalInt != null ? 1 : 0; + } + bjs["swift_js_get_optional_int_value"] = function() { + const value = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; + return value; + } + bjs["swift_js_get_optional_string"] = function() { + const str = tmpRetString; + tmpRetString = undefined; + if (str == null) { + return -1; + } else { + const bytes = textEncoder.encode(str); + tmpRetBytes = bytes; + return bytes.length; + } + } + bjs["swift_js_get_optional_float_presence"] = function() { + return tmpRetOptionalFloat != null ? 1 : 0; + } + bjs["swift_js_get_optional_float_value"] = function() { + const value = tmpRetOptionalFloat; + tmpRetOptionalFloat = undefined; + return value; + } + bjs["swift_js_get_optional_double_presence"] = function() { + return tmpRetOptionalDouble != null ? 1 : 0; + } + bjs["swift_js_get_optional_double_value"] = function() { + const value = tmpRetOptionalDouble; + tmpRetOptionalDouble = undefined; + return value; + } + bjs["swift_js_get_optional_heap_object_pointer"] = function() { + const pointer = tmpRetOptionalHeapObject; + tmpRetOptionalHeapObject = undefined; + return pointer || 0; + } + bjs["swift_js_closure_unregister"] = function(funcRef) {} + const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; + TestModule["bjs_dashedProperty_get"] = function bjs_dashedProperty_get() { + try { + let ret = __bjs_imported_module_1["dashed-property"]; + tmpRetBytes = textEncoder.encode(ret); + return tmpRetBytes.length; + } catch (error) { + setException(error); + } + } + TestModule["bjs_kebabCaseFunction"] = function bjs_kebabCaseFunction() { + try { + let ret = __bjs_imported_module_1["kebab-case-function"](); + return ret; + } catch (error) { + setException(error); + return 0 + } + } + TestModule["bjs_joinPaths"] = function bjs_joinPaths(lhsBytes, lhsCount, rhsBytes, rhsCount) { + try { + const string = decodeString(lhsBytes, lhsCount); + const string1 = decodeString(rhsBytes, rhsCount); + let ret = __bjs_import_0_join(string, string1); + tmpRetBytes = textEncoder.encode(ret); + return tmpRetBytes.length; + } catch (error) { + setException(error); + } + } + }, + setInstance: (i) => { + instance = i; + memory = instance.exports.memory; + + decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + + setException = (error) => { + instance.exports._swift_js_exception.value = swift.memory.retain(error) + } + }, + /** @param {WebAssembly.Instance} instance */ + createExports: (instance) => { + const js = swift.memory.heap; + const exports = { + }; + _exports = exports; + return exports; + }, + } +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.js index cb4767f03..e03dcbab4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.js @@ -4,8 +4,8 @@ // To update this file, just rebuild your project or run // `swift package bridge-js`. -import * as __bjs_imported_module_0 from "./bridge-js-modules/TestModule/Modules/JSImportModule.mjs"; -import * as __bjs_imported_module_1 from "./bridge-js-modules/TestModule/Modules/ModuleCounter.mjs"; +import { moduleAdd as __bjs_import_0_moduleAdd, renamedFunction as __bjs_import_0_renamedFunction, version as __bjs_import_0_version } from "./bridge-js-modules/TestModule/Modules/JSImportModule.mjs"; +import { ModuleCounter as __bjs_import_1_ModuleCounter } from "./bridge-js-modules/TestModule/Modules/ModuleCounter.mjs"; export async function createInstantiator(options, swift) { let instance; @@ -209,7 +209,7 @@ export async function createInstantiator(options, swift) { const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; TestModule["bjs_moduleVersion_get"] = function bjs_moduleVersion_get() { try { - let ret = __bjs_imported_module_0.version; + let ret = __bjs_import_0_version; tmpRetBytes = textEncoder.encode(ret); return tmpRetBytes.length; } catch (error) { @@ -218,7 +218,7 @@ export async function createInstantiator(options, swift) { } TestModule["bjs_moduleAdd"] = function bjs_moduleAdd(lhs, rhs) { try { - let ret = __bjs_imported_module_0.moduleAdd(lhs, rhs); + let ret = __bjs_import_0_moduleAdd(lhs, rhs); return ret; } catch (error) { setException(error); @@ -227,7 +227,7 @@ export async function createInstantiator(options, swift) { } TestModule["bjs_moduleRenamed"] = function bjs_moduleRenamed() { try { - let ret = __bjs_imported_module_0.renamedFunction(); + let ret = __bjs_import_0_renamedFunction(); tmpRetBytes = textEncoder.encode(ret); return tmpRetBytes.length; } catch (error) { @@ -236,7 +236,7 @@ export async function createInstantiator(options, swift) { } TestModule["bjs_ModuleCounter_init"] = function bjs_ModuleCounter_init(value) { try { - return swift.memory.retain(new __bjs_imported_module_1.ModuleCounter(value)); + return swift.memory.retain(new __bjs_import_1_ModuleCounter(value)); } catch (error) { setException(error); return 0 @@ -260,7 +260,7 @@ export async function createInstantiator(options, swift) { } TestModule["bjs_ModuleCounter_create_static"] = function bjs_ModuleCounter_create_static(value) { try { - let ret = __bjs_imported_module_1.ModuleCounter.create(value); + let ret = __bjs_import_1_ModuleCounter.create(value); return swift.memory.retain(ret); } catch (error) { setException(error); diff --git a/Plugins/PackageToJS/Sources/PackageToJS.swift b/Plugins/PackageToJS/Sources/PackageToJS.swift index d86a34fa1..c1d09af0a 100644 --- a/Plugins/PackageToJS/Sources/PackageToJS.swift +++ b/Plugins/PackageToJS/Sources/PackageToJS.swift @@ -698,7 +698,10 @@ struct PackagingPlanner { for input in skeletons { let skeleton = try link.addSkeletonFile(data: Data(contentsOf: input.source)) - for reference in ImportedJSModuleRegistry.collectReferences(skeletons: [skeleton]) { + // Only target-local modules are files we copy. Bare specifiers (e.g. "node:path", + // "lodash") are resolved by the JavaScript host at load time, so there is + // nothing to find on disk and nothing to place in the output. + for reference in ImportedJSModuleRegistry.collectSnippetFiles(skeletons: [skeleton]) { guard let sourceURL = JavaScriptModulePath.resolve( reference.path, diff --git a/Plugins/PackageToJS/Tests/PackagingPlannerTests.swift b/Plugins/PackageToJS/Tests/PackagingPlannerTests.swift index e5f04402a..12187a201 100644 --- a/Plugins/PackageToJS/Tests/PackagingPlannerTests.swift +++ b/Plugins/PackageToJS/Tests/PackagingPlannerTests.swift @@ -134,7 +134,7 @@ import Testing functions: [ ImportedFunctionSkeleton( name: "value", - from: .module("/module.mjs"), + from: .snippet("/module.mjs"), parameters: [], returnType: .void ) @@ -208,4 +208,165 @@ import Testing #expect(system.writtenFiles.filter { $0.hasSuffix("/bridge-js.js") }.count == initialLinkCount) } } + + /// A bare specifier must not suppress copying of local modules that appear alongside it. + @Test func mixedLocalAndBareModulesBothWork() throws { + try withTemporaryDirectory { temporaryDirectory, _ in + let skeleton = temporaryDirectory.appending(path: "BridgeJS.json") + let module = temporaryDirectory.appending(path: "module.mjs") + let wasm = temporaryDirectory.appending(path: "main.wasm") + let plannerSource = temporaryDirectory.appending(path: "PackageToJS.swift") + let output = temporaryDirectory.appending(path: "output") + let intermediates = temporaryDirectory.appending(path: "intermediates") + + let bridgeSkeleton = BridgeJSSkeleton( + moduleName: "TestModule", + imported: ImportedModuleSkeleton( + children: [ + ImportedFileSkeleton( + functions: [ + ImportedFunctionSkeleton( + name: "value", + from: .snippet("/module.mjs"), + parameters: [], + returnType: .void + ), + ImportedFunctionSkeleton( + name: "basename", + from: .module("node:path"), + parameters: [], + returnType: .void + ), + ], + types: [] + ) + ] + ) + ) + try JSONEncoder().encode(bridgeSkeleton).write(to: skeleton) + try Data("export const value = 1;\n".utf8).write(to: module) + try Data([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]).write(to: wasm) + try Data().write(to: plannerSource) + + let system = TestPackagingSystem() + let planner = PackagingPlanner( + options: PackageToJS.PackageOptions(), + packageId: "test", + intermediatesDir: BuildPath(absolute: intermediates.path), + selfPackageDir: BuildPath( + absolute: URL(fileURLWithPath: #filePath) + .deletingLastPathComponent() + .deletingLastPathComponent() + .deletingLastPathComponent() + .deletingLastPathComponent() + .path + ), + skeletons: [.init(source: skeleton, targetDirectory: temporaryDirectory)], + outputDir: BuildPath(absolute: output.path), + wasmProductArtifact: BuildPath(absolute: wasm.path), + wasmFilename: "main.wasm", + configuration: "debug", + triple: "wasm32-unknown-wasi", + selfPath: BuildPath(absolute: plannerSource.path), + system: system + ) + var make = MiniMake(printProgress: { _, _ in }) + let root = try planner.planBuild( + make: &make, + buildOptions: PackageToJS.BuildOptions( + product: "test", + noOptimize: false, + debugInfoFormat: .none, + packageOptions: PackageToJS.PackageOptions() + ) + ) + try make.build(output: root, scope: MiniMake.VariableScope(variables: [:])) + + let copiedModule = output.appending(path: "bridge-js-modules/TestModule/module.mjs") + #expect(try String(contentsOf: copiedModule, encoding: .utf8) == "export const value = 1;\n") + let generated = try String(contentsOf: output.appending(path: "bridge-js.js"), encoding: .utf8) + #expect(generated.contains("from \"node:path\"")) + #expect(generated.contains("bridge-js-modules/TestModule/module.mjs")) + } + } + + /// A bare specifier such as "node:path" is resolved by the JavaScript host at load + /// time, so packaging must not look for a file on disk or copy anything for it. + @Test func bareJavaScriptModuleIsNotCopied() throws { + try withTemporaryDirectory { temporaryDirectory, _ in + let skeleton = temporaryDirectory.appending(path: "BridgeJS.json") + let wasm = temporaryDirectory.appending(path: "main.wasm") + let plannerSource = temporaryDirectory.appending(path: "PackageToJS.swift") + let output = temporaryDirectory.appending(path: "output") + let intermediates = temporaryDirectory.appending(path: "intermediates") + + let bridgeSkeleton = BridgeJSSkeleton( + moduleName: "TestModule", + imported: ImportedModuleSkeleton( + children: [ + ImportedFileSkeleton( + functions: [ + ImportedFunctionSkeleton( + name: "basename", + from: .module("node:path"), + parameters: [], + returnType: .void + ) + ], + types: [] + ) + ] + ) + ) + try JSONEncoder().encode(bridgeSkeleton).write(to: skeleton) + try Data([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]).write(to: wasm) + try Data().write(to: plannerSource) + + let system = TestPackagingSystem() + let planner = PackagingPlanner( + options: PackageToJS.PackageOptions(), + packageId: "test", + intermediatesDir: BuildPath(absolute: intermediates.path), + selfPackageDir: BuildPath( + absolute: URL(fileURLWithPath: #filePath) + .deletingLastPathComponent() + .deletingLastPathComponent() + .deletingLastPathComponent() + .deletingLastPathComponent() + .path + ), + skeletons: [ + .init( + source: skeleton, + targetDirectory: temporaryDirectory + ) + ], + outputDir: BuildPath(absolute: output.path), + wasmProductArtifact: BuildPath(absolute: wasm.path), + wasmFilename: "main.wasm", + configuration: "debug", + triple: "wasm32-unknown-wasi", + selfPath: BuildPath(absolute: plannerSource.path), + system: system + ) + var make = MiniMake(printProgress: { _, _ in }) + let root = try planner.planBuild( + make: &make, + buildOptions: PackageToJS.BuildOptions( + product: "test", + noOptimize: false, + debugInfoFormat: .none, + packageOptions: PackageToJS.PackageOptions() + ) + ) + try make.build(output: root, scope: MiniMake.VariableScope(variables: [:])) + + #expect(!FileManager.default.fileExists(atPath: output.appending(path: "bridge-js-modules").path)) + let generated = try String( + contentsOf: output.appending(path: "bridge-js.js"), + encoding: .utf8 + ) + #expect(generated.contains("from \"node:path\"")) + } + } } diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript-into-Swift.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript-into-Swift.md index 6d06d4339..c6818b923 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript-into-Swift.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript-into-Swift.md @@ -29,7 +29,7 @@ You can bring JavaScript into Swift in three ways: - **Inject at initialization**: Declare in Swift and supply the implementation in `getImports()` (e.g. a `today()` function). - **Import from `globalThis`**: For APIs on the JavaScript global object (e.g. `console`, `document`), use `@JSGetter(from: .global)` so they are read from `globalThis` and you don't pass them in `getImports()`. -- **Ship an ECMAScript module**: Use `from: .module("/path/from/target/root.js")` on a top-level function/getter or `@JSClass`. The leading `/` denotes the Swift target root; it is not a filesystem-absolute path. BridgeJS copies the referenced file into the generated package, so it is not supplied through `getImports()`. +- **Ship an ECMAScript module**: Use `from: .snippet("/path/from/target/root.js")` on a top-level function/getter or `@JSClass`. The leading `/` denotes the Swift target root; it is not a filesystem-absolute path. BridgeJS copies the referenced file into the generated package, so it is not supplied through `getImports()`. Exclude the directory containing `.js` or `.mjs` modules from the Swift target to avoid SwiftPM's unhandled-file warning. See for an example. diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Class.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Class.md index 185b47d1f..7c6ae5a03 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Class.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Class.md @@ -36,7 +36,7 @@ export class Greeter { ``` ```swift -@JSClass(from: .module("/JavaScript/greeter.js")) +@JSClass(from: .snippet("/JavaScript/greeter.js")) struct Greeter { @JSFunction init(_ name: String) throws(JSException) @JSFunction static func named(_ name: String) throws(JSException) -> Greeter @@ -44,6 +44,18 @@ struct Greeter { } ``` +To wrap a class exported by an installed npm package, use `from: .module(...)`. Pass `jsName: .default` when the class is the module's default export: + +```swift +@JSClass(jsName: "File", from: .module("@bjorn3/browser_wasi_shim")) +struct WasiFile { + @JSFunction init(_ data: JSObject) throws(JSException) + @JSGetter var size: Int64 +} +``` + +Nothing is copied for these, and you are responsible for making them resolvable at load time; see . + The path's leading `/` denotes the Swift target root, not the filesystem root. The module's named class export is the root for construction and static methods. Instance methods, getters, and setters operate on the wrapped object and must not specify their own `from:` argument. Use `jsName` on `@JSClass` to select a differently named class export. JavaScript inheritance may be implemented normally in the module; the Swift declaration describes the API visible on the exported class and its instances. ### 2. Wire the JavaScript side diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Function.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Function.md index c57aeda03..1b2be6cb0 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Function.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Function.md @@ -25,12 +25,24 @@ export function add(a, b) { return a + b; } ``` ```swift -@JSFunction(from: .module("/JavaScript/math.js")) +@JSFunction(from: .snippet("/JavaScript/math.js")) func add(_ a: Double, _ b: Double) throws(JSException) -> Double ``` The leading `/` denotes the Swift target root, not the filesystem root. BridgeJS copies explicitly referenced modules into the generated PackageToJS package. Multiple declarations may reference the same file; it is copied and imported only once. `jsName` selects a differently named export, otherwise BridgeJS uses the normalized Swift name. +To call a Node builtin or an installed npm package instead, use `from: .module(...)`. The specifier is passed to the JavaScript module resolver verbatim: + +```swift +@JSFunction(jsName: "basename", from: .module("node:path")) +func basename(_ path: String) throws(JSException) -> String + +@JSFunction(jsName: "chunk", from: .module("lodash/fp")) +func chunk(_ input: JSObject, _ size: Int) throws(JSException) -> JSObject +``` + +Nothing is copied for these, and you are responsible for making them resolvable at load time; see for what that entails. To call the module's default export instead of a named one, pass `jsName: .default`. + SwiftPM does not know what to do with `.js`/`.mjs` files inside a target, so exclude the directory holding them to avoid an "unhandled files" warning: ```swift diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Variable.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Variable.md index 6825875dd..3a92a690e 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Variable.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Variable.md @@ -25,12 +25,24 @@ export const environment = "production"; ``` ```swift -@JSGetter(jsName: "environment", from: .module("/JavaScript/config.js")) +@JSGetter(jsName: "environment", from: .snippet("/JavaScript/config.js")) var currentEnvironment: String ``` The path's leading `/` denotes the Swift target root, not the filesystem root. Module exports are read-only through this API. Top-level `@JSSetter` remains unsupported. +A getter can also read from an external module with `from: .module(...)`, covering Node builtins and installed npm packages. Pass `jsName: .default` to read the module's default export, which is how many npm packages expose their main value: + +```swift +@JSGetter(jsName: "version", from: .module("some-package")) +var packageVersion: String + +@JSGetter(jsName: .default, from: .module("some-package")) +var packageDefault: JSObject +``` + +Nothing is copied for these, and you are responsible for making them resolvable at load time; see . + ### 2. Add a setter for writable variables (optional) If the JavaScript property is writable and you need to set it from Swift, add a corresponding `@JSSetter` function. Property setters are exposed as functions (e.g. `setMyConfig(_:)`) because Swift property setters cannot `throw`. diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Unsupported-Features.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Unsupported-Features.md index 238bc8687..74588b06b 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Unsupported-Features.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Unsupported-Features.md @@ -6,13 +6,26 @@ Limitations and unsupported patterns when using BridgeJS. BridgeJS generates glue code per Swift target (module). Some patterns that are valid in Swift or TypeScript are not supported across the bridge today. This article summarizes the main limitations so you can design your APIs accordingly. -## File-backed JavaScript modules +## JavaScript modules -Files referenced by `JSImportFrom.module` must be nonempty `.js` or `.mjs` paths beginning with `/`. This leading slash denotes the Swift target root, not the filesystem root. Files must remain within that Swift target. Only explicitly referenced files are copied. BridgeJS does not discover or rewrite an imported module's dependency graph, so referenced files should currently be self-contained. +Two origins read from an ECMAScript module, and which one you use depends on who owns the JavaScript. -Generated packages use static ECMAScript module imports. This works with the existing PackageToJS browser and Node ESM entry points. CommonJS and classic non-module script output are not generated or translated. +`JSImportFrom.snippet` names a JavaScript file you ship inside the Swift target, such as `.snippet("/Modules/utils.mjs")`. The path must begin with `/` and end in `.js` or `.mjs`. That leading slash denotes the Swift target root, not the filesystem root, and the file must remain within that Swift target. Only explicitly referenced files are copied into the generated package. BridgeJS does not discover or rewrite a snippet's dependency graph, so snippets should currently be self-contained. -Module origins apply to top-level `@JSFunction`, top-level `@JSGetter`, and an entire `@JSClass`. Per-member origins, top-level setters, inline JavaScript source, package-root-relative paths, and per-member module overrides are not supported. +`JSImportFrom.module` names an external module resolved by the JavaScript host — for example `.module("node:path")`, `.module("lodash/fp")`, or `.module("@scope/package")`. Because resolution is host-defined, BridgeJS deliberately performs no build-time validation of these specifiers beyond rejecting the empty string, relative specifiers (`./x`, `../x`), and rooted paths (which are snippets). This has several consequences you are responsible for: + +- Importing a `node:`-prefixed builtin makes the generated package Node-only. It will fail to load in a browser. +- An npm package must be resolvable at load time — either from the generated output directory (Node walks up to the nearest `node_modules`), or through your bundler's aliasing or an import map. +- BridgeJS does not add anything to the generated `package.json`. Installing the dependency is up to you, and no version is inferred. +- A specifier is not verified to exist until the JavaScript host loads the generated module, so a typo surfaces as a resolution error from your JavaScript toolchain rather than a Swift compile error. + +Generated packages use static ECMAScript module imports. This works with the existing PackageToJS browser and Node ESM entry points. CommonJS and classic non-module script output are not generated or translated. Note that named exports of a CommonJS package are only importable when Node can statically detect them; when in doubt, use `jsName: .default` and reach members through the default export. + +A module export is called through a named import, so `this` is `undefined` inside the called function rather than the module namespace object. A function that reaches sibling exports through `this` — which happens in CommonJS packages consumed through Node's ESM interop — will fail. Import the default export and call the member through it when a package needs that receiver. + +Both origins apply to top-level `@JSFunction`, top-level `@JSGetter`, and an entire `@JSClass`. Per-member origins, top-level setters, inline JavaScript source, package-root-relative paths, and per-member overrides are not supported. `jsName: .default` is likewise only valid on those three declaration forms and only together with `from: .module(...)` or `from: .snippet(...)`; it cannot be used on `@JSSetter`, because ECMAScript module bindings are read-only. + +The TypeScript-definition workflow (`bridge-js.d.ts`) always imports from `globalThis` and cannot yet target a snippet or module origin. To import from either, declare the API with the macros instead. ## Type usage crossing module boundary diff --git a/Sources/JavaScriptKit/Macros.swift b/Sources/JavaScriptKit/Macros.swift index 7a1bb4091..2750f8268 100644 --- a/Sources/JavaScriptKit/Macros.swift +++ b/Sources/JavaScriptKit/Macros.swift @@ -9,13 +9,47 @@ public enum JSEnumStyle: String { /// Controls where BridgeJS reads imported JS values from. /// /// - `global`: Read from `globalThis`. -/// - `module`: Read a named export from an ECMAScript module file rooted at the Swift target. +/// - `snippet`: Read from a JavaScript file shipped inside the Swift target. +/// - `module`: Read from an external ECMAScript module. public enum JSImportFrom { case global - /// Read from an ECMAScript module file using a `/`-prefixed path rooted at the Swift target directory. + /// Read from a JavaScript file that ships with the Swift target. + /// + /// The path is rooted at the Swift target directory and must begin with `/` + /// and end in `.js` or `.mjs`, e.g. `.snippet("/Modules/utils.mjs")`. The + /// leading `/` denotes the target root, not the filesystem root, and the file + /// must exist inside that target. BridgeJS copies referenced files into the + /// generated package. + case snippet(String) + /// Read from an external ECMAScript module, resolved by the JavaScript host. + /// + /// The value is passed to the module resolver verbatim, which covers Node + /// built-in modules and installed packages, e.g. `.module("node:path")`, + /// `.module("lodash/fp")`, or `.module("@scope/package")`. Nothing is copied + /// for these, and making them resolvable at load time is up to you. + /// + /// To reference a file in your own target, use ``JSImportFrom/snippet(_:)``. case module(String) } +/// Names the JavaScript member that an imported declaration refers to. +/// +/// A string literal is accepted directly, so `jsName: "basename"` means +/// ``JSName/name(_:)`` with that value. +public enum JSName: ExpressibleByStringLiteral { + /// A member looked up by name. + case name(String) + /// The default export of an ECMAScript module. + /// + /// Only valid on a top-level `@JSFunction`, `@JSGetter`, or `@JSClass` + /// that also specifies `from: .module(...)` or `from: .snippet(...)`. + case `default` + + public init(stringLiteral value: String) { + self = .name(value) + } +} + /// A macro that exposes Swift functions, classes, and methods to JavaScript. /// /// Apply this macro to Swift declarations that you want to make callable from JavaScript: @@ -144,9 +178,11 @@ public macro JS( /// /// - Parameter from: Selects where the property is read from. /// Use `.global` to read from `globalThis` (e.g. `console`, `document`). -/// Use `.module("/path/to/module.js")` to read a named export from a file rooted at the Swift target. +/// Use `.snippet("/path/to/module.js")` to read a named export from a file rooted at the Swift target, +/// or `.module("node:os")` to read a named export from an external module. +/// Pass `jsName: .default` to read the module's default export. @attached(accessor) -public macro JSGetter(jsName: String? = nil, from: JSImportFrom? = nil) = +public macro JSGetter(jsName: JSName? = nil, from: JSImportFrom? = nil) = #externalMacro(module: "BridgeJSMacros", type: "JSGetterMacro") /// A macro that generates a Swift function body that writes a value to JavaScript. @@ -164,7 +200,7 @@ public macro JSGetter(jsName: String? = nil, from: JSImportFrom? = nil) = /// @JSSetter func setName(_ value: String) throws (JSException) /// ``` @attached(body) -public macro JSSetter(jsName: String? = nil, from: JSImportFrom? = nil) = +public macro JSSetter(jsName: JSName? = nil, from: JSImportFrom? = nil) = #externalMacro(module: "BridgeJSMacros", type: "JSSetterMacro") /// A macro that generates a Swift function body that calls a JavaScript function. @@ -184,9 +220,11 @@ public macro JSSetter(jsName: String? = nil, from: JSImportFrom? = nil) = /// If not provided, the Swift function name is used. /// - Parameter from: Selects where the function is looked up from. /// Use `.global` to call a function on `globalThis` (e.g. `setTimeout`). -/// Use `.module("/path/to/module.js")` to call a named export from a file rooted at the Swift target. +/// Use `.snippet("/path/to/module.js")` to call a named export from a file rooted at the Swift target, +/// or `.module("node:path")` to call a named export from an external module. +/// Pass `jsName: .default` to call the module's default export. @attached(body) -public macro JSFunction(jsName: String? = nil, from: JSImportFrom? = nil) = +public macro JSFunction(jsName: JSName? = nil, from: JSImportFrom? = nil) = #externalMacro(module: "BridgeJSMacros", type: "JSFunctionMacro") /// A macro that adds bridging members for a Swift type that represents a JavaScript class. @@ -209,8 +247,10 @@ public macro JSFunction(jsName: String? = nil, from: JSImportFrom? = nil) = /// /// - Parameter from: Selects where the constructor is looked up from. /// Use `.global` to construct globals like `WebSocket` via `globalThis`. -/// Use `.module("/path/to/module.js")` to construct a named class export from a file rooted at the Swift target. +/// Use `.snippet("/path/to/module.js")` to construct a named class export from a file rooted at the Swift target, +/// or `.module("@scope/package")` to construct a named class export from an external module. +/// Pass `jsName: .default` to construct the module's default export. @attached(member, names: named(jsObject), named(init(unsafelyWrapping:))) @attached(extension, conformances: _JSBridgedClass) -public macro JSClass(jsName: String? = nil, from: JSImportFrom? = nil) = +public macro JSClass(jsName: JSName? = nil, from: JSImportFrom? = nil) = #externalMacro(module: "BridgeJSMacros", type: "JSClassMacro") diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 39de49ca0..5337e923a 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -17010,6 +17010,119 @@ func _$JSClassSupportImports_makeJSClassWithArrayMembers(_ numbers: [Int], _ lab return JSClassWithArrayMembers.bridgeJSLiftReturn(ret) } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_defaultExport_get") +fileprivate func bjs_defaultExport_get_extern() -> Int32 +#else +fileprivate func bjs_defaultExport_get_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_defaultExport_get() -> Int32 { + return bjs_defaultExport_get_extern() +} + +func _$defaultExport_get() throws(JSException) -> JSObject { + let ret = bjs_defaultExport_get() + if let error = _swift_js_take_exception() { + throw error + } + return JSObject.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_nodeBasename") +fileprivate func bjs_nodeBasename_extern(_ pathBytes: Int32, _ pathLength: Int32) -> Int32 +#else +fileprivate func bjs_nodeBasename_extern(_ pathBytes: Int32, _ pathLength: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_nodeBasename(_ pathBytes: Int32, _ pathLength: Int32) -> Int32 { + return bjs_nodeBasename_extern(pathBytes, pathLength) +} + +func _$nodeBasename(_ path: String) throws(JSException) -> String { + let ret0 = path.bridgeJSWithLoweredParameter { (pathBytes, pathLength) in + let ret = bjs_nodeBasename(pathBytes, pathLength) + return ret + } + let ret = ret0 + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_nodeJoin") +fileprivate func bjs_nodeJoin_extern(_ lhsBytes: Int32, _ lhsLength: Int32, _ rhsBytes: Int32, _ rhsLength: Int32) -> Int32 +#else +fileprivate func bjs_nodeJoin_extern(_ lhsBytes: Int32, _ lhsLength: Int32, _ rhsBytes: Int32, _ rhsLength: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_nodeJoin(_ lhsBytes: Int32, _ lhsLength: Int32, _ rhsBytes: Int32, _ rhsLength: Int32) -> Int32 { + return bjs_nodeJoin_extern(lhsBytes, lhsLength, rhsBytes, rhsLength) +} + +func _$nodeJoin(_ lhs: String, _ rhs: String) throws(JSException) -> String { + let ret0 = lhs.bridgeJSWithLoweredParameter { (lhsBytes, lhsLength) in + let ret1 = rhs.bridgeJSWithLoweredParameter { (rhsBytes, rhsLength) in + let ret = bjs_nodeJoin(lhsBytes, lhsLength, rhsBytes, rhsLength) + return ret + } + return ret1 + } + let ret = ret0 + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_WasiFile_init") +fileprivate func bjs_WasiFile_init_extern(_ data: Int32) -> Int32 +#else +fileprivate func bjs_WasiFile_init_extern(_ data: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WasiFile_init(_ data: Int32) -> Int32 { + return bjs_WasiFile_init_extern(data) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_WasiFile_size_get") +fileprivate func bjs_WasiFile_size_get_extern(_ self: Int32) -> Int64 +#else +fileprivate func bjs_WasiFile_size_get_extern(_ self: Int32) -> Int64 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_WasiFile_size_get(_ self: Int32) -> Int64 { + return bjs_WasiFile_size_get_extern(self) +} + +func _$WasiFile_init(_ data: JSObject) throws(JSException) -> JSObject { + let dataValue = data.bridgeJSLowerParameter() + let ret = bjs_WasiFile_init(dataValue) + if let error = _swift_js_take_exception() { + throw error + } + return JSObject.bridgeJSLiftReturn(ret) +} + +func _$WasiFile_size_get(_ self: JSObject) throws(JSException) -> Int64 { + let selfValue = self.bridgeJSLowerParameter() + let ret = bjs_WasiFile_size_get(selfValue) + if let error = _swift_js_take_exception() { + throw error + } + return Int64.bridgeJSLiftReturn(ret) +} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_moduleVersion_get") fileprivate func bjs_moduleVersion_get_extern() -> Int32 diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index e0c30c428..ac0d9914e 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -24183,7 +24183,143 @@ "isStatic" : false, "isThrows" : true }, - "from" : "\/Modules\/JSImportModule.mjs", + "from" : { + "kind" : "module", + "specifier" : "node:path" + }, + "jsName" : "basename", + "name" : "nodeBasename", + "parameters" : [ + { + "name" : "path", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "from" : { + "kind" : "module", + "specifier" : "node:path" + }, + "jsName" : "join", + "name" : "nodeJoin", + "parameters" : [ + { + "name" : "lhs", + "type" : { + "string" : { + + } + } + }, + { + "name" : "rhs", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + } + } + ], + "globalGetters" : [ + { + "accessLevel" : "internal", + "from" : { + "kind" : "snippet", + "path" : "\/Modules\/DefaultExport.mjs" + }, + "jsName" : "default", + "name" : "defaultExport", + "type" : { + "jsObject" : { + + } + } + } + ], + "types" : [ + { + "accessLevel" : "internal", + "constructor" : { + "accessLevel" : "internal", + "parameters" : [ + { + "name" : "data", + "type" : { + "jsObject" : { + + } + } + } + ] + }, + "from" : { + "kind" : "module", + "specifier" : "@bjorn3\/browser_wasi_shim" + }, + "getters" : [ + { + "accessLevel" : "internal", + "name" : "size", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "w64" + } + } + } + } + ], + "jsName" : "File", + "methods" : [ + + ], + "name" : "WasiFile", + "setters" : [ + + ], + "staticMethods" : [ + + ] + } + ] + }, + { + "functions" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "from" : { + "kind" : "snippet", + "path" : "\/Modules\/JSImportModule.mjs" + }, "name" : "moduleAdd", "parameters" : [ { @@ -24225,7 +24361,10 @@ "isStatic" : false, "isThrows" : true }, - "from" : "\/Modules\/JSImportModule.mjs", + "from" : { + "kind" : "snippet", + "path" : "\/Modules\/JSImportModule.mjs" + }, "jsName" : "renamedFunction", "name" : "moduleRenamed", "parameters" : [ @@ -24244,7 +24383,10 @@ "isStatic" : false, "isThrows" : true }, - "from" : "\/Modules\/JSImportModule.mjs", + "from" : { + "kind" : "snippet", + "path" : "\/Modules\/JSImportModule.mjs" + }, "name" : "moduleThrow", "parameters" : [ @@ -24259,7 +24401,10 @@ "globalGetters" : [ { "accessLevel" : "internal", - "from" : "\/Modules\/JSImportModule.mjs", + "from" : { + "kind" : "snippet", + "path" : "\/Modules\/JSImportModule.mjs" + }, "jsName" : "version", "name" : "moduleVersion", "type" : { @@ -24288,7 +24433,10 @@ } ] }, - "from" : "\/Modules\/ModuleCounter.mjs", + "from" : { + "kind" : "snippet", + "path" : "\/Modules\/ModuleCounter.mjs" + }, "getters" : [ { "accessLevel" : "internal", diff --git a/Tests/BridgeJSRuntimeTests/JSImportBareModuleTests.swift b/Tests/BridgeJSRuntimeTests/JSImportBareModuleTests.swift new file mode 100644 index 000000000..36c22913f --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/JSImportBareModuleTests.swift @@ -0,0 +1,40 @@ +import JavaScriptKit +import XCTest + +// A Node built-in module. Nothing is copied into the generated package for this; +// the generated JavaScript imports "node:path" directly and Node resolves it. +@JSFunction(jsName: "basename", from: .module("node:path")) +func nodeBasename(_ path: String) throws(JSException) -> String + +@JSFunction(jsName: "join", from: .module("node:path")) +func nodeJoin(_ lhs: String, _ rhs: String) throws(JSException) -> String + +// An npm package, resolved through node_modules rather than being built into the runtime. +@JSClass(jsName: "File", from: .module("@bjorn3/browser_wasi_shim")) +struct WasiFile { + @JSFunction init(_ data: JSObject) throws(JSException) + @JSGetter var size: Int64 +} + +// The default export of a module, reached with `jsName: .default`. +@JSGetter(jsName: .default, from: .snippet("/Modules/DefaultExport.mjs")) +var defaultExport: JSObject + +final class JSImportBareModuleTests: XCTestCase { + func testNodeBuiltinModule() throws { + XCTAssertEqual(try nodeBasename("/a/b/c.txt"), "c.txt") + XCTAssertEqual(try nodeJoin("a", "b"), "a/b") + } + + func testNpmPackageClass() throws { + let bytes = JSObject.global.Uint8Array.function!.new(3) + let file = try WasiFile(bytes) + XCTAssertEqual(try file.size, 3) + } + + func testDefaultExport() throws { + let module = try defaultExport + XCTAssertEqual(module.label.string, "from the default export") + XCTAssertEqual(module.triple!(7).number, 21) + } +} diff --git a/Tests/BridgeJSRuntimeTests/JSImportModuleTests.swift b/Tests/BridgeJSRuntimeTests/JSImportModuleTests.swift index 4cc228328..9efb64161 100644 --- a/Tests/BridgeJSRuntimeTests/JSImportModuleTests.swift +++ b/Tests/BridgeJSRuntimeTests/JSImportModuleTests.swift @@ -1,19 +1,19 @@ import JavaScriptKit import XCTest -@JSFunction(from: .module("/Modules/JSImportModule.mjs")) +@JSFunction(from: .snippet("/Modules/JSImportModule.mjs")) func moduleAdd(_ lhs: Int, _ rhs: Int) throws(JSException) -> Int -@JSFunction(jsName: "renamedFunction", from: .module("/Modules/JSImportModule.mjs")) +@JSFunction(jsName: "renamedFunction", from: .snippet("/Modules/JSImportModule.mjs")) func moduleRenamed() throws(JSException) -> String -@JSFunction(from: .module("/Modules/JSImportModule.mjs")) +@JSFunction(from: .snippet("/Modules/JSImportModule.mjs")) func moduleThrow() throws(JSException) -@JSGetter(jsName: "version", from: .module("/Modules/JSImportModule.mjs")) +@JSGetter(jsName: "version", from: .snippet("/Modules/JSImportModule.mjs")) var moduleVersion: String -@JSClass(from: .module("/Modules/ModuleCounter.mjs")) +@JSClass(from: .snippet("/Modules/ModuleCounter.mjs")) struct ModuleCounter { @JSFunction init(_ value: Int) throws(JSException) @JSFunction static func create(_ value: Int) throws(JSException) -> ModuleCounter diff --git a/Tests/BridgeJSRuntimeTests/Modules/DefaultExport.mjs b/Tests/BridgeJSRuntimeTests/Modules/DefaultExport.mjs new file mode 100644 index 000000000..295129c36 --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/Modules/DefaultExport.mjs @@ -0,0 +1,6 @@ +export default { + label: "from the default export", + triple(value) { + return value * 3; + }, +}; From 0e11da502d9601712fae1c8d8d7ae6ed21676a70 Mon Sep 17 00:00:00 2001 From: Yuta Saito Date: Mon, 10 Aug 2026 01:54:07 +0100 Subject: [PATCH 34/50] BridgeJS: Unify @JS struct parameter lowering onto the stack ABI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit bridgeJSLowerParameter for structs used toJSObject(), so Swift→JS callbacks discarded the stack and JS lift() read garbage. Match arrays: stack-push on lower, and use the same ABI for ImportTS non-optional structs. --- .../Sources/BridgeJSCore/ImportTS.swift | 29 +-- .../Sources/BridgeJSLink/JSGlueGen.swift | 36 ++- .../BridgeJSCodegenTests/Async.swift | 12 +- .../BridgeJSCodegenTests/SwiftClosure.swift | 12 +- .../SwiftStructImports.swift | 14 +- .../__Snapshots__/BridgeJSLinkTests/Async.js | 7 +- .../BridgeJSLinkTests/SwiftClosure.js | 7 +- .../BridgeJSLinkTests/SwiftStructImports.js | 9 +- .../JavaScriptKit/BridgeJSIntrinsics.swift | 13 +- .../BridgeJSRuntimeTests/ExportAPITests.swift | 9 + .../Generated/BridgeJS.swift | 209 +++++++++++++++--- .../Generated/JavaScript/BridgeJS.json | 98 ++++++++ .../JavaScript/ClosureSupportTests.mjs | 18 ++ 13 files changed, 356 insertions(+), 117 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift index 474f1a75f..286352915 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift @@ -933,19 +933,10 @@ extension BridgeType { case .associatedValueEnum: return LoweringParameterInfo(loweredParameters: [("caseId", .i32)]) case .swiftStruct: - switch context { - case .importTS: - // Swift structs are bridged as JS objects (object IDs) in imported signatures. - return LoweringParameterInfo(loweredParameters: [("objectId", .i32)]) - case .exportSwift: - return LoweringParameterInfo(loweredParameters: []) - } + // `@JS struct` parameters always use the stack ABI (same as arrays/dictionaries). + return LoweringParameterInfo(loweredParameters: []) case .namespaceEnum: throw BridgeJSCoreError("Namespace enums cannot be used as parameters") - case .nullable(.swiftStruct, _) where context == .importTS: - // Optional `@JS struct`s bridge through the stack (isSome discriminator + fields), - // like optional arrays/dictionaries, rather than the non-optional object-id ABI. - return LoweringParameterInfo(loweredParameters: [("isSome", .i32)]) case .nullable(let wrappedType, _): let wrappedInfo = try wrappedType.loweringParameterInfo(context: context) var params = [("isSome", WasmCoreType.i32)] @@ -1005,24 +996,16 @@ extension BridgeType { case .associatedValueEnum: return LiftingReturnInfo(valueToLift: .i32) case .swiftStruct: - switch context { - case .importTS: - // Swift structs are bridged as JS objects (object IDs) in imported signatures. - return LiftingReturnInfo(valueToLift: .i32) - case .exportSwift: - return LiftingReturnInfo(valueToLift: nil) - } + // `@JS struct` returns always use the stack ABI (same as arrays/dictionaries). + return LiftingReturnInfo(valueToLift: nil) case .namespaceEnum: throw BridgeJSCoreError("Namespace enums cannot be used as return values") case .nullable(let wrappedType, _): - // jsObject and `@JS struct` use the stack ABI for optionals — the thunk returns - // void and the value (plus isSome discriminator) flows through the stacks. + // jsObject uses the stack ABI for optionals — the thunk returns void and the + // value (plus isSome discriminator) flows through the stacks. if case .jsObject = wrappedType { return LiftingReturnInfo(valueToLift: nil) } - if case .swiftStruct = wrappedType, context == .importTS { - return LiftingReturnInfo(valueToLift: nil) - } let wrappedInfo = try wrappedType.liftingReturnInfo(context: context) return LiftingReturnInfo(valueToLift: wrappedInfo.valueToLift) case .array, .dictionary: diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift index 782988751..1cf0fa298 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift @@ -1437,23 +1437,18 @@ struct IntrinsicJSFragment: Sendable { } ) case .swiftStruct(let fullName): - switch context { - case .importTS: - return .jsObjectLiftRetainedObjectId - case .exportSwift: - let base = fullName.replacingOccurrences(of: ".", with: "_") - return IntrinsicJSFragment( - parameters: [], - printCode: { arguments, context in - let (scope, printer) = (context.scope, context.printer) - let resultVar = scope.variable("structValue") - printer.write( - "const \(resultVar) = \(JSGlueVariableScope.reservedStructHelpers).\(base).lift();" - ) - return [resultVar] - } - ) - } + let base = fullName.replacingOccurrences(of: ".", with: "_") + return IntrinsicJSFragment( + parameters: [], + printCode: { arguments, context in + let (scope, printer) = (context.scope, context.printer) + let resultVar = scope.variable("structValue") + printer.write( + "const \(resultVar) = \(JSGlueVariableScope.reservedStructHelpers).\(base).lift();" + ) + return [resultVar] + } + ) case .closure: return IntrinsicJSFragment( parameters: ["funcRef"], @@ -1497,12 +1492,7 @@ struct IntrinsicJSFragment: Sendable { case .associatedValueEnum(let fullName): return associatedValueLowerReturn(fullName: fullName) case .swiftStruct(let fullName): - switch context { - case .importTS: - return .jsObjectLowerReturn - case .exportSwift: - return swiftStructLowerReturn(fullName: fullName) - } + return swiftStructLowerReturn(fullName: fullName) case .closure: return IntrinsicJSFragment( parameters: ["value"], diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift index 230676e67..f2223ee7c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift @@ -507,20 +507,20 @@ func _$Promise_resolve_8JSObjectC(_ promise: JSObject, _ value: JSObject) throws #if arch(wasm32) @_extern(wasm, module: "bjs", name: "promise_resolve_TestModule_10AsyncPointV") -fileprivate func promise_resolve_TestModule_10AsyncPointV_extern(_ promise: Int32, _ value: Int32) -> Void +fileprivate func promise_resolve_TestModule_10AsyncPointV_extern(_ promise: Int32) -> Void #else -fileprivate func promise_resolve_TestModule_10AsyncPointV_extern(_ promise: Int32, _ value: Int32) -> Void { +fileprivate func promise_resolve_TestModule_10AsyncPointV_extern(_ promise: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func promise_resolve_TestModule_10AsyncPointV(_ promise: Int32, _ value: Int32) -> Void { - return promise_resolve_TestModule_10AsyncPointV_extern(promise, value) +@inline(never) fileprivate func promise_resolve_TestModule_10AsyncPointV(_ promise: Int32) -> Void { + return promise_resolve_TestModule_10AsyncPointV_extern(promise) } func _$Promise_resolve_10AsyncPointV(_ promise: JSObject, _ value: AsyncPoint) throws(JSException) -> Void { - let valueObjectId = value.bridgeJSLowerParameter() + let _ = value.bridgeJSLowerParameter() let promiseValue = promise.bridgeJSLowerParameter() - promise_resolve_TestModule_10AsyncPointV(promiseValue, valueObjectId) + promise_resolve_TestModule_10AsyncPointV(promiseValue) if let error = _swift_js_take_exception() { throw error } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift index e1f10ab97..c7ac02fb1 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift @@ -2684,20 +2684,20 @@ func _$Promise_resolve_SS(_ promise: JSObject, _ value: String) throws(JSExcepti #if arch(wasm32) @_extern(wasm, module: "bjs", name: "promise_resolve_TestModule_6AnimalV") -fileprivate func promise_resolve_TestModule_6AnimalV_extern(_ promise: Int32, _ value: Int32) -> Void +fileprivate func promise_resolve_TestModule_6AnimalV_extern(_ promise: Int32) -> Void #else -fileprivate func promise_resolve_TestModule_6AnimalV_extern(_ promise: Int32, _ value: Int32) -> Void { +fileprivate func promise_resolve_TestModule_6AnimalV_extern(_ promise: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func promise_resolve_TestModule_6AnimalV(_ promise: Int32, _ value: Int32) -> Void { - return promise_resolve_TestModule_6AnimalV_extern(promise, value) +@inline(never) fileprivate func promise_resolve_TestModule_6AnimalV(_ promise: Int32) -> Void { + return promise_resolve_TestModule_6AnimalV_extern(promise) } func _$Promise_resolve_6AnimalV(_ promise: JSObject, _ value: Animal) throws(JSException) -> Void { - let valueObjectId = value.bridgeJSLowerParameter() + let _ = value.bridgeJSLowerParameter() let promiseValue = promise.bridgeJSLowerParameter() - promise_resolve_TestModule_6AnimalV(promiseValue, valueObjectId) + promise_resolve_TestModule_6AnimalV(promiseValue) if let error = _swift_js_take_exception() { throw error } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.swift index 0e792ea14..38ec94c0d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.swift @@ -48,25 +48,25 @@ fileprivate func _bjs_struct_lift_Point_extern() -> Int32 { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_translate") -fileprivate func bjs_translate_extern(_ point: Int32, _ dx: Int32, _ dy: Int32) -> Int32 +fileprivate func bjs_translate_extern(_ dx: Int32, _ dy: Int32) -> Void #else -fileprivate func bjs_translate_extern(_ point: Int32, _ dx: Int32, _ dy: Int32) -> Int32 { +fileprivate func bjs_translate_extern(_ dx: Int32, _ dy: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_translate(_ point: Int32, _ dx: Int32, _ dy: Int32) -> Int32 { - return bjs_translate_extern(point, dx, dy) +@inline(never) fileprivate func bjs_translate(_ dx: Int32, _ dy: Int32) -> Void { + return bjs_translate_extern(dx, dy) } func _$translate(_ point: Point, _ dx: Int, _ dy: Int) throws(JSException) -> Point { let dyValue = dy.bridgeJSLowerParameter() let dxValue = dx.bridgeJSLowerParameter() - let pointObjectId = point.bridgeJSLowerParameter() - let ret = bjs_translate(pointObjectId, dxValue, dyValue) + let _ = point.bridgeJSLowerParameter() + bjs_translate(dxValue, dyValue) if let error = _swift_js_take_exception() { throw error } - return Point.bridgeJSLiftReturn(ret) + return Point.bridgeJSLiftReturn() } #if arch(wasm32) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js index 680da9c5e..9f2faf589 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js @@ -280,11 +280,10 @@ export async function createInstantiator(options, swift) { setException(error); } } - bjs["promise_resolve_TestModule_10AsyncPointV"] = function(promise, value) { + bjs["promise_resolve_TestModule_10AsyncPointV"] = function(promise) { try { - const value1 = swift.memory.getObject(value); - swift.memory.release(value); - swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(value1); + const structValue = structHelpers.AsyncPoint.lift(); + swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(structValue); } catch (error) { setException(error); } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js index f3b9d987c..62c2de8c6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js @@ -345,11 +345,10 @@ export async function createInstantiator(options, swift) { setException(error); } } - bjs["promise_resolve_TestModule_6AnimalV"] = function(promise, value) { + bjs["promise_resolve_TestModule_6AnimalV"] = function(promise) { try { - const value1 = swift.memory.getObject(value); - swift.memory.release(value); - swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(value1); + const structValue = structHelpers.Animal.lift(); + swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(structValue); } catch (error) { setException(error); } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js index 523861b9a..4a2e18d6b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js @@ -223,12 +223,11 @@ export async function createInstantiator(options, swift) { } bjs["swift_js_closure_unregister"] = function(funcRef) {} const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; - TestModule["bjs_translate"] = function bjs_translate(point, dx, dy) { + TestModule["bjs_translate"] = function bjs_translate(dx, dy) { try { - const value = swift.memory.getObject(point); - swift.memory.release(point); - let ret = imports.translate(value, dx, dy); - return swift.memory.retain(ret); + const structValue = structHelpers.Point.lift(); + let ret = imports.translate(structValue, dx, dy); + structHelpers.Point.lower(ret); } catch (error) { setException(error); } diff --git a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift index a07ca0152..4eeae4dac 100644 --- a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift +++ b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift @@ -1133,13 +1133,12 @@ where StackLiftResult == Self { } extension _BridgedSwiftStruct { - @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> Int32 { - return toJSObject().bridgeJSLowerReturn() - } - - @_spi(BridgeJS) public static func bridgeJSLiftReturn(_ objectId: Int32) -> Self { - let jsObject = JSObject.bridgeJSLiftReturn(objectId) - return Self(unsafelyCopying: jsObject) + /// Lower a struct parameter onto the shared stacks for the peer to `lift()`. + /// + /// Same convention as arrays/dictionaries. Use ``toJSObject()`` when a real JS object + /// representation is needed (e.g. `init(unsafelyCopying:)` round-trips). + @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() { + bridgeJSStackPush() } @_spi(BridgeJS) public static func bridgeJSLiftReturn() -> Self { diff --git a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift index 5a852a23d..8778c2c8e 100644 --- a/Tests/BridgeJSRuntimeTests/ExportAPITests.swift +++ b/Tests/BridgeJSRuntimeTests/ExportAPITests.swift @@ -1339,6 +1339,15 @@ enum GraphOperations { let noneStr = none.map { "(\($0.dx),\($0.dy))" } ?? "nil" return "\(someStr) | \(noneStr)" } + + /// Swift→JS callback with a struct parameter (ExportSwift stack ABI). + @JS func observeVector(_ callback: (Vector2D) -> Void) { + callback(Vector2D(dx: 1.5, dy: 2.5)) + } + + @JS func mapVector(_ vector: Vector2D, _ callback: (Vector2D) -> Vector2D) -> Vector2D { + return callback(vector) + } } @JS enum NestedStructGroupA { diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 5337e923a..ad6f3fa24 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -455,6 +455,130 @@ public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8JS #endif } +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8Vector2DV_8Vector2DV") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8Vector2DV_8Vector2DV_extern(_ callback: Int32) -> Void +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8Vector2DV_8Vector2DV_extern(_ callback: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8Vector2DV_8Vector2DV(_ callback: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8Vector2DV_8Vector2DV_extern(callback) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8Vector2DV_8Vector2DV") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8Vector2DV_8Vector2DV_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8Vector2DV_8Vector2DV_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8Vector2DV_8Vector2DV(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8Vector2DV_8Vector2DV_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTests8Vector2DV_8Vector2DV { + static func bridgeJSLift(_ callbackId: Int32) -> (Vector2D) -> Vector2D { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let _ = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8Vector2DV_8Vector2DV(callbackValue) + return Vector2D.bridgeJSLiftReturn() + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (Vector2D) -> Vector2D { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Vector2D) -> Vector2D) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8Vector2DV_8Vector2DV, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8Vector2DV_8Vector2DV") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8Vector2DV_8Vector2DV") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8Vector2DV_8Vector2DV(_ boxPtr: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Vector2D) -> Vector2D>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Vector2D.bridgeJSLiftParameter()) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8Vector2DV_y") +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8Vector2DV_y_extern(_ callback: Int32) -> Void +#else +fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8Vector2DV_y_extern(_ callback: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8Vector2DV_y(_ callback: Int32) -> Void { + return invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8Vector2DV_y_extern(callback) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8Vector2DV_y") +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8Vector2DV_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8Vector2DV_y_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8Vector2DV_y(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8Vector2DV_y_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_20BridgeJSRuntimeTests8Vector2DV_y { + static func bridgeJSLift(_ callbackId: Int32) -> (Vector2D) -> Void { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let _ = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() + invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8Vector2DV_y(callbackValue) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (Vector2D) -> Void { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Vector2D) -> Void) { + self.init( + makeClosure: make_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8Vector2DV_y, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8Vector2DV_y") +@_cdecl("invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8Vector2DV_y") +public func _invoke_swift_closure_BridgeJSRuntimeTests_20BridgeJSRuntimeTests8Vector2DV_y(_ boxPtr: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Vector2D) -> Void>>.fromOpaque(boxPtr).takeUnretainedValue().closure + closure(Vector2D.bridgeJSLiftParameter()) + #else + fatalError("Only available on WebAssembly") + #endif +} + #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9APIResultO_SS") fileprivate func invoke_js_callback_BridgeJSRuntimeTests_20BridgeJSRuntimeTests9APIResultO_SS_extern(_ callback: Int32, _ param0: Int32) -> Int32 @@ -12933,6 +13057,27 @@ public func _bjs_TextProcessor_processOptionalVector(_ _self: UnsafeMutableRawPo #endif } +@_expose(wasm, "bjs_TextProcessor_observeVector") +@_cdecl("bjs_TextProcessor_observeVector") +public func _bjs_TextProcessor_observeVector(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { + #if arch(wasm32) + TextProcessor.bridgeJSLiftParameter(_self).observeVector(_: _BJS_Closure_20BridgeJSRuntimeTests8Vector2DV_y.bridgeJSLift(callback)) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_TextProcessor_mapVector") +@_cdecl("bjs_TextProcessor_mapVector") +public func _bjs_TextProcessor_mapVector(_ _self: UnsafeMutableRawPointer, _ callback: Int32) -> Void { + #if arch(wasm32) + let ret = TextProcessor.bridgeJSLiftParameter(_self).mapVector(_: Vector2D.bridgeJSLiftParameter(), _: _BJS_Closure_20BridgeJSRuntimeTests8Vector2DV_8Vector2DV.bridgeJSLift(callback)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_TextProcessor_deinit") @_cdecl("bjs_TextProcessor_deinit") public func _bjs_TextProcessor_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { @@ -13781,20 +13926,20 @@ func _$Promise_resolve_Sq18AsyncPayloadResultO(_ promise: JSObject, _ value: Opt #if arch(wasm32) @_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_11PublicPointV") -fileprivate func promise_resolve_BridgeJSRuntimeTests_11PublicPointV_extern(_ promise: Int32, _ value: Int32) -> Void +fileprivate func promise_resolve_BridgeJSRuntimeTests_11PublicPointV_extern(_ promise: Int32) -> Void #else -fileprivate func promise_resolve_BridgeJSRuntimeTests_11PublicPointV_extern(_ promise: Int32, _ value: Int32) -> Void { +fileprivate func promise_resolve_BridgeJSRuntimeTests_11PublicPointV_extern(_ promise: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_11PublicPointV(_ promise: Int32, _ value: Int32) -> Void { - return promise_resolve_BridgeJSRuntimeTests_11PublicPointV_extern(promise, value) +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_11PublicPointV(_ promise: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_11PublicPointV_extern(promise) } func _$Promise_resolve_11PublicPointV(_ promise: JSObject, _ value: PublicPoint) throws(JSException) -> Void { - let valueObjectId = value.bridgeJSLowerParameter() + let _ = value.bridgeJSLowerParameter() let promiseValue = promise.bridgeJSLowerParameter() - promise_resolve_BridgeJSRuntimeTests_11PublicPointV(promiseValue, valueObjectId) + promise_resolve_BridgeJSRuntimeTests_11PublicPointV(promiseValue) if let error = _swift_js_take_exception() { throw error } } @@ -13802,20 +13947,20 @@ func _$Promise_resolve_11PublicPointV(_ promise: JSObject, _ value: PublicPoint) #if arch(wasm32) @_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_7ContactV") -fileprivate func promise_resolve_BridgeJSRuntimeTests_7ContactV_extern(_ promise: Int32, _ value: Int32) -> Void +fileprivate func promise_resolve_BridgeJSRuntimeTests_7ContactV_extern(_ promise: Int32) -> Void #else -fileprivate func promise_resolve_BridgeJSRuntimeTests_7ContactV_extern(_ promise: Int32, _ value: Int32) -> Void { +fileprivate func promise_resolve_BridgeJSRuntimeTests_7ContactV_extern(_ promise: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_7ContactV(_ promise: Int32, _ value: Int32) -> Void { - return promise_resolve_BridgeJSRuntimeTests_7ContactV_extern(promise, value) +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_7ContactV(_ promise: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_7ContactV_extern(promise) } func _$Promise_resolve_7ContactV(_ promise: JSObject, _ value: Contact) throws(JSException) -> Void { - let valueObjectId = value.bridgeJSLowerParameter() + let _ = value.bridgeJSLowerParameter() let promiseValue = promise.bridgeJSLowerParameter() - promise_resolve_BridgeJSRuntimeTests_7ContactV(promiseValue, valueObjectId) + promise_resolve_BridgeJSRuntimeTests_7ContactV(promiseValue) if let error = _swift_js_take_exception() { throw error } } @@ -13886,20 +14031,20 @@ func _$Promise_resolve_SD11PublicPointV(_ promise: JSObject, _ value: [String: P #if arch(wasm32) @_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_9DataPointV") -fileprivate func promise_resolve_BridgeJSRuntimeTests_9DataPointV_extern(_ promise: Int32, _ value: Int32) -> Void +fileprivate func promise_resolve_BridgeJSRuntimeTests_9DataPointV_extern(_ promise: Int32) -> Void #else -fileprivate func promise_resolve_BridgeJSRuntimeTests_9DataPointV_extern(_ promise: Int32, _ value: Int32) -> Void { +fileprivate func promise_resolve_BridgeJSRuntimeTests_9DataPointV_extern(_ promise: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_9DataPointV(_ promise: Int32, _ value: Int32) -> Void { - return promise_resolve_BridgeJSRuntimeTests_9DataPointV_extern(promise, value) +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_9DataPointV(_ promise: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_9DataPointV_extern(promise) } func _$Promise_resolve_9DataPointV(_ promise: JSObject, _ value: DataPoint) throws(JSException) -> Void { - let valueObjectId = value.bridgeJSLowerParameter() + let _ = value.bridgeJSLowerParameter() let promiseValue = promise.bridgeJSLowerParameter() - promise_resolve_BridgeJSRuntimeTests_9DataPointV(promiseValue, valueObjectId) + promise_resolve_BridgeJSRuntimeTests_9DataPointV(promiseValue) if let error = _swift_js_take_exception() { throw error } } @@ -14032,14 +14177,14 @@ fileprivate func bjs_AliasImports_jsRoundTripPolygon_static_extern(_ value: Unsa #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_AliasImports_jsRoundTripCoordinate_static") -fileprivate func bjs_AliasImports_jsRoundTripCoordinate_static_extern(_ value: Int32) -> Int32 +fileprivate func bjs_AliasImports_jsRoundTripCoordinate_static_extern() -> Void #else -fileprivate func bjs_AliasImports_jsRoundTripCoordinate_static_extern(_ value: Int32) -> Int32 { +fileprivate func bjs_AliasImports_jsRoundTripCoordinate_static_extern() -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_AliasImports_jsRoundTripCoordinate_static(_ value: Int32) -> Int32 { - return bjs_AliasImports_jsRoundTripCoordinate_static_extern(value) +@inline(never) fileprivate func bjs_AliasImports_jsRoundTripCoordinate_static() -> Void { + return bjs_AliasImports_jsRoundTripCoordinate_static_extern() } #if arch(wasm32) @@ -14117,12 +14262,12 @@ func _$AliasImports_jsRoundTripPolygon(_ value: Polygon) throws(JSException) -> } func _$AliasImports_jsRoundTripCoordinate(_ value: Coordinate) throws(JSException) -> Coordinate { - let valueObjectId = value.bridgeJSLowerParameter() - let ret = bjs_AliasImports_jsRoundTripCoordinate_static(valueObjectId) + let _ = value.bridgeJSLowerParameter() + bjs_AliasImports_jsRoundTripCoordinate_static() if let error = _swift_js_take_exception() { throw error } - return Coordinate.bridgeJSLiftReturn(ret) + return Coordinate.bridgeJSLiftReturn() } func _$AliasImports_jsRoundTripUserId(_ value: UserId) throws(JSException) -> UserId { @@ -16545,25 +16690,25 @@ func _$jsJoinStringThenStackParams(_ s: String, _ a: Optional<[Int]>, _ b: [Int] #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsTranslatePoint") -fileprivate func bjs_jsTranslatePoint_extern(_ point: Int32, _ dx: Int32, _ dy: Int32) -> Int32 +fileprivate func bjs_jsTranslatePoint_extern(_ dx: Int32, _ dy: Int32) -> Void #else -fileprivate func bjs_jsTranslatePoint_extern(_ point: Int32, _ dx: Int32, _ dy: Int32) -> Int32 { +fileprivate func bjs_jsTranslatePoint_extern(_ dx: Int32, _ dy: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_jsTranslatePoint(_ point: Int32, _ dx: Int32, _ dy: Int32) -> Int32 { - return bjs_jsTranslatePoint_extern(point, dx, dy) +@inline(never) fileprivate func bjs_jsTranslatePoint(_ dx: Int32, _ dy: Int32) -> Void { + return bjs_jsTranslatePoint_extern(dx, dy) } func _$jsTranslatePoint(_ point: Point, _ dx: Int, _ dy: Int) throws(JSException) -> Point { let dyValue = dy.bridgeJSLowerParameter() let dxValue = dx.bridgeJSLowerParameter() - let pointObjectId = point.bridgeJSLowerParameter() - let ret = bjs_jsTranslatePoint(pointObjectId, dxValue, dyValue) + let _ = point.bridgeJSLowerParameter() + bjs_jsTranslatePoint(dxValue, dyValue) if let error = _swift_js_take_exception() { throw error } - return Point.bridgeJSLiftReturn(ret) + return Point.bridgeJSLiftReturn() } #if arch(wasm32) diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index ac0d9914e..e2a8575e1 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -4697,6 +4697,104 @@ } } + }, + { + "abiName" : "bjs_TextProcessor_observeVector", + "documentation" : "Swift→JS callback with a struct parameter (ExportSwift stack ABI).", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "observeVector", + "parameters" : [ + { + "label" : "_", + "name" : "callback", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTests8Vector2DV_y", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "swiftStruct" : { + "_0" : "Vector2D" + } + } + ], + "returnType" : { + "void" : { + + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "abiName" : "bjs_TextProcessor_mapVector", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "mapVector", + "parameters" : [ + { + "label" : "_", + "name" : "vector", + "type" : { + "swiftStruct" : { + "_0" : "Vector2D" + } + } + }, + { + "label" : "_", + "name" : "callback", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "20BridgeJSRuntimeTests8Vector2DV_8Vector2DV", + "moduleName" : "BridgeJSRuntimeTests", + "parameters" : [ + { + "swiftStruct" : { + "_0" : "Vector2D" + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "Vector2D" + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "Vector2D" + } + } } ], "name" : "TextProcessor", diff --git a/Tests/BridgeJSRuntimeTests/JavaScript/ClosureSupportTests.mjs b/Tests/BridgeJSRuntimeTests/JavaScript/ClosureSupportTests.mjs index bab496d09..9461bec1f 100644 --- a/Tests/BridgeJSRuntimeTests/JavaScript/ClosureSupportTests.mjs +++ b/Tests/BridgeJSRuntimeTests/JavaScript/ClosureSupportTests.mjs @@ -366,6 +366,24 @@ export function runJsClosureSupportTests(exports) { ); assert.equal(optVectorResult, "(2.0,4.0) | nil"); + // Swift→JS callback with a struct parameter must deliver the struct fields. + // Regression: empty-stack lift previously yielded `dx`/`dy` as `undefined` + // (and Bool fields wrongly became `true`). + let observed = null; + processor.observeVector((vector) => { + observed = vector; + }); + assert.ok(observed, "observeVector must invoke the callback"); + assert.equal(observed.dx, 1.5); + assert.equal(observed.dy, 2.5); + + const mapped = processor.mapVector({ dx: 3, dy: 4 }, (vector) => ({ + dx: vector.dx * 2, + dy: vector.dy * 2, + })); + assert.equal(mapped.dx, 6); + assert.equal(mapped.dy, 8); + processor.release(); const intToInt = exports.ClosureSupportExports.makeIntToInt(10); From 30d994d137395cb97bb460c2cfa67cbfcfe92496 Mon Sep 17 00:00:00 2001 From: William Taylor Date: Tue, 11 Aug 2026 16:55:43 +1000 Subject: [PATCH 35/50] BridgeJS: Add runtime test for instance method String returns on a struct (#800) --- .../Generated/BridgeJS.swift | 11 +++++++++++ .../Generated/JavaScript/BridgeJS.json | 17 +++++++++++++++++ Tests/BridgeJSRuntimeTests/StructAPIs.swift | 4 ++++ Tests/prelude.mjs | 1 + 4 files changed, 33 insertions(+) diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index ad6f3fa24..c9db5b2ac 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -7861,6 +7861,17 @@ public func _bjs_Vector2D_scaled(_ factor: Float64) -> Void { #endif } +@_expose(wasm, "bjs_Vector2D_describe") +@_cdecl("bjs_Vector2D_describe") +public func _bjs_Vector2D_describe() -> Void { + #if arch(wasm32) + let ret = Vector2D.bridgeJSLiftParameter().describe() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + extension JSObjectContainer: _BridgedSwiftStruct { @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> JSObjectContainer { let optionalObject = Optional.bridgeJSStackPop() diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index e2a8575e1..c68d264e2 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -19680,6 +19680,23 @@ "_0" : "Vector2D" } } + }, + { + "abiName" : "bjs_Vector2D_describe", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "describe", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } } ], "name" : "Vector2D", diff --git a/Tests/BridgeJSRuntimeTests/StructAPIs.swift b/Tests/BridgeJSRuntimeTests/StructAPIs.swift index c2216c808..e11856d41 100644 --- a/Tests/BridgeJSRuntimeTests/StructAPIs.swift +++ b/Tests/BridgeJSRuntimeTests/StructAPIs.swift @@ -200,6 +200,10 @@ extension Vector2D { @JS func scaled(by factor: Double) -> Vector2D { return Vector2D(dx: dx * factor, dy: dy * factor) } + + @JS func describe() -> String { + return "Vector2D(\(dx), \(dy))" + } } @JS func roundTripDataPoint(_ data: DataPoint) -> DataPoint { diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index 42a0e3ea4..931d42561 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -871,6 +871,7 @@ function testStructSupport(exports) { const scaled = vec.scaled(2.0); assert.equal(scaled.dx, 6.0); assert.equal(scaled.dy, 8.0); + assert.equal(vec.describe(), "Vector2D(3.0, 4.0)"); const publicPoint = { x: 9, y: -3 }; assert.deepEqual(exports.roundTripPublicPoint(publicPoint), publicPoint); From e10836b71f0f270c8334e825e6920192e806dc6a Mon Sep 17 00:00:00 2001 From: William Taylor Date: Tue, 11 Aug 2026 16:57:06 +1000 Subject: [PATCH 36/50] BridgeJS: Export with a different JS name (#801) --- .../BridgeJSCore/SwiftToSkeleton.swift | 88 ++- .../Sources/BridgeJSLink/BridgeJSLink.swift | 122 ++-- .../ImportedJSModuleRegistry.swift | 6 +- .../Sources/BridgeJSLink/JSGlueGen.swift | 2 +- .../BridgeJSSkeleton/BridgeJSSkeleton.swift | 18 + .../BridgeJSToolTests/DiagnosticsTests.swift | 81 +++ .../Inputs/MacroSwift/JSNameOverride.swift | 40 ++ .../BridgeJSCodegenTests/JSNameOverride.json | 524 ++++++++++++++++++ .../BridgeJSCodegenTests/JSNameOverride.swift | 351 ++++++++++++ .../BridgeJSLinkTests/JSNameOverride.d.ts | 68 +++ .../BridgeJSLinkTests/JSNameOverride.js | 442 +++++++++++++++ .../Exporting-Swift-Function.md | 21 + Sources/JavaScriptKit/Macros.swift | 2 + .../Generated/BridgeJS.swift | 118 ++++ .../Generated/JavaScript/BridgeJS.json | 180 ++++++ Tests/BridgeJSRuntimeTests/JSNameAPIs.swift | 34 ++ Tests/prelude.mjs | 12 + 17 files changed, 2049 insertions(+), 60 deletions(-) create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSNameOverride.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSNameOverride.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSNameOverride.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.d.ts create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.js create mode 100644 Tests/BridgeJSRuntimeTests/JSNameAPIs.swift diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index d327de307..bfd639ee6 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -731,6 +731,23 @@ public final class SwiftToSkeleton { return String(name.dropFirst().dropLast()) } + fileprivate static func isValidJSIdentifier(_ name: String) -> Bool { + func isIdentifierPart(_ scalar: Unicode.Scalar, isStart: Bool) -> Bool { + switch scalar { + case "a"..."z", "A"..."Z", "_", "$": + return true + case "0"..."9": + return !isStart + default: + return false + } + } + guard let first = name.unicodeScalars.first, isIdentifierPart(first, isStart: true) else { + return false + } + return name.unicodeScalars.dropFirst().allSatisfy { isIdentifierPart($0, isStart: false) } + } + } private enum ExportSwiftConstants { @@ -1291,6 +1308,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { } let name = node.name.text + let jsName = extractValidatedJSName(from: jsAttribute) let attributeNamespace = extractNamespace(from: jsAttribute) let computedNamespace = computeNamespace(for: node) @@ -1378,7 +1396,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { classNameForABI = nil } abiName = ABINameGenerator.generateABIName( - baseName: name, + baseName: jsName ?? name, namespace: finalNamespace, staticContext: isStatic ? staticContext : nil, className: classNameForABI @@ -1390,6 +1408,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { return ExportedFunction( name: name, + jsName: jsName, abiName: abiName, parameters: parameters, returnType: returnType, @@ -1469,6 +1488,45 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { return Effects(isAsync: isAsync, isThrows: isThrows, isStatic: isStatic) } + private func extractJSName( + from jsAttribute: AttributeSyntax + ) -> String? { + guard let arguments = jsAttribute.arguments?.as(LabeledExprListSyntax.self), + let nameArg = arguments.first, + nameArg.label == nil, + let stringLiteral = nameArg.expression.as(StringLiteralExprSyntax.self), + stringLiteral.segments.count == 1, + let name = stringLiteral.segments.first?.as(StringSegmentSyntax.self)?.content.text + else { + return nil + } + return name + } + + private func extractValidatedJSName( + from jsAttribute: AttributeSyntax + ) -> String? { + guard let jsName = extractJSName(from: jsAttribute) else { return nil } + guard SwiftToSkeleton.isValidJSIdentifier(jsName) else { + diagnose( + node: jsAttribute, + message: "`\(jsName)` is not a valid JavaScript identifier" + ) + return nil + } + return jsName + } + + private func diagnoseUnsupportedJSName( + from jsAttribute: AttributeSyntax + ) { + guard extractJSName(from: jsAttribute) != nil else { return } + diagnose( + node: jsAttribute, + message: "A separate name for JavaScript is not supported here" + ) + } + private func extractNamespace( from jsAttribute: AttributeSyntax ) -> [String]? { @@ -1515,6 +1573,8 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { override func visit(_ node: InitializerDeclSyntax) -> SyntaxVisitorContinueKind { guard let jsAttribute = node.attributes.firstJSAttribute else { return .skipChildren } + diagnoseUnsupportedJSName(from: jsAttribute) + switch state { case .classBody(_, let classKey): if extractNamespace(from: jsAttribute) != nil { @@ -1636,6 +1696,15 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { } } + let jsName = extractValidatedJSName(from: jsAttribute) + if jsName != nil, node.bindings.count > 1 { + diagnose( + node: jsAttribute, + message: "Name targets declaration with multiple bindings", + hint: "Declare each property with a different JS name separately" + ) + } + // Process each binding (variable declaration) for binding in node.bindings { guard let pattern = binding.pattern.as(IdentifierPatternSyntax.self) else { @@ -1663,6 +1732,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { let exportedProperty = ExportedProperty( name: propertyName, + jsName: jsName, type: propertyType, isReadonly: isReadonly, isStatic: isStatic, @@ -1693,6 +1763,8 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { return .skipChildren } + diagnoseUnsupportedJSName(from: jsAttribute) + if let aliasTarget = parent.extractAliasTarget(from: jsAttribute) { recordAlias(node: node, jsAttribute: jsAttribute, aliasTarget: aliasTarget) return .skipChildren @@ -1843,6 +1915,8 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { return .skipChildren } + diagnoseUnsupportedJSName(from: jsAttribute) + if let aliasTarget = parent.extractAliasTarget(from: jsAttribute) { recordAlias(node: node, jsAttribute: jsAttribute, aliasTarget: aliasTarget) return .skipChildren @@ -1968,6 +2042,8 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { return .skipChildren } + diagnoseUnsupportedJSName(from: jsAttribute) + let name = node.name.text let namespaceResult = resolveNamespace(from: jsAttribute, for: node, declarationType: "protocol") @@ -2031,6 +2107,8 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { return .skipChildren } + diagnoseUnsupportedJSName(from: jsAttribute) + if let aliasTarget = parent.extractAliasTarget(from: jsAttribute) { recordAlias(node: node, jsAttribute: jsAttribute, aliasTarget: aliasTarget) return .skipChildren @@ -2169,6 +2247,10 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { protocolName: String, namespace: [String]? ) -> ExportedFunction? { + if let jsAttribute = node.attributes.firstJSAttribute { + diagnoseUnsupportedJSName(from: jsAttribute) + } + let name = node.name.text let parameters = parseParameters(from: node.signature.parameterClause, allowDefaults: false) @@ -2215,6 +2297,10 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { protocolName: String, protocolKey: String ) -> SyntaxVisitorContinueKind { + if let jsAttribute = node.attributes.firstJSAttribute { + diagnoseUnsupportedJSName(from: jsAttribute) + } + for binding in node.bindings { guard let pattern = binding.pattern.as(IdentifierPatternSyntax.self) else { diagnose(node: binding.pattern, message: "Complex patterns not supported for protocol properties") diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index 1b6300595..6043f3cd1 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -235,7 +235,7 @@ public struct BridgeJSLink { for function in skeleton.functions { if function.namespace == nil { var (js, dts) = try renderExportedFunction(function: function) - js[0] = "\(function.name): " + js[0] + js[0] = "\(function.resolvedJSName): " + js[0] js[js.count - 1] += "," data.exportsLines.append(contentsOf: js) data.dtsExportLines.append(contentsOf: dts) @@ -973,13 +973,15 @@ public struct BridgeJSLink { ) ) printer.write( - "\(function.name)\(renderTSSignature(parameters: function.parameters, returnType: function.returnType, effects: function.effects));" + "\(function.resolvedJSName)\(renderTSSignature(parameters: function.parameters, returnType: function.returnType, effects: function.effects));" ) } for property in enumDefinition.staticProperties { let readonly = property.isReadonly ? "readonly " : "" printer.write(lines: renderJSDoc(documentation: property.documentation, parameters: [])) - printer.write("\(readonly)\(property.name): \(resolveTypeScriptType(property.type));") + printer.write( + "\(readonly)\(property.resolvedJSName): \(resolveTypeScriptType(property.type));" + ) } } printer.write("};") @@ -1025,13 +1027,13 @@ public struct BridgeJSLink { renderFunctionEntry: { function in self.renderJSDoc(documentation: function.documentation, parameters: function.parameters) + [ - "\(function.name)\(self.renderTSSignature(parameters: function.parameters, returnType: function.returnType, effects: function.effects));" + "\(function.resolvedJSName)\(self.renderTSSignature(parameters: function.parameters, returnType: function.returnType, effects: function.effects));" ] }, renderPropertyEntry: { property in let readonly = property.isReadonly ? "readonly " : "" return self.renderJSDoc(documentation: property.documentation, parameters: []) - + ["\(readonly)\(property.name): \(property.type.tsType);"] + + ["\(readonly)\(property.resolvedJSName): \(property.type.tsType);"] } ) printer.write("export type Exports = {") @@ -1370,7 +1372,7 @@ public struct BridgeJSLink { // Add methods for method in type.methods { - let methodName = method.jsName ?? method.name + let methodName = method.resolvedJSName let methodSignature = "\(renderTSPropertyName(methodName))\(renderTSSignature(parameters: method.parameters, returnType: method.returnType, effects: method.effects));" printer.write(methodSignature) @@ -1379,9 +1381,9 @@ public struct BridgeJSLink { // Add properties from getters var propertyNames = Set() for getter in type.getters { - let propertyName = getter.jsName ?? getter.name + let propertyName = getter.resolvedJSName propertyNames.insert(propertyName) - let hasSetter = type.setters.contains { ($0.jsName ?? $0.name) == propertyName } + let hasSetter = type.setters.contains { $0.resolvedJSName == propertyName } let propertySignature = hasSetter ? "\(renderTSPropertyName(propertyName)): \(resolveTypeScriptType(getter.type));" @@ -1390,7 +1392,7 @@ public struct BridgeJSLink { } // Add setters that don't have corresponding getters for setter in type.setters { - let propertyName = setter.jsName ?? setter.name + let propertyName = setter.resolvedJSName guard !propertyNames.contains(propertyName) else { continue } printer.write("\(renderTSPropertyName(propertyName)): \(resolveTypeScriptType(setter.type));") } @@ -1628,7 +1630,7 @@ public struct BridgeJSLink { returnType: method.returnType, effects: method.effects ) - dtsTypePrinter.write("\(method.name)\(signature);") + dtsTypePrinter.write("\(method.resolvedJSName)\(signature);") } } dtsTypePrinter.write("}") @@ -1649,13 +1651,15 @@ public struct BridgeJSLink { for property in structDefinition.properties where property.isStatic { let readonly = property.isReadonly ? "readonly " : "" dtsExportEntryPrinter.write(lines: renderJSDoc(documentation: property.documentation, parameters: [])) - dtsExportEntryPrinter.write("\(readonly)\(property.name): \(resolveTypeScriptType(property.type));") + dtsExportEntryPrinter.write( + "\(readonly)\(property.resolvedJSName): \(resolveTypeScriptType(property.type));" + ) } for method in structDefinition.methods where method.effects.isStatic { let jsDocLines = renderJSDoc(documentation: method.documentation, parameters: method.parameters) dtsExportEntryPrinter.write(lines: jsDocLines) dtsExportEntryPrinter.write( - "\(method.name)\(renderTSSignature(parameters: method.parameters, returnType: method.returnType, effects: method.effects));" + "\(method.resolvedJSName)\(renderTSSignature(parameters: method.parameters, returnType: method.returnType, effects: method.effects));" ) } @@ -1914,7 +1918,7 @@ extension BridgeJSLink { dtsLines.append(contentsOf: renderJSDoc(documentation: function.documentation, parameters: function.parameters)) dtsLines.append( - "\(function.name)\(renderTSSignature(parameters: function.parameters, returnType: function.returnType, effects: function.effects));" + "\(function.resolvedJSName)\(renderTSSignature(parameters: function.parameters, returnType: function.returnType, effects: function.effects));" ) return (funcLines, dtsLines) @@ -1955,7 +1959,7 @@ extension BridgeJSLink { let returnExpr = try thunkBuilder.call(abiName: function.abiName, returnType: function.returnType) let funcLines = thunkBuilder.renderFunction( - name: function.name, + name: function.resolvedJSName, parameters: function.parameters, returnExpr: returnExpr, declarationPrefixKeyword: "static" @@ -1966,7 +1970,7 @@ extension BridgeJSLink { dtsLines.append(contentsOf: renderJSDoc(documentation: function.documentation, parameters: function.parameters)) dtsLines.append( - "static \(function.name)\(renderTSSignature(parameters: function.parameters, returnType: function.returnType, effects: function.effects));" + "static \(function.resolvedJSName)\(renderTSSignature(parameters: function.parameters, returnType: function.returnType, effects: function.effects));" ) return (funcLines, dtsLines) @@ -1986,7 +1990,7 @@ extension BridgeJSLink { let returnExpr = try thunkBuilder.call(abiName: function.abiName, returnType: function.returnType) let printer = CodeFragmentPrinter() - printer.write("\(function.name)(\(DefaultValueUtils.formatParameterList(function.parameters))) {") + printer.write("\(function.resolvedJSName)(\(DefaultValueUtils.formatParameterList(function.parameters))) {") printer.indent { thunkBuilder.renderFunctionBody(into: printer, returnExpr: returnExpr) } @@ -1997,7 +2001,7 @@ extension BridgeJSLink { dtsLines.append(contentsOf: renderJSDoc(documentation: function.documentation, parameters: function.parameters)) dtsLines.append( - "\(function.name)\(renderTSSignature(parameters: function.parameters, returnType: function.returnType, effects: function.effects));" + "\(function.resolvedJSName)\(renderTSSignature(parameters: function.parameters, returnType: function.returnType, effects: function.effects));" ) return (printer.lines, dtsLines) @@ -2043,7 +2047,7 @@ extension BridgeJSLink { let methodPrinter = CodeFragmentPrinter() methodPrinter.write( - "\(method.name): function(\(DefaultValueUtils.formatParameterList(method.parameters))) {" + "\(method.resolvedJSName): function(\(DefaultValueUtils.formatParameterList(method.parameters))) {" ) methodPrinter.indent { thunkBuilder.renderFunctionBody(into: methodPrinter, returnExpr: returnExpr) @@ -2071,7 +2075,7 @@ extension BridgeJSLink { returnType: property.type ) - propertyPrinter.write("get \(property.name)() {") + propertyPrinter.write("get \(property.resolvedJSName)() {") propertyPrinter.indent { getterThunkBuilder.renderFunctionBody(into: propertyPrinter, returnExpr: getterReturnExpr) } @@ -2093,7 +2097,7 @@ extension BridgeJSLink { returnType: .void ) - propertyPrinter.write("set \(property.name)(value) {") + propertyPrinter.write("set \(property.resolvedJSName)(value) {") propertyPrinter.indent { setterThunkBuilder.renderFunctionBody(into: propertyPrinter, returnExpr: nil) } @@ -2177,7 +2181,7 @@ extension BridgeJSLink { jsPrinter.indent { jsPrinter.write( lines: thunkBuilder.renderFunction( - name: method.name, + name: method.resolvedJSName, parameters: method.parameters, returnExpr: returnExpr, declarationPrefixKeyword: "static" @@ -2198,7 +2202,7 @@ extension BridgeJSLink { jsPrinter.indent { jsPrinter.write( lines: thunkBuilder.renderFunction( - name: method.name, + name: method.resolvedJSName, parameters: method.parameters, returnExpr: returnExpr, declarationPrefixKeyword: nil @@ -2214,7 +2218,7 @@ extension BridgeJSLink { dtsTypePrinter.write(line) } dtsTypePrinter.write( - "\(method.name)\(renderTSSignature(parameters: method.parameters, returnType: method.returnType, effects: method.effects));" + "\(method.resolvedJSName)\(renderTSSignature(parameters: method.parameters, returnType: method.returnType, effects: method.effects));" ) } } @@ -2252,13 +2256,13 @@ extension BridgeJSLink { for method in klass.methods where method.effects.isStatic { printer.write(lines: renderJSDoc(documentation: method.documentation, parameters: method.parameters)) printer.write( - "\(method.name)\(renderTSSignature(parameters: method.parameters, returnType: method.returnType, effects: method.effects));" + "\(method.resolvedJSName)\(renderTSSignature(parameters: method.parameters, returnType: method.returnType, effects: method.effects));" ) } for property in klass.properties where property.isStatic { let readonly = property.isReadonly ? "readonly " : "" printer.write(lines: renderJSDoc(documentation: property.documentation, parameters: [])) - printer.write("\(readonly)\(property.name): \(resolveTypeScriptType(property.type));") + printer.write("\(readonly)\(property.resolvedJSName): \(resolveTypeScriptType(property.type));") } return printer.lines } @@ -2280,18 +2284,20 @@ extension BridgeJSLink { ) printer.write("constructor(\(paramSignatures.joined(separator: ", ")));") } - for method in klass.methods.sorted(by: { $0.name < $1.name }) { + for method in klass.methods.sorted(by: { $0.resolvedJSName < $1.resolvedJSName }) { let staticKeyword = method.effects.isStatic ? "static " : "" printer.write(lines: renderJSDoc(documentation: method.documentation, parameters: method.parameters)) printer.write( - "\(staticKeyword)\(method.name)\(renderTSSignature(parameters: method.parameters, returnType: method.returnType, effects: method.effects));" + "\(staticKeyword)\(method.resolvedJSName)\(renderTSSignature(parameters: method.parameters, returnType: method.returnType, effects: method.effects));" ) } - for property in klass.properties.sorted(by: { $0.name < $1.name }) { + for property in klass.properties.sorted(by: { $0.resolvedJSName < $1.resolvedJSName }) { let staticKeyword = property.isStatic ? "static " : "" let readonly = property.isReadonly ? "readonly " : "" printer.write(lines: renderJSDoc(documentation: property.documentation, parameters: [])) - printer.write("\(staticKeyword)\(readonly)\(property.name): \(resolveTypeScriptType(property.type));") + printer.write( + "\(staticKeyword)\(readonly)\(property.resolvedJSName): \(resolveTypeScriptType(property.type));" + ) } printer.write("release(): void;") } @@ -2321,7 +2327,7 @@ extension BridgeJSLink { jsPrinter.indent { jsPrinter.write( lines: getterThunkBuilder.renderFunction( - name: property.name, + name: property.resolvedJSName, parameters: [], returnExpr: getterReturnExpr, declarationPrefixKeyword: getterKeyword @@ -2349,7 +2355,7 @@ extension BridgeJSLink { jsPrinter.indent { jsPrinter.write( lines: setterThunkBuilder.renderFunction( - name: property.name, + name: property.resolvedJSName, parameters: [.init(label: nil, name: "value", type: property.type)], returnExpr: nil, declarationPrefixKeyword: setterKeyword @@ -2365,7 +2371,7 @@ extension BridgeJSLink { for line in renderJSDoc(documentation: property.documentation, parameters: []) { dtsPrinter.write(line) } - dtsPrinter.write("\(readonly)\(property.name): \(resolveTypeScriptType(property.type));") + dtsPrinter.write("\(readonly)\(property.resolvedJSName): \(resolveTypeScriptType(property.type));") } } } @@ -2738,7 +2744,7 @@ extension BridgeJSLink { for function in skeleton.functions where function.namespace != nil { let namespacePath = function.namespace!.joined(separator: ".") printer.write( - "globalThis.\(namespacePath).\(function.name) = exports.\(namespacePath).\(function.name);" + "globalThis.\(namespacePath).\(function.resolvedJSName) = exports.\(namespacePath).\(function.resolvedJSName);" ) } for enumDef in skeleton.enums where enumDef.enumType == .namespace { @@ -2746,7 +2752,7 @@ extension BridgeJSLink { let fullNamespace = (enumDef.namespace ?? []) + [enumDef.name] let namespacePath = fullNamespace.joined(separator: ".") printer.write( - "globalThis.\(namespacePath).\(function.name) = exports.\(namespacePath).\(function.name);" + "globalThis.\(namespacePath).\(function.resolvedJSName) = exports.\(namespacePath).\(function.resolvedJSName);" ) } for property in enumDef.staticProperties { @@ -2754,11 +2760,13 @@ extension BridgeJSLink { let namespacePath = fullNamespace.joined(separator: ".") let exportsPath = "exports.\(namespacePath)" - printer.write("Object.defineProperty(globalThis.\(namespacePath), '\(property.name)', {") + printer.write( + "Object.defineProperty(globalThis.\(namespacePath), '\(property.resolvedJSName)', {" + ) printer.indent { - printer.write("get: () => \(exportsPath).\(property.name),") + printer.write("get: () => \(exportsPath).\(property.resolvedJSName),") if !property.isReadonly { - printer.write("set: (value) => { \(exportsPath).\(property.name) = value; }") + printer.write("set: (value) => { \(exportsPath).\(property.resolvedJSName) = value; }") } } printer.write("});") @@ -2940,7 +2948,7 @@ extension BridgeJSLink { renderPropertyEntry: (ExportedProperty) -> [String] ) { for function in node.content.functions { - node.content.functionDtsLines.append((function.name, renderFunctionEntry(function))) + node.content.functionDtsLines.append((function.resolvedJSName, renderFunctionEntry(function))) } switch node.content.declaration { @@ -2953,7 +2961,7 @@ extension BridgeJSLink { } for property in node.content.staticProperties { - node.content.staticPropertyDtsLines.append((property.name, renderPropertyEntry(property))) + node.content.staticPropertyDtsLines.append((property.resolvedJSName, renderPropertyEntry(property))) } for enumDef in node.content.enums { @@ -3005,7 +3013,7 @@ extension BridgeJSLink { ) throws { for function in node.content.functions { let impl = try renderFunctionImpl(function) - node.content.functionJsLines.append((function.name, impl)) + node.content.functionJsLines.append((function.resolvedJSName, impl)) } switch node.content.declaration { @@ -3039,7 +3047,7 @@ extension BridgeJSLink { ) let getterPrinter = CodeFragmentPrinter() - getterPrinter.write("get \(property.name)() {") + getterPrinter.write("get \(property.resolvedJSName)() {") getterPrinter.indent { getterPrinter.write(contentsOf: getterThunkBuilder.body) getterPrinter.write(lines: getterThunkBuilder.checkExceptionLines()) @@ -3066,7 +3074,7 @@ extension BridgeJSLink { ) let setterPrinter = CodeFragmentPrinter() - setterPrinter.write("set \(property.name)(value) {") + setterPrinter.write("set \(property.resolvedJSName)(value) {") setterPrinter.indent { setterPrinter.write(contentsOf: setterThunkBuilder.body) setterPrinter.write(lines: setterThunkBuilder.checkExceptionLines()) @@ -3431,18 +3439,22 @@ extension BridgeJSLink { // Only include functions and properties when exposeToGlobal is true if exposeToGlobal { - let sortedFunctions = childNode.content.functions.sorted { $0.name < $1.name } + let sortedFunctions = childNode.content.functions.sorted { + $0.resolvedJSName < $1.resolvedJSName + } for function in sortedFunctions { let signature = - "function \(function.name)\(renderTSSignatureCallback(function.parameters, function.returnType, function.effects));" + "function \(function.resolvedJSName)\(renderTSSignatureCallback(function.parameters, function.returnType, function.effects));" printer.write(lines: renderDocCallback(function.documentation, function.parameters)) printer.write(signature) } - let sortedProperties = childNode.content.staticProperties.sorted { $0.name < $1.name } + let sortedProperties = childNode.content.staticProperties.sorted { + $0.resolvedJSName < $1.resolvedJSName + } for property in sortedProperties { let readonly = property.isReadonly ? "var " : "let " printer.write(lines: renderDocCallback(property.documentation, [])) - printer.write("\(readonly)\(property.name): \(property.type.tsType);") + printer.write("\(readonly)\(property.resolvedJSName): \(property.type.tsType);") } } @@ -3479,7 +3491,7 @@ extension BridgeJSLink { for param in function.parameters { try thunkBuilder.liftParameter(param: param) } - let jsName = function.jsName ?? function.name + let jsName = function.resolvedJSName let calleeExpr = try importedModuleRegistry.memberExpression( swiftModuleName: importObjectBuilder.moduleName, from: function.from, @@ -3507,7 +3519,7 @@ extension BridgeJSLink { returnType: getter.type, intrinsicRegistry: intrinsicRegistry ) - let jsName = getter.jsName ?? getter.name + let jsName = getter.resolvedJSName let accessExpr = try importedModuleRegistry.memberExpression( swiftModuleName: importObjectBuilder.moduleName, from: getter.from, @@ -3542,7 +3554,7 @@ extension BridgeJSLink { getter: getter, abiName: getterAbiName, emitCall: { thunkBuilder in - return try thunkBuilder.callPropertyGetter(name: getter.jsName ?? getter.name) + return try thunkBuilder.callPropertyGetter(name: getter.resolvedJSName) } ) importObjectBuilder.assignToImportObject(name: getterAbiName, function: js) @@ -3558,7 +3570,7 @@ extension BridgeJSLink { try thunkBuilder.liftParameter( param: Parameter(label: nil, name: "newValue", type: setter.type) ) - thunkBuilder.callPropertySetter(name: setter.jsName ?? setter.name) + thunkBuilder.callPropertySetter(name: setter.resolvedJSName) } ) importObjectBuilder.assignToImportObject(name: setterAbiName, function: js) @@ -3585,7 +3597,7 @@ extension BridgeJSLink { ) } for method in type.staticMethods { - let methodName = method.jsName ?? method.name + let methodName = method.resolvedJSName let signature = "\(renderTSPropertyName(methodName))\(renderTSSignature(parameters: method.parameters, returnType: method.returnType, effects: method.effects));" dtsPrinter.write(signature) @@ -3617,7 +3629,7 @@ extension BridgeJSLink { let ctorExpr = try importedModuleRegistry.memberExpression( swiftModuleName: importObjectBuilder.moduleName, from: type.from, - memberName: type.jsName ?? type.name + memberName: type.resolvedJSName ) try thunkBuilder.callConstructor( ctorExpr: ctorExpr, @@ -3676,10 +3688,10 @@ extension BridgeJSLink { let constructorExpr = try importedModuleRegistry.memberExpression( swiftModuleName: swiftModuleName, from: context.from, - memberName: context.jsName ?? context.name + memberName: context.resolvedJSName ) - try thunkBuilder.callStaticMethod(on: constructorExpr, name: method.jsName ?? method.name) + try thunkBuilder.callStaticMethod(on: constructorExpr, name: method.resolvedJSName) let funcLines = thunkBuilder.renderFunction(name: method.abiName(context: context, operation: "static")) return (funcLines, []) } @@ -3698,7 +3710,7 @@ extension BridgeJSLink { try thunkBuilder.liftParameter(param: param) } - try thunkBuilder.callMethod(name: method.jsName ?? method.name) + try thunkBuilder.callMethod(name: method.resolvedJSName) let funcLines = thunkBuilder.renderFunction(name: method.abiName(context: context)) return (funcLines, []) } diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/ImportedJSModuleRegistry.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/ImportedJSModuleRegistry.swift index 96efcd1d4..daf220d7f 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/ImportedJSModuleRegistry.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/ImportedJSModuleRegistry.swift @@ -133,14 +133,14 @@ final class ImportedJSModuleRegistry { } for file in skeleton.imported?.children ?? [] { for function in file.functions { - visit(from: function.from, memberName: function.jsName ?? function.name) + visit(from: function.from, memberName: function.resolvedJSName) } for getter in file.globalGetters { - visit(from: getter.from, memberName: getter.jsName ?? getter.name) + visit(from: getter.from, memberName: getter.resolvedJSName) } for type in file.types { guard type.constructor != nil || !type.staticMethods.isEmpty else { continue } - visit(from: type.from, memberName: type.jsName ?? type.name) + visit(from: type.from, memberName: type.resolvedJSName) } } } diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift index 1cf0fa298..2bf656708 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift @@ -2353,7 +2353,7 @@ struct IntrinsicJSFragment: Sendable { for method in structDef.methods where !method.effects.isStatic { let paramList = DefaultValueUtils.formatParameterList(method.parameters) printer.write( - "\(instanceVar).\(method.name) = function(\(paramList)) {" + "\(instanceVar).\(method.resolvedJSName) = function(\(paramList)) {" ) try printer.indent { printer.write( diff --git a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift index 5507f39c2..21704d1c9 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift @@ -861,6 +861,7 @@ public struct ExportedProtocol: Codable, Equatable { public struct ExportedFunction: Codable, Equatable, Sendable { public var name: String + public var jsName: String? public var abiName: String public var parameters: [Parameter] public var returnType: BridgeType @@ -869,8 +870,11 @@ public struct ExportedFunction: Codable, Equatable, Sendable { public var staticContext: StaticContext? public var documentation: String? + public var resolvedJSName: String { jsName ?? name } + public init( name: String, + jsName: String? = nil, abiName: String, parameters: [Parameter], returnType: BridgeType, @@ -880,6 +884,7 @@ public struct ExportedFunction: Codable, Equatable, Sendable { documentation: String? = nil ) { self.name = name + self.jsName = jsName self.abiName = abiName self.parameters = parameters self.returnType = returnType @@ -948,6 +953,7 @@ public struct ExportedConstructor: Codable, Equatable, Sendable { public struct ExportedProperty: Codable, Equatable, Sendable { public var name: String + public var jsName: String? public var type: BridgeType public var isReadonly: Bool public var isStatic: Bool @@ -955,8 +961,11 @@ public struct ExportedProperty: Codable, Equatable, Sendable { public var staticContext: StaticContext? public var documentation: String? + public var resolvedJSName: String { jsName ?? name } + public init( name: String, + jsName: String? = nil, type: BridgeType, isReadonly: Bool = false, isStatic: Bool = false, @@ -965,6 +974,7 @@ public struct ExportedProperty: Codable, Equatable, Sendable { documentation: String? = nil ) { self.name = name + self.jsName = jsName self.type = type self.isReadonly = isReadonly self.isStatic = isStatic @@ -1245,6 +1255,8 @@ public struct ImportedFunctionSkeleton: Codable { /// closure inits) that surface through this function's signature. public let accessLevel: BridgeJSAccessLevel + public var resolvedJSName: String { jsName ?? name } + public init( name: String, jsName: String? = nil, @@ -1336,6 +1348,8 @@ public struct ImportedGetterSkeleton: Codable { /// Source access level of the originating Swift declaration. public let accessLevel: BridgeJSAccessLevel + public var resolvedJSName: String { jsName ?? name } + public init( name: String, jsName: String? = nil, @@ -1396,6 +1410,8 @@ public struct ImportedSetterSkeleton: Codable { /// Source access level of the originating Swift declaration. public let accessLevel: BridgeJSAccessLevel + public var resolvedJSName: String { jsName ?? name } + public init( name: String, jsName: String? = nil, @@ -1458,6 +1474,8 @@ public struct ImportedTypeSkeleton: Codable { /// Source access level of the originating Swift `@JSClass` declaration. public let accessLevel: BridgeJSAccessLevel + public var resolvedJSName: String { jsName ?? name } + public init( name: String, jsName: String? = nil, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift index 316d51b41..5abdf8fb2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift @@ -658,6 +658,87 @@ import Testing } } + @Test + func jsNameOnClassDiagnostic() throws { + let source = """ + @JS("Renamed") class Box { @JS init() {} } + """ + let diagnostics = try #require(moduleDiagnostics(source: source)) + #expect(diagnostics.description.contains("A separate name for JavaScript is not supported here")) + } + + @Test + func jsNameOnStructDiagnostic() throws { + let source = """ + @JS("Renamed") struct Box { var x: Int } + """ + let diagnostics = try #require(moduleDiagnostics(source: source)) + #expect(diagnostics.description.contains("A separate name for JavaScript is not supported here")) + } + + @Test + func jsNameOnEnumDiagnostic() throws { + let source = """ + @JS("Renamed") enum Box { case a } + """ + let diagnostics = try #require(moduleDiagnostics(source: source)) + #expect(diagnostics.description.contains("A separate name for JavaScript is not supported here")) + } + + @Test + func jsNameOnProtocolDiagnostic() throws { + let source = """ + @JS("Renamed") protocol Box { func run() } + """ + let diagnostics = try #require(moduleDiagnostics(source: source)) + #expect(diagnostics.description.contains("A separate name for JavaScript is not supported here")) + } + + @Test + func jsNameOnInitializerDiagnostic() throws { + let source = """ + @JS class Box { @JS("create") init() {} } + """ + let diagnostics = try #require(moduleDiagnostics(source: source)) + #expect(diagnostics.description.contains("A separate name for JavaScript is not supported here")) + } + + @Test + func jsNameOnProtocolRequirementDiagnostic() throws { + let source = """ + @JS protocol Box { @JS("run") func run() } + """ + let diagnostics = try #require(moduleDiagnostics(source: source)) + #expect(diagnostics.description.contains("A separate name for JavaScript is not supported here")) + } + + @Test + func invalidJSNameDiagnostic() throws { + let source = """ + @JS("1notAnIdentifier") func a() -> Int { 42 } + @JS("has space") func b() -> Int { 42 } + @JS("has-dash") func c() -> Int { 42 } + @JS("") func d() -> Int { 42 } + """ + let diagnostics = try #require(moduleDiagnostics(source: source)) + #expect(diagnostics.description.contains("`1notAnIdentifier` is not a valid JavaScript identifier")) + #expect(diagnostics.description.contains("`has space` is not a valid JavaScript identifier")) + #expect(diagnostics.description.contains("`has-dash` is not a valid JavaScript identifier")) + #expect(diagnostics.description.contains("`` is not a valid JavaScript identifier")) + } + + @Test + func jsNameOnMultipleBindingsDiagnostic() throws { + let source = """ + @JS class Box { + @JS init() {} + @JS("renamed") var first: Int = 1, second: Int = 2 + } + """ + let diagnostics = try #require(moduleDiagnostics(source: source)) + #expect(diagnostics.description.contains("Name targets declaration with multiple bindings")) + } + @Test func omitsNextLineWhenErrorIsOnLastLine() throws { let source = """ diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSNameOverride.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSNameOverride.swift new file mode 100644 index 000000000..fc5777a15 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/JSNameOverride.swift @@ -0,0 +1,40 @@ +@JS("makeGreeting") func renderGreeting(name: String) -> String + +@JS("greetName") func greet(_ name: String) -> String + +@JS("greetCount") func greet(_ count: Int) -> String + +@JS("namespacedRenamed", namespace: "Utils.Text") func namespacedFunction() -> Int + +@JS class RenamedMembers { + @JS("label") var title: String + @JS("total") let count: Int + @JS("sharedTotal") nonisolated(unsafe) static var sharedCount: Int = 0 + @JS("readOnlyLimit") static let limit: Int = 10 + + @JS init(title: String, count: Int) + @JS("makeGreeting") func greet() -> String + @JS("makeDefault") static func createDefault() -> RenamedMembers +} + +@JS struct RenamedVector { + var dx: Double + var dy: Double + + @JS("originVector") static let origin: RenamedVector = RenamedVector(dx: 0, dy: 0) + @JS("magnitude") func length() -> Double + @JS("fromPolar") static func polar(radius: Double, angle: Double) -> RenamedVector +} + +@JS enum RenamedEnumMembers { + case active + case inactive + + @JS("describeCase") static func describe() -> String + @JS("currentDefault") nonisolated(unsafe) static var defaultValue: String = "active" +} + +@JS enum RenamedNamespaceMembers { + @JS("plus") static func add(_ a: Int, _ b: Int) -> Int + @JS("theAnswer") nonisolated(unsafe) static var answer: Int = 42 +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSNameOverride.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSNameOverride.json new file mode 100644 index 000000000..c5cd01631 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSNameOverride.json @@ -0,0 +1,524 @@ +{ + "exported" : { + "aliases" : [ + + ], + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_RenamedMembers_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "title", + "name" : "title", + "type" : { + "string" : { + + } + } + }, + { + "label" : "count", + "name" : "count", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_RenamedMembers_makeGreeting", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "jsName" : "makeGreeting", + "name" : "greet", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_RenamedMembers_static_makeDefault", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "jsName" : "makeDefault", + "name" : "createDefault", + "parameters" : [ + + ], + "returnType" : { + "swiftHeapObject" : { + "_0" : "RenamedMembers" + } + }, + "staticContext" : { + "className" : { + "_0" : "RenamedMembers" + } + } + } + ], + "name" : "RenamedMembers", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "jsName" : "label", + "name" : "title", + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "jsName" : "total", + "name" : "count", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "isReadonly" : false, + "isStatic" : true, + "jsName" : "sharedTotal", + "name" : "sharedCount", + "staticContext" : { + "className" : { + "_0" : "RenamedMembers" + } + }, + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "isReadonly" : true, + "isStatic" : true, + "jsName" : "readOnlyLimit", + "name" : "limit", + "staticContext" : { + "className" : { + "_0" : "RenamedMembers" + } + }, + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "swiftCallName" : "RenamedMembers" + } + ], + "enums" : [ + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "active" + }, + { + "associatedValues" : [ + + ], + "name" : "inactive" + } + ], + "emitStyle" : "const", + "name" : "RenamedEnumMembers", + "staticMethods" : [ + { + "abiName" : "bjs_RenamedEnumMembers_static_describeCase", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "jsName" : "describeCase", + "name" : "describe", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + }, + "staticContext" : { + "enumName" : { + "_0" : "RenamedEnumMembers" + } + } + } + ], + "staticProperties" : [ + { + "isReadonly" : false, + "isStatic" : true, + "jsName" : "currentDefault", + "name" : "defaultValue", + "staticContext" : { + "enumName" : { + "_0" : "RenamedEnumMembers" + } + }, + "type" : { + "string" : { + + } + } + } + ], + "swiftCallName" : "RenamedEnumMembers", + "tsFullPath" : "RenamedEnumMembers" + }, + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "RenamedNamespaceMembers", + "staticMethods" : [ + { + "abiName" : "bjs_RenamedNamespaceMembers_static_plus", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "jsName" : "plus", + "name" : "add", + "namespace" : [ + "RenamedNamespaceMembers" + ], + "parameters" : [ + { + "label" : "_", + "name" : "a", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "label" : "_", + "name" : "b", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + }, + "staticContext" : { + "namespaceEnum" : { + "_0" : "RenamedNamespaceMembers" + } + } + } + ], + "staticProperties" : [ + { + "isReadonly" : false, + "isStatic" : true, + "jsName" : "theAnswer", + "name" : "answer", + "namespace" : [ + "RenamedNamespaceMembers" + ], + "staticContext" : { + "namespaceEnum" : { + "_0" : "RenamedNamespaceMembers" + } + }, + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "swiftCallName" : "RenamedNamespaceMembers", + "tsFullPath" : "RenamedNamespaceMembers" + } + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_makeGreeting", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "jsName" : "makeGreeting", + "name" : "renderGreeting", + "parameters" : [ + { + "label" : "name", + "name" : "name", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_greetName", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "jsName" : "greetName", + "name" : "greet", + "parameters" : [ + { + "label" : "_", + "name" : "name", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_greetCount", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "jsName" : "greetCount", + "name" : "greet", + "parameters" : [ + { + "label" : "_", + "name" : "count", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_Utils_Text_namespacedRenamed", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "jsName" : "namespacedRenamed", + "name" : "namespacedFunction", + "namespace" : [ + "Utils", + "Text" + ], + "parameters" : [ + + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + { + "methods" : [ + { + "abiName" : "bjs_RenamedVector_magnitude", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "jsName" : "magnitude", + "name" : "length", + "parameters" : [ + + ], + "returnType" : { + "double" : { + + } + } + }, + { + "abiName" : "bjs_RenamedVector_static_fromPolar", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "jsName" : "fromPolar", + "name" : "polar", + "parameters" : [ + { + "label" : "radius", + "name" : "radius", + "type" : { + "double" : { + + } + } + }, + { + "label" : "angle", + "name" : "angle", + "type" : { + "double" : { + + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "RenamedVector" + } + }, + "staticContext" : { + "structName" : { + "_0" : "RenamedVector" + } + } + } + ], + "name" : "RenamedVector", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "dx", + "type" : { + "double" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "dy", + "type" : { + "double" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : true, + "jsName" : "originVector", + "name" : "origin", + "staticContext" : { + "structName" : { + "_0" : "RenamedVector" + } + }, + "type" : { + "swiftStruct" : { + "_0" : "RenamedVector" + } + } + } + ], + "swiftCallName" : "RenamedVector" + } + ] + }, + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSNameOverride.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSNameOverride.swift new file mode 100644 index 000000000..b525b5152 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSNameOverride.swift @@ -0,0 +1,351 @@ +extension RenamedEnumMembers: _BridgedSwiftCaseEnum { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + return bridgeJSRawValue + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> RenamedEnumMembers { + return bridgeJSLiftParameter(value) + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> RenamedEnumMembers { + return RenamedEnumMembers(bridgeJSRawValue: value)! + } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { + return bridgeJSLowerParameter() + } + + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { + switch bridgeJSRawValue { + case 0: + self = .active + case 1: + self = .inactive + default: + return nil + } + } + + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { + switch self { + case .active: + return 0 + case .inactive: + return 1 + } + } +} + +@_expose(wasm, "bjs_RenamedEnumMembers_static_describeCase") +@_cdecl("bjs_RenamedEnumMembers_static_describeCase") +public func _bjs_RenamedEnumMembers_static_describeCase() -> Void { + #if arch(wasm32) + let ret = RenamedEnumMembers.describe() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_RenamedEnumMembers_static_defaultValue_get") +@_cdecl("bjs_RenamedEnumMembers_static_defaultValue_get") +public func _bjs_RenamedEnumMembers_static_defaultValue_get() -> Void { + #if arch(wasm32) + let ret = RenamedEnumMembers.defaultValue + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_RenamedEnumMembers_static_defaultValue_set") +@_cdecl("bjs_RenamedEnumMembers_static_defaultValue_set") +public func _bjs_RenamedEnumMembers_static_defaultValue_set(_ valueBytes: Int32, _ valueLength: Int32) -> Void { + #if arch(wasm32) + RenamedEnumMembers.defaultValue = String.bridgeJSLiftParameter(valueBytes, valueLength) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_RenamedNamespaceMembers_static_plus") +@_cdecl("bjs_RenamedNamespaceMembers_static_plus") +public func _bjs_RenamedNamespaceMembers_static_plus(_ a: Int32, _ b: Int32) -> Int32 { + #if arch(wasm32) + let ret = RenamedNamespaceMembers.add(_: Int.bridgeJSLiftParameter(a), _: Int.bridgeJSLiftParameter(b)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_RenamedNamespaceMembers_static_answer_get") +@_cdecl("bjs_RenamedNamespaceMembers_static_answer_get") +public func _bjs_RenamedNamespaceMembers_static_answer_get() -> Int32 { + #if arch(wasm32) + let ret = RenamedNamespaceMembers.answer + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_RenamedNamespaceMembers_static_answer_set") +@_cdecl("bjs_RenamedNamespaceMembers_static_answer_set") +public func _bjs_RenamedNamespaceMembers_static_answer_set(_ value: Int32) -> Void { + #if arch(wasm32) + RenamedNamespaceMembers.answer = Int.bridgeJSLiftParameter(value) + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension RenamedVector: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> RenamedVector { + let dy = Double.bridgeJSStackPop() + let dx = Double.bridgeJSStackPop() + return RenamedVector(dx: dx, dy: dy) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.dx.bridgeJSStackPush() + self.dy.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_RenamedVector(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_RenamedVector())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_RenamedVector") +fileprivate func _bjs_struct_lower_RenamedVector_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_RenamedVector_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_RenamedVector(_ objectId: Int32) -> Void { + return _bjs_struct_lower_RenamedVector_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_RenamedVector") +fileprivate func _bjs_struct_lift_RenamedVector_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_RenamedVector_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_RenamedVector() -> Int32 { + return _bjs_struct_lift_RenamedVector_extern() +} + +@_expose(wasm, "bjs_RenamedVector_static_origin_get") +@_cdecl("bjs_RenamedVector_static_origin_get") +public func _bjs_RenamedVector_static_origin_get() -> Void { + #if arch(wasm32) + let ret = RenamedVector.origin + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_RenamedVector_magnitude") +@_cdecl("bjs_RenamedVector_magnitude") +public func _bjs_RenamedVector_magnitude() -> Float64 { + #if arch(wasm32) + let ret = RenamedVector.bridgeJSLiftParameter().length() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_RenamedVector_static_fromPolar") +@_cdecl("bjs_RenamedVector_static_fromPolar") +public func _bjs_RenamedVector_static_fromPolar(_ radius: Float64, _ angle: Float64) -> Void { + #if arch(wasm32) + let ret = RenamedVector.polar(radius: Double.bridgeJSLiftParameter(radius), angle: Double.bridgeJSLiftParameter(angle)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_makeGreeting") +@_cdecl("bjs_makeGreeting") +public func _bjs_makeGreeting(_ nameBytes: Int32, _ nameLength: Int32) -> Void { + #if arch(wasm32) + let ret = renderGreeting(name: String.bridgeJSLiftParameter(nameBytes, nameLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_greetName") +@_cdecl("bjs_greetName") +public func _bjs_greetName(_ nameBytes: Int32, _ nameLength: Int32) -> Void { + #if arch(wasm32) + let ret = greet(_: String.bridgeJSLiftParameter(nameBytes, nameLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_greetCount") +@_cdecl("bjs_greetCount") +public func _bjs_greetCount(_ count: Int32) -> Void { + #if arch(wasm32) + let ret = greet(_: Int.bridgeJSLiftParameter(count)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Utils_Text_namespacedRenamed") +@_cdecl("bjs_Utils_Text_namespacedRenamed") +public func _bjs_Utils_Text_namespacedRenamed() -> Int32 { + #if arch(wasm32) + let ret = namespacedFunction() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_RenamedMembers_init") +@_cdecl("bjs_RenamedMembers_init") +public func _bjs_RenamedMembers_init(_ titleBytes: Int32, _ titleLength: Int32, _ count: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = RenamedMembers(title: String.bridgeJSLiftParameter(titleBytes, titleLength), count: Int.bridgeJSLiftParameter(count)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_RenamedMembers_makeGreeting") +@_cdecl("bjs_RenamedMembers_makeGreeting") +public func _bjs_RenamedMembers_makeGreeting(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = RenamedMembers.bridgeJSLiftParameter(_self).greet() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_RenamedMembers_static_makeDefault") +@_cdecl("bjs_RenamedMembers_static_makeDefault") +public func _bjs_RenamedMembers_static_makeDefault() -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = RenamedMembers.createDefault() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_RenamedMembers_title_get") +@_cdecl("bjs_RenamedMembers_title_get") +public func _bjs_RenamedMembers_title_get(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = RenamedMembers.bridgeJSLiftParameter(_self).title + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_RenamedMembers_title_set") +@_cdecl("bjs_RenamedMembers_title_set") +public func _bjs_RenamedMembers_title_set(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + #if arch(wasm32) + RenamedMembers.bridgeJSLiftParameter(_self).title = String.bridgeJSLiftParameter(valueBytes, valueLength) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_RenamedMembers_count_get") +@_cdecl("bjs_RenamedMembers_count_get") +public func _bjs_RenamedMembers_count_get(_ _self: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let ret = RenamedMembers.bridgeJSLiftParameter(_self).count + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_RenamedMembers_static_sharedCount_get") +@_cdecl("bjs_RenamedMembers_static_sharedCount_get") +public func _bjs_RenamedMembers_static_sharedCount_get() -> Int32 { + #if arch(wasm32) + let ret = RenamedMembers.sharedCount + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_RenamedMembers_static_sharedCount_set") +@_cdecl("bjs_RenamedMembers_static_sharedCount_set") +public func _bjs_RenamedMembers_static_sharedCount_set(_ value: Int32) -> Void { + #if arch(wasm32) + RenamedMembers.sharedCount = Int.bridgeJSLiftParameter(value) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_RenamedMembers_static_limit_get") +@_cdecl("bjs_RenamedMembers_static_limit_get") +public func _bjs_RenamedMembers_static_limit_get() -> Int32 { + #if arch(wasm32) + let ret = RenamedMembers.limit + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_RenamedMembers_deinit") +@_cdecl("bjs_RenamedMembers_deinit") +public func _bjs_RenamedMembers_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension RenamedMembers: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_RenamedMembers_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_RenamedMembers_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_RenamedMembers_wrap") +fileprivate func _bjs_RenamedMembers_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_RenamedMembers_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_RenamedMembers_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_RenamedMembers_wrap_extern(pointer) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.d.ts new file mode 100644 index 000000000..d31aeebe3 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.d.ts @@ -0,0 +1,68 @@ +// 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`. + +export const RenamedEnumMembersValues: { + readonly Active: 0; + readonly Inactive: 1; +}; +export type RenamedEnumMembersTag = typeof RenamedEnumMembersValues[keyof typeof RenamedEnumMembersValues]; + +export interface RenamedVector { + dx: number; + dy: number; + magnitude(): number; +} +export type RenamedEnumMembersObject = typeof RenamedEnumMembersValues & { + describeCase(): string; + currentDefault: string; +}; + +/// Represents a Swift heap object like a class instance or an actor instance. +export interface SwiftHeapObject { + /// Release the heap object. + /// + /// Note: Calling this method will release the heap object and it will no longer be accessible. + release(): void; +} +export interface RenamedMembers extends SwiftHeapObject { + makeGreeting(): string; + label: string; + readonly total: number; +} +export type Exports = { + makeGreeting(name: string): string; + greetName(name: string): string; + greetCount(count: number): string; + RenamedEnumMembers: RenamedEnumMembersObject + RenamedMembers: { + new(title: string, count: number): RenamedMembers; + makeDefault(): RenamedMembers; + sharedTotal: number; + readonly readOnlyLimit: number; + }, + RenamedNamespaceMembers: { + theAnswer: number; + plus(a: number, b: number): number; + }, + RenamedVector: { + readonly originVector: RenamedVector; + fromPolar(radius: number, angle: number): RenamedVector; + }, + Utils: { + Text: { + namespacedRenamed(): number; + }, + }, +} +export type Imports = { +} +export function createInstantiator(options: { + imports: Imports; +}, swift: any): Promise<{ + addImports: (importObject: WebAssembly.Imports) => void; + setInstance: (instance: WebAssembly.Instance) => void; + createExports: (instance: WebAssembly.Instance) => Exports; +}>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.js new file mode 100644 index 000000000..543ae05f0 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.js @@ -0,0 +1,442 @@ +// 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`. + +export const RenamedEnumMembersValues = { + Active: 0, + Inactive: 1, +}; + +export async function createInstantiator(options, swift) { + let instance; + let memory; + let setException; + let decodeString; + const textDecoder = new TextDecoder("utf-8"); + const textEncoder = new TextEncoder("utf-8"); + let tmpRetString; + let tmpRetBytes; + let tmpRetException; + let tmpRetOptionalBool; + let tmpRetOptionalInt; + let tmpRetOptionalFloat; + let tmpRetOptionalDouble; + let tmpRetOptionalHeapObject; + let strStack = []; + let i32Stack = []; + let i64Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; + let taStack = []; + const enumHelpers = {}; + const structHelpers = {}; + + let _exports = null; + let bjs = null; + const __bjs_createRenamedVectorHelpers = () => ({ + lower: (value) => { + f64Stack.push(value.dx); + f64Stack.push(value.dy); + }, + lift: () => { + const f64 = f64Stack.pop(); + const f641 = f64Stack.pop(); + const instance1 = { dx: f641, dy: f64 }; + instance1.magnitude = function() { + structHelpers.RenamedVector.lower(this); + const ret = instance.exports.bjs_RenamedVector_magnitude(); + return ret; + }.bind(instance1); + return instance1; + } + }); + + return { + /** + * @param {WebAssembly.Imports} importObject + */ + addImports: (importObject, importsContext) => { + bjs = {}; + importObject["bjs"] = bjs; + bjs["swift_js_return_string"] = function(ptr, len) { + tmpRetString = decodeString(ptr, len); + } + bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { + const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); + bytes.set(source); + } + bjs["swift_js_make_js_string"] = function(ptr, len) { + return swift.memory.retain(decodeString(ptr, len)); + } + bjs["swift_js_init_memory_with_result"] = function(ptr, len) { + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); + target.set(tmpRetBytes); + tmpRetBytes = undefined; + } + bjs["swift_js_throw"] = function(id) { + tmpRetException = swift.memory.retainByRef(id); + } + bjs["swift_js_retain"] = function(id) { + return swift.memory.retainByRef(id); + } + bjs["swift_js_release"] = function(id) { + swift.memory.release(id); + } + bjs["swift_js_push_i32"] = function(v) { + i32Stack.push(v | 0); + } + bjs["swift_js_push_f32"] = function(v) { + f32Stack.push(Math.fround(v)); + } + bjs["swift_js_push_f64"] = function(v) { + f64Stack.push(v); + } + bjs["swift_js_push_string"] = function(ptr, len) { + const value = decodeString(ptr, len); + strStack.push(value); + } + bjs["swift_js_pop_i32"] = function() { + return i32Stack.pop(); + } + bjs["swift_js_pop_f32"] = function() { + return f32Stack.pop(); + } + bjs["swift_js_pop_f64"] = function() { + return f64Stack.pop(); + } + bjs["swift_js_push_pointer"] = function(pointer) { + ptrStack.push(pointer); + } + bjs["swift_js_pop_pointer"] = function() { + return ptrStack.pop(); + } + bjs["swift_js_push_i64"] = function(v) { + i64Stack.push(v); + } + bjs["swift_js_pop_i64"] = function() { + return i64Stack.pop(); + } + const taCtors = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array]; + bjs["swift_js_push_typed_array"] = function(kind, ptr, count) { + const Ctor = taCtors[kind]; + const byteLen = count * Ctor.BYTES_PER_ELEMENT; + const copy = memory.buffer.slice(ptr, ptr + byteLen); + taStack.push(Array.from(new Ctor(copy))); + } + bjs["swift_js_struct_lower_RenamedVector"] = function(objectId) { + structHelpers.RenamedVector.lower(swift.memory.getObject(objectId)); + } + bjs["swift_js_struct_lift_RenamedVector"] = function() { + const value = structHelpers.RenamedVector.lift(); + return swift.memory.retain(value); + } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } + bjs["swift_js_return_optional_bool"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalBool = null; + } else { + tmpRetOptionalBool = value !== 0; + } + } + bjs["swift_js_return_optional_int"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalInt = null; + } else { + tmpRetOptionalInt = value | 0; + } + } + bjs["swift_js_return_optional_float"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalFloat = null; + } else { + tmpRetOptionalFloat = Math.fround(value); + } + } + bjs["swift_js_return_optional_double"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalDouble = null; + } else { + tmpRetOptionalDouble = value; + } + } + bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = decodeString(ptr, len); + } + } + bjs["swift_js_return_optional_object"] = function(isSome, objectId) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = swift.memory.getObject(objectId); + } + } + bjs["swift_js_return_optional_heap_object"] = function(isSome, pointer) { + if (isSome === 0) { + tmpRetOptionalHeapObject = null; + } else { + tmpRetOptionalHeapObject = pointer; + } + } + bjs["swift_js_get_optional_int_presence"] = function() { + return tmpRetOptionalInt != null ? 1 : 0; + } + bjs["swift_js_get_optional_int_value"] = function() { + const value = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; + return value; + } + bjs["swift_js_get_optional_string"] = function() { + const str = tmpRetString; + tmpRetString = undefined; + if (str == null) { + return -1; + } else { + const bytes = textEncoder.encode(str); + tmpRetBytes = bytes; + return bytes.length; + } + } + bjs["swift_js_get_optional_float_presence"] = function() { + return tmpRetOptionalFloat != null ? 1 : 0; + } + bjs["swift_js_get_optional_float_value"] = function() { + const value = tmpRetOptionalFloat; + tmpRetOptionalFloat = undefined; + return value; + } + bjs["swift_js_get_optional_double_presence"] = function() { + return tmpRetOptionalDouble != null ? 1 : 0; + } + bjs["swift_js_get_optional_double_value"] = function() { + const value = tmpRetOptionalDouble; + tmpRetOptionalDouble = undefined; + return value; + } + bjs["swift_js_get_optional_heap_object_pointer"] = function() { + const pointer = tmpRetOptionalHeapObject; + tmpRetOptionalHeapObject = undefined; + return pointer || 0; + } + bjs["swift_js_closure_unregister"] = function(funcRef) {} + // Wrapper functions for module: TestModule + if (!importObject["TestModule"]) { + importObject["TestModule"] = {}; + } + importObject["TestModule"]["bjs_RenamedMembers_wrap"] = function(pointer) { + const obj = _exports['RenamedMembers'].__construct(pointer); + return swift.memory.retain(obj); + }; + }, + setInstance: (i) => { + instance = i; + memory = instance.exports.memory; + + decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + + setException = (error) => { + instance.exports._swift_js_exception.value = swift.memory.retain(error) + } + }, + /** @param {WebAssembly.Instance} instance */ + createExports: (instance) => { + const js = swift.memory.heap; + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.identityMap?.delete(state.pointer); + state.deinit(state.pointer); + }); + + /// Represents a Swift heap object like a class instance or an actor instance. + class SwiftHeapObject { + static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; + const makeFresh = (identityMap) => { + const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false, identityMap }; + obj.pointer = pointer; + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); + if (identityMap) { + identityMap.set(pointer, new WeakRef(obj)); + } + return obj; + }; + + if (!identityCache) { + return makeFresh(null); + } + + const cached = identityCache.get(pointer)?.deref(); + if (cached && !cached.__swiftHeapObjectState.hasReleased) { + deinit(pointer); + return cached; + } + if (identityCache.has(pointer)) { + identityCache.delete(pointer); + } + + return makeFresh(identityCache); + } + + release() { + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.identityMap?.delete(state.pointer); + state.deinit(state.pointer); + } + } + class RenamedMembers extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_RenamedMembers_deinit, RenamedMembers.prototype, null); + } + + constructor(title, count) { + const titleBytes = textEncoder.encode(title); + const titleId = swift.memory.retain(titleBytes); + const ret = instance.exports.bjs_RenamedMembers_init(titleId, titleBytes.length, count); + return RenamedMembers.__construct(ret); + } + makeGreeting() { + instance.exports.bjs_RenamedMembers_makeGreeting(this.pointer); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + } + static makeDefault() { + const ret = instance.exports.bjs_RenamedMembers_static_makeDefault(); + return RenamedMembers.__construct(ret); + } + get label() { + instance.exports.bjs_RenamedMembers_title_get(this.pointer); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + } + set label(value) { + const valueBytes = textEncoder.encode(value); + const valueId = swift.memory.retain(valueBytes); + instance.exports.bjs_RenamedMembers_title_set(this.pointer, valueId, valueBytes.length); + } + get total() { + const ret = instance.exports.bjs_RenamedMembers_count_get(this.pointer); + return ret; + } + static get sharedTotal() { + const ret = instance.exports.bjs_RenamedMembers_static_sharedCount_get(); + return ret; + } + static set sharedTotal(value) { + instance.exports.bjs_RenamedMembers_static_sharedCount_set(value); + } + static get readOnlyLimit() { + const ret = instance.exports.bjs_RenamedMembers_static_limit_get(); + return ret; + } + } + const RenamedVectorHelpers = __bjs_createRenamedVectorHelpers(); + structHelpers.RenamedVector = RenamedVectorHelpers; + + const exports = { + makeGreeting: function bjs_makeGreeting(name) { + const nameBytes = textEncoder.encode(name); + const nameId = swift.memory.retain(nameBytes); + instance.exports.bjs_makeGreeting(nameId, nameBytes.length); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + }, + greetName: function bjs_greetName(name) { + const nameBytes = textEncoder.encode(name); + const nameId = swift.memory.retain(nameBytes); + instance.exports.bjs_greetName(nameId, nameBytes.length); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + }, + greetCount: function bjs_greetCount(count) { + instance.exports.bjs_greetCount(count); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + }, + RenamedEnumMembers: { + ...RenamedEnumMembersValues, + describeCase: function() { + instance.exports.bjs_RenamedEnumMembers_static_describeCase(); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + }, + get currentDefault() { + instance.exports.bjs_RenamedEnumMembers_static_defaultValue_get(); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + }, + set currentDefault(value) { + const valueBytes = textEncoder.encode(value); + const valueId = swift.memory.retain(valueBytes); + instance.exports.bjs_RenamedEnumMembers_static_defaultValue_set(valueId, valueBytes.length); + } + }, + RenamedMembers, + RenamedNamespaceMembers: { + get theAnswer() { + const ret = instance.exports.bjs_RenamedNamespaceMembers_static_answer_get(); + return ret; + }, + set theAnswer(value) { + instance.exports.bjs_RenamedNamespaceMembers_static_answer_set(value); + }, + plus: function bjs_RenamedNamespaceMembers_static_plus(a, b) { + const ret = instance.exports.bjs_RenamedNamespaceMembers_static_plus(a, b); + return ret; + }, + }, + RenamedVector: { + get originVector() { + instance.exports.bjs_RenamedVector_static_origin_get(); + const structValue = structHelpers.RenamedVector.lift(); + return structValue; + }, + fromPolar: function(radius, angle) { + instance.exports.bjs_RenamedVector_static_fromPolar(radius, angle); + const structValue = structHelpers.RenamedVector.lift(); + return structValue; + }, + }, + Utils: { + Text: { + namespacedRenamed: function bjs_Utils_Text_namespacedRenamed() { + const ret = instance.exports.bjs_Utils_Text_namespacedRenamed(); + return ret; + }, + }, + }, + }; + _exports = exports; + return exports; + }, + } +} \ No newline at end of file diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Function.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Function.md index c26841041..098a931af 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Function.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Exporting-Swift/Exporting-Swift-Function.md @@ -37,6 +37,27 @@ export type Exports = { } ``` +### Renaming functions in JavaScript + +If a different name is more appropriate in JavaScript or to export multiple overloaded Swift functions with distinct JavaScript names, you can pass a JavaScript identifier as the first argument to `@JS`. + +```swift +import JavaScriptKit + +@JS("greetName") public func greet(_ name: String) -> String { + return "Hello, \(name)!" +} + +@JS("greetPerson") public func greet(_ person: Person) -> String { + return "Hello, \(person.name)!" +} +``` + +```javascript +exports.greetName("World"); +exports.greetPerson({ name: "World" }); +``` + ### Throwing functions Swift functions can throw JavaScript errors using `throws(JSException)`. diff --git a/Sources/JavaScriptKit/Macros.swift b/Sources/JavaScriptKit/Macros.swift index 2750f8268..a1cdc0c44 100644 --- a/Sources/JavaScriptKit/Macros.swift +++ b/Sources/JavaScriptKit/Macros.swift @@ -140,6 +140,7 @@ public enum JSName: ExpressibleByStringLiteral { /// /// For detailed usage information, see the article . /// +/// - Parameter name: A different name to use in the exported JavaScript. /// - Parameter namespace: A dot-separated string that defines the namespace hierarchy in JavaScript. /// Each segment becomes a nested object in the resulting JavaScript structure. /// - Parameter enumStyle: Controls how enums are emitted to TypeScript for this declaration: @@ -151,6 +152,7 @@ public enum JSName: ExpressibleByStringLiteral { /// - Important: This feature is still experimental. No API stability is guaranteed, and the API may change in future releases. @attached(peer) public macro JS( + _ name: String? = nil, as aliasOf: Any.Type? = nil, namespace: String? = nil, enumStyle: JSEnumStyle = .const, diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index c9db5b2ac..6c5fe3b05 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -9825,6 +9825,39 @@ public func _bjs_makeAdder(_ base: Int32) -> Int32 { #endif } +@_expose(wasm, "bjs_renamedEcho") +@_cdecl("bjs_renamedEcho") +public func _bjs_renamedEcho(_ valueBytes: Int32, _ valueLength: Int32) -> Void { + #if arch(wasm32) + let ret = jsNameEcho(_: String.bridgeJSLiftParameter(valueBytes, valueLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_greetName") +@_cdecl("bjs_greetName") +public func _bjs_greetName(_ nameBytes: Int32, _ nameLength: Int32) -> Void { + #if arch(wasm32) + let ret = greet(_: String.bridgeJSLiftParameter(nameBytes, nameLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_greetCount") +@_cdecl("bjs_greetCount") +public func _bjs_greetCount(_ count: Int32) -> Void { + #if arch(wasm32) + let ret = greet(_: Int.bridgeJSLiftParameter(count)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_roundTripPointerFields") @_cdecl("bjs_roundTripPointerFields") public func _bjs_roundTripPointerFields() -> Void { @@ -13173,6 +13206,91 @@ fileprivate func _bjs_NestedTypeHost_wrap_extern(_ pointer: UnsafeMutableRawPoin return _bjs_NestedTypeHost_wrap_extern(pointer) } +@_expose(wasm, "bjs_JSNameRenamedClass_init") +@_cdecl("bjs_JSNameRenamedClass_init") +public func _bjs_JSNameRenamedClass_init(_ value: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = JSNameRenamedClass(value: Int.bridgeJSLiftParameter(value)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_JSNameRenamedClass_doubled") +@_cdecl("bjs_JSNameRenamedClass_doubled") +public func _bjs_JSNameRenamedClass_doubled(_ _self: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let ret = JSNameRenamedClass.bridgeJSLiftParameter(_self).timesTwo() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_JSNameRenamedClass_static_makeWithValue") +@_cdecl("bjs_JSNameRenamedClass_static_makeWithValue") +public func _bjs_JSNameRenamedClass_static_makeWithValue(_ value: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = JSNameRenamedClass.create(value: Int.bridgeJSLiftParameter(value)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_JSNameRenamedClass_value_get") +@_cdecl("bjs_JSNameRenamedClass_value_get") +public func _bjs_JSNameRenamedClass_value_get(_ _self: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let ret = JSNameRenamedClass.bridgeJSLiftParameter(_self).value + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_JSNameRenamedClass_value_set") +@_cdecl("bjs_JSNameRenamedClass_value_set") +public func _bjs_JSNameRenamedClass_value_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { + #if arch(wasm32) + JSNameRenamedClass.bridgeJSLiftParameter(_self).value = Int.bridgeJSLiftParameter(value) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_JSNameRenamedClass_deinit") +@_cdecl("bjs_JSNameRenamedClass_deinit") +public func _bjs_JSNameRenamedClass_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension JSNameRenamedClass: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_JSNameRenamedClass_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_JSNameRenamedClass_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_JSNameRenamedClass_wrap") +fileprivate func _bjs_JSNameRenamedClass_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_JSNameRenamedClass_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_JSNameRenamedClass_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_JSNameRenamedClass_wrap_extern(pointer) +} + @_expose(wasm, "bjs_OptionalHolder_init") @_cdecl("bjs_OptionalHolder_init") public func _bjs_OptionalHolder_init(_ nullableGreeterIsSome: Int32, _ nullableGreeterValue: UnsafeMutableRawPointer, _ undefinedNumberIsSome: Int32, _ undefinedNumberValue: Float64) -> UnsafeMutableRawPointer { diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index c68d264e2..d4e1878e1 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -4840,6 +4840,105 @@ ], "swiftCallName" : "NestedTypeHost" }, + { + "constructor" : { + "abiName" : "bjs_JSNameRenamedClass_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_JSNameRenamedClass_doubled", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "jsName" : "doubled", + "name" : "timesTwo", + "parameters" : [ + + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "abiName" : "bjs_JSNameRenamedClass_static_makeWithValue", + "effects" : { + "isAsync" : false, + "isStatic" : true, + "isThrows" : false + }, + "jsName" : "makeWithValue", + "name" : "create", + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "swiftHeapObject" : { + "_0" : "JSNameRenamedClass" + } + }, + "staticContext" : { + "className" : { + "_0" : "JSNameRenamedClass" + } + } + } + ], + "name" : "JSNameRenamedClass", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "jsName" : "current", + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "swiftCallName" : "JSNameRenamedClass" + }, { "constructor" : { "abiName" : "bjs_OptionalHolder_init", @@ -16832,6 +16931,87 @@ } } }, + { + "abiName" : "bjs_renamedEcho", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "jsName" : "renamedEcho", + "name" : "jsNameEcho", + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_greetName", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "jsName" : "greetName", + "name" : "greet", + "parameters" : [ + { + "label" : "_", + "name" : "name", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_greetCount", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "jsName" : "greetCount", + "name" : "greet", + "parameters" : [ + { + "label" : "_", + "name" : "count", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, { "abiName" : "bjs_roundTripPointerFields", "effects" : { diff --git a/Tests/BridgeJSRuntimeTests/JSNameAPIs.swift b/Tests/BridgeJSRuntimeTests/JSNameAPIs.swift new file mode 100644 index 000000000..48efcff59 --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/JSNameAPIs.swift @@ -0,0 +1,34 @@ +import JavaScriptKit + +@JS("renamedEcho") func jsNameEcho(_ value: String) -> String { + return "echo: \(value)" +} + +@JS("greetName") func greet(_ name: String) -> String { + return "Hello, \(name)!" +} + +@JS("greetCount") func greet(_ count: Int) -> String { + return "Hello, \(count) people!" +} + +@JS class JSNameRenamedClass { + private var storage: Int + + @JS init(value: Int) { + self.storage = value + } + + @JS("current") var value: Int { + get { storage } + set { storage = newValue } + } + + @JS("doubled") func timesTwo() -> Int { + return storage * 2 + } + + @JS("makeWithValue") static func create(value: Int) -> JSNameRenamedClass { + return JSNameRenamedClass(value: value) + } +} diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index 931d42561..9ca873301 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -281,6 +281,18 @@ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { assert.equal(exports.roundTripUnsafeMutablePointer(p), p); } + assert.equal(exports.renamedEcho("hi"), "echo: hi"); + assert.equal(exports.jsNameEcho, undefined); + assert.equal(exports.greetName("John"), "Hello, John!"); + assert.equal(exports.greetCount(3), "Hello, 3 people!"); + const renamed = new exports.JSNameRenamedClass(21); + assert.equal(renamed.doubled(), 42); + assert.equal(renamed.current, 21); + renamed.current = 5; + assert.equal(renamed.doubled(), 10); + const madeRenamed = exports.JSNameRenamedClass.makeWithValue(7); + assert.equal(madeRenamed.current, 7); + const g = new exports.Greeter("John"); assert.equal(g.greet(), "Hello, John!"); From ccd828beef2de161915474cb11e954923be8aac7 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Mon, 10 Aug 2026 15:32:57 +0200 Subject: [PATCH 37/50] BridgeJS: Support generic functions on imported JS APIs --- Benchmarks/Sources/Generated/BridgeJS.swift | 66 +- Examples/Embedded/Package.swift | 3 + .../Embedded/Sources/EmbeddedApp/main.swift | 18 + Examples/Embedded/index.html | 8 +- .../PlayBridgeJS/Generated/BridgeJS.swift | 46 +- Plugins/BridgeJS/README.md | 2 +- .../Sources/BridgeJSCore/ExportSwift.swift | 109 +- .../Sources/BridgeJSCore/ImportTS.swift | 79 +- .../BridgeJSCore/SwiftToSkeleton.swift | 256 +++- .../Sources/BridgeJSLink/BridgeJSLink.swift | 211 ++- .../Sources/BridgeJSLink/JSGlueGen.swift | 577 +++++--- .../BridgeJSSkeleton/BridgeJSSkeleton.swift | 171 ++- .../Sources/BridgeJSTool/BridgeJSTool.swift | 5 +- .../BridgeJSToolInternal.swift | 3 +- .../BridgeJSCodegenTests/Alias.json | 2 + .../BridgeJSCodegenTests/Alias.swift | 12 + .../BridgeJSCodegenTests/AliasInClosure.json | 1 + .../BridgeJSCodegenTests/AliasInClosure.swift | 4 + .../BridgeJSCodegenTests/ArrayTypes.swift | 12 + .../BridgeJSCodegenTests/Async.swift | 12 + .../AsyncAssociatedValueEnum.swift | 4 + .../ClassWithNestedTypes.swift | 8 + .../DefaultParameters.swift | 12 + .../DictionaryTypes.swift | 4 + .../BridgeJSCodegenTests/DocComments.swift | 8 + .../BridgeJSCodegenTests/EnumAlias.json | 1 + .../BridgeJSCodegenTests/EnumAlias.swift | 4 + .../EnumAssociatedValue.swift | 44 + .../EnumAssociatedValueImport.swift | 4 + .../BridgeJSCodegenTests/EnumCase.swift | 16 + .../BridgeJSCodegenTests/EnumCaseImport.swift | 4 + .../EnumNamespace.Global.swift | 16 + .../BridgeJSCodegenTests/EnumNamespace.swift | 16 + .../BridgeJSCodegenTests/EnumRawType.swift | 48 + .../ImportedTypeInExportedInterface.swift | 4 + .../BridgeJSCodegenTests/JSNameOverride.swift | 8 + .../BridgeJSCodegenTests/NestedType.swift | 8 + .../BridgeJSCodegenTests/Protocol.swift | 16 + .../StaticFunctions.Global.swift | 8 + .../StaticFunctions.swift | 8 + .../StaticProperties.Global.swift | 4 + .../StaticProperties.swift | 4 + .../StructWithNestedTypes.swift | 28 + .../BridgeJSCodegenTests/SwiftClosure.swift | 20 + .../BridgeJSCodegenTests/SwiftStruct.swift | 36 + .../SwiftStructImports.swift | 4 + .../BridgeJSCodegenTests/UnsafePointer.swift | 4 + .../BridgeJSLinkTests/Alias.d.ts | 1 + .../__Snapshots__/BridgeJSLinkTests/Alias.js | 395 ++++- .../BridgeJSLinkTests/AliasInClosure.d.ts | 1 + .../BridgeJSLinkTests/AliasInClosure.js | 1 + .../BridgeJSLinkTests/ArrayTypes.d.ts | 1 + .../BridgeJSLinkTests/ArrayTypes.js | 1290 ++++++++--------- .../BridgeJSLinkTests/Async.d.ts | 1 + .../__Snapshots__/BridgeJSLinkTests/Async.js | 336 ++++- .../AsyncAssociatedValueEnum.d.ts | 1 + .../AsyncAssociatedValueEnum.js | 1 + .../BridgeJSLinkTests/AsyncImport.d.ts | 1 + .../BridgeJSLinkTests/AsyncStaticImport.d.ts | 1 + .../ClassWithNestedTypes.d.ts | 1 + .../BridgeJSLinkTests/ClassWithNestedTypes.js | 1 + .../BridgeJSLinkTests/DefaultParameters.d.ts | 1 + .../BridgeJSLinkTests/DefaultParameters.js | 431 ++++-- .../BridgeJSLinkTests/DictionaryTypes.d.ts | 1 + .../BridgeJSLinkTests/DictionaryTypes.js | 538 ++++--- .../BridgeJSLinkTests/DocComments.d.ts | 1 + .../BridgeJSLinkTests/DocComments.js | 1 + .../BridgeJSLinkTests/EnumAlias.d.ts | 1 + .../BridgeJSLinkTests/EnumAlias.js | 1 + .../EnumAssociatedValue.d.ts | 1 + .../BridgeJSLinkTests/EnumAssociatedValue.js | 629 +++++--- .../EnumAssociatedValueImport.d.ts | 1 + .../EnumAssociatedValueImport.js | 1 + .../BridgeJSLinkTests/EnumCase.d.ts | 1 + .../BridgeJSLinkTests/EnumCase.js | 1 + .../BridgeJSLinkTests/EnumCaseImport.d.ts | 1 + .../BridgeJSLinkTests/EnumCaseImport.js | 1 + .../EnumNamespace.Global.d.ts | 1 + .../BridgeJSLinkTests/EnumNamespace.Global.js | 1 + .../BridgeJSLinkTests/EnumNamespace.d.ts | 1 + .../BridgeJSLinkTests/EnumNamespace.js | 1 + .../BridgeJSLinkTests/EnumRawType.d.ts | 1 + .../BridgeJSLinkTests/EnumRawType.js | 351 ++++- .../BridgeJSLinkTests/FixedWidthIntegers.d.ts | 1 + .../BridgeJSLinkTests/GlobalGetter.d.ts | 1 + .../BridgeJSLinkTests/GlobalThisImports.d.ts | 1 + .../IdentityModeClass.ConfigPointer.d.ts | 1 + .../IdentityModeClass.PerClass.d.ts | 1 + .../BridgeJSLinkTests/IdentityModeClass.d.ts | 1 + .../BridgeJSLinkTests/ImportArray.d.ts | 1 + .../BridgeJSLinkTests/ImportArray.js | 393 ++++- .../ImportedTypeInExportedInterface.d.ts | 1 + .../ImportedTypeInExportedInterface.js | 452 +++++- .../InvalidPropertyNames.d.ts | 1 + .../BridgeJSLinkTests/JSClass.d.ts | 1 + .../JSClassStaticFunctions.d.ts | 1 + .../BridgeJSLinkTests/JSImportBareModule.d.ts | 1 + .../JSImportBareModuleFallback.d.ts | 1 + .../BridgeJSLinkTests/JSImportModule.d.ts | 1 + .../BridgeJSLinkTests/JSNameOverride.d.ts | 1 + .../BridgeJSLinkTests/JSNameOverride.js | 1 + .../BridgeJSLinkTests/JSTypedArrayTypes.d.ts | 1 + .../BridgeJSLinkTests/JSValue.d.ts | 1 + .../BridgeJSLinkTests/JSValue.js | 306 +++- .../BridgeJSLinkTests/MixedGlobal.d.ts | 1 + .../BridgeJSLinkTests/MixedModules.d.ts | 1 + .../BridgeJSLinkTests/MixedPrivate.d.ts | 1 + .../BridgeJSLinkTests/Namespaces.Global.d.ts | 1 + .../BridgeJSLinkTests/Namespaces.Global.js | 330 ++++- .../BridgeJSLinkTests/Namespaces.d.ts | 1 + .../BridgeJSLinkTests/Namespaces.js | 330 ++++- .../BridgeJSLinkTests/NestedType.d.ts | 1 + .../BridgeJSLinkTests/NestedType.js | 1 + .../BridgeJSLinkTests/Optionals.d.ts | 1 + .../BridgeJSLinkTests/Optionals.js | 398 ++++- .../PrimitiveParameters.d.ts | 1 + .../BridgeJSLinkTests/PrimitiveReturn.d.ts | 1 + .../BridgeJSLinkTests/PropertyTypes.d.ts | 1 + .../BridgeJSLinkTests/Protocol.d.ts | 1 + .../BridgeJSLinkTests/Protocol.js | 505 ++++++- .../BridgeJSLinkTests/ProtocolInClosure.d.ts | 1 + .../StaticFunctions.Global.d.ts | 1 + .../StaticFunctions.Global.js | 1 + .../BridgeJSLinkTests/StaticFunctions.d.ts | 1 + .../BridgeJSLinkTests/StaticFunctions.js | 1 + .../StaticProperties.Global.d.ts | 1 + .../StaticProperties.Global.js | 1 + .../BridgeJSLinkTests/StaticProperties.d.ts | 1 + .../BridgeJSLinkTests/StaticProperties.js | 1 + .../BridgeJSLinkTests/StringParameter.d.ts | 1 + .../BridgeJSLinkTests/StringReturn.d.ts | 1 + .../StructWithNestedTypes.d.ts | 1 + .../StructWithNestedTypes.js | 1 + .../BridgeJSLinkTests/SwiftClass.d.ts | 1 + .../BridgeJSLinkTests/SwiftClosure.d.ts | 1 + .../BridgeJSLinkTests/SwiftClosure.js | 239 ++- .../SwiftClosureImports.d.ts | 1 + .../BridgeJSLinkTests/SwiftStruct.d.ts | 1 + .../BridgeJSLinkTests/SwiftStruct.js | 457 ++++-- .../BridgeJSLinkTests/SwiftStructImports.d.ts | 1 + .../BridgeJSLinkTests/SwiftStructImports.js | 317 +++- .../SwiftTypedClosureAccess.d.ts | 1 + .../BridgeJSLinkTests/Throws.d.ts | 1 + .../BridgeJSLinkTests/UnsafePointer.d.ts | 1 + .../BridgeJSLinkTests/UnsafePointer.js | 1 + .../VoidParameterVoidReturn.d.ts | 1 + Plugins/PackageToJS/Templates/instantiate.js | 7 +- .../JavaScriptKit/BridgeJSIntrinsics.swift | 99 ++ .../BridgeJS/Generating-from-TypeScript.md | 2 +- .../Importing-JS-Function.md | 14 +- .../Articles/BridgeJS/Supported-Types.md | 4 + .../Generated/BridgeJS.swift | 51 +- .../Generated/BridgeJS.swift | 331 ++++- .../Generated/JavaScript/BridgeJS.json | 4 + 154 files changed, 8159 insertions(+), 2070 deletions(-) diff --git a/Benchmarks/Sources/Generated/BridgeJS.swift b/Benchmarks/Sources/Generated/BridgeJS.swift index 384ca35a2..81888845b 100644 --- a/Benchmarks/Sources/Generated/BridgeJS.swift +++ b/Benchmarks/Sources/Generated/BridgeJS.swift @@ -2179,6 +2179,34 @@ fileprivate func _bjs_ArrayRoundtrip_wrap_extern(_ pointer: UnsafeMutableRawPoin return _bjs_ArrayRoundtrip_wrap_extern(pointer) } +extension SimpleStruct: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = SimpleStruct.bridgeJSMakeTypeHandle() +} + +extension Address: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Address.bridgeJSMakeTypeHandle() +} + +extension Person: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Person.bridgeJSMakeTypeHandle() +} + +extension ComplexStruct: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = ComplexStruct.bridgeJSMakeTypeHandle() +} + +extension Point: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Point.bridgeJSMakeTypeHandle() +} + +extension APIResult: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = APIResult.bridgeJSMakeTypeHandle() +} + +extension ComplexResult: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = ComplexResult.bridgeJSMakeTypeHandle() +} + #if arch(wasm32) @_extern(wasm, module: "Benchmarks", name: "bjs_benchmarkHelperNoop") fileprivate func bjs_benchmarkHelperNoop_extern() -> Void @@ -2238,4 +2266,40 @@ func _$benchmarkRunner(_ name: String, _ body: JSObject) throws(JSException) -> if let error = _swift_js_take_exception() { throw error } -} \ No newline at end of file +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_Benchmarks_register_type_handles") +fileprivate func _bjs_Benchmarks_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_Benchmarks_register_type_handles") +public func _bjs_Benchmarks_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + SimpleStruct.bridgeJSTypeID, + Address.bridgeJSTypeID, + Person.bridgeJSTypeID, + ComplexStruct.bridgeJSTypeID, + Point.bridgeJSTypeID, + APIResult.bridgeJSTypeID, + ComplexResult.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_Benchmarks_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Examples/Embedded/Package.swift b/Examples/Embedded/Package.swift index 42702394a..1f88a8947 100644 --- a/Examples/Embedded/Package.swift +++ b/Examples/Embedded/Package.swift @@ -16,6 +16,9 @@ let package = Package( swiftSettings: [ .enableExperimentalFeature("Extern") ], + plugins: [ + .plugin(name: "BridgeJS", package: "JavaScriptKit") + ] ) ], swiftLanguageModes: [.v5] diff --git a/Examples/Embedded/Sources/EmbeddedApp/main.swift b/Examples/Embedded/Sources/EmbeddedApp/main.swift index 5e7f01a3c..c3e0dd3cd 100644 --- a/Examples/Embedded/Sources/EmbeddedApp/main.swift +++ b/Examples/Embedded/Sources/EmbeddedApp/main.swift @@ -1,5 +1,12 @@ import JavaScriptKit +@JS struct CounterLabel { + var count: Int + var text: String +} + +@JSFunction func echoValue(_ value: T) throws(JSException) -> T + let alert = JSObject.global.alert.object! let document = JSObject.global.document @@ -46,6 +53,17 @@ _ = encoderContainer.appendChild(textInputElement) _ = encoderContainer.appendChild(encodeResultElement) _ = document.body.appendChild(encoderContainer) +let genericResultElement = document.createElement("pre") +do { + let number = try echoValue(42) + let text = try echoValue("hello") + let label = try echoValue(CounterLabel(count: number, text: text)) + genericResultElement.innerText = .string("Generic import round-trip: \(label.text) \(label.count)") +} catch { + genericResultElement.innerText = "Generic import round-trip failed" +} +_ = document.body.appendChild(genericResultElement) + func print(_ message: String) { _ = JSObject.global.console.log(message) } diff --git a/Examples/Embedded/index.html b/Examples/Embedded/index.html index 93868214d..d280d7067 100644 --- a/Examples/Embedded/index.html +++ b/Examples/Embedded/index.html @@ -8,7 +8,13 @@ diff --git a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift index 10976f793..dff715c64 100644 --- a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift +++ b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift @@ -231,6 +231,18 @@ fileprivate func _bjs_PlayBridgeJS_wrap_extern(_ pointer: UnsafeMutableRawPointe return _bjs_PlayBridgeJS_wrap_extern(pointer) } +extension PlayBridgeJSOutput: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = PlayBridgeJSOutput.bridgeJSMakeTypeHandle() +} + +extension PlayBridgeJSDiagnostic: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = PlayBridgeJSDiagnostic.bridgeJSMakeTypeHandle() +} + +extension PlayBridgeJSResult: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = PlayBridgeJSResult.bridgeJSMakeTypeHandle() +} + #if arch(wasm32) @_extern(wasm, module: "PlayBridgeJS", name: "bjs_createTS2Swift") fileprivate func bjs_createTS2Swift_extern() -> Int32 @@ -274,4 +286,36 @@ func _$TS2Swift_convert(_ self: JSObject, _ ts: String) throws(JSException) -> S throw error } return String.bridgeJSLiftReturn(ret) -} \ No newline at end of file +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_PlayBridgeJS_register_type_handles") +fileprivate func _bjs_PlayBridgeJS_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_PlayBridgeJS_register_type_handles") +public func _bjs_PlayBridgeJS_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + PlayBridgeJSOutput.bridgeJSTypeID, + PlayBridgeJSDiagnostic.bridgeJSTypeID, + PlayBridgeJSResult.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_PlayBridgeJS_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/README.md b/Plugins/BridgeJS/README.md index 9e1e0aa08..0905695c5 100644 --- a/Plugins/BridgeJS/README.md +++ b/Plugins/BridgeJS/README.md @@ -98,7 +98,7 @@ graph LR | `Dictionary` | `Record` | - | [#495](https://github.com/swiftwasm/JavaScriptKit/issues/495) | | `Set` | `Set` | - | [#397](https://github.com/swiftwasm/JavaScriptKit/issues/397) | | `Foundation.URL` | `string` | - | [#496](https://github.com/swiftwasm/JavaScriptKit/issues/496) | -| Generics | - | - | [#398](https://github.com/swiftwasm/JavaScriptKit/issues/398) | +| Generic function or method (`T`, `[T]`, `T?`, `[String: T]`) | `(value: T): T` | Depends on `T` | ✅ imports only ([#398](https://github.com/swiftwasm/JavaScriptKit/issues/398) for exports) | ### Import-specific (TypeScript -> Swift) diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift index 2cc551857..e4d0f5b02 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift @@ -91,6 +91,15 @@ public class ExportSwift { } } + withSpan("Render Generic Bridgeable Conformances") { [self] in + // Emitted unconditionally: a module cannot know whether a dependent + // module passes its types to a generic imported function. + let genericConformanceCodegen = GenericConformanceCodegen() + for entry in skeleton.genericBridgeableTypeEntries { + decls.append(contentsOf: genericConformanceCodegen.renderConformance(typeName: entry.swiftName)) + } + } + try withSpan("Render Async Promise Helpers") { [self] in let asyncResolveTypes = skeleton.asyncPromiseResolveReturnTypes if !asyncResolveTypes.isEmpty { @@ -875,6 +884,63 @@ public class ExportSwift { } } +// MARK: - GenericConformanceCodegen + +/// Renders `BridgedSwiftGenericBridgeable` conformances for `@JS` types so they +/// can be used as the generic argument of a generic imported `@JSFunction`. +struct GenericConformanceCodegen { + func renderConformance(typeName: String) -> [DeclSyntax] { + let printer = CodeFragmentPrinter() + printer.write("extension \(typeName): BridgedSwiftGenericBridgeable {") + printer.indent { + printer.write( + "@_spi(BridgeJS) public static let bridgeJSTypeHandle = \(typeName).bridgeJSMakeTypeHandle()" + ) + } + printer.write("}") + return ["\(raw: printer.lines.joined(separator: "\n"))"] + } +} + +// MARK: - GenericTypeRegistrationCodegen + +/// Renders the `bjs__register_type_handles` wasm export: it lowers each +/// registered type's `bridgeJSTypeID` into a buffer, in the canonical order of +/// `BridgeJSSkeleton.typeRegistrationEntries`, and passes it to the JS import +/// hook of the same name, which pairs the IDs with its codec array by index. +public struct GenericTypeRegistrationCodegen { + public init() {} + + public func render(for skeleton: BridgeJSSkeleton) -> String? { + guard let entries = skeleton.typeRegistrationEntries else { return nil } + let abiName = ABINameGenerator.typeRegistrationFunctionName(moduleName: skeleton.moduleName) + let printer = CodeFragmentPrinter() + printer.write("#if arch(wasm32)") + printer.write("@_extern(wasm, module: \"bjs\", name: \"\(abiName)\")") + printer.write("fileprivate func _\(abiName)_extern(_ base: UnsafePointer?, _ count: Int32)") + printer.nextLine() + printer.write("@_expose(wasm, \"\(abiName)\")") + printer.write("public func _\(abiName)() {") + printer.indent { + printer.write("let typeIds: [Int32] = [") + printer.indent { + for entry in entries { + printer.write("\(entry.swiftName).bridgeJSTypeID,") + } + } + printer.write("]") + printer.write("typeIds.withUnsafeBufferPointer { buffer in") + printer.indent { + printer.write("_\(abiName)_extern(buffer.baseAddress, Int32(buffer.count))") + } + printer.write("}") + } + printer.write("}") + printer.write("#endif") + return printer.lines.joined(separator: "\n") + } +} + // MARK: - StackCodegen /// Helper for stack-based lifting and lowering operations. @@ -896,6 +962,10 @@ struct StackCodegen { return "JSObject.bridgeJSStackPop()" case .void, .namespaceEnum: return "()" + case .generic: + fatalError( + "Generic parameters are only supported on imported declarations, not exported concrete-type codegen" + ) } } @@ -908,7 +978,7 @@ struct StackCodegen { return "\(raw: typeName)<\(raw: wrappedType.swiftType)>.bridgeJSStackPop()" case .jsObject(let className?): return "\(raw: typeName).bridgeJSStackPop().map { \(raw: className)(unsafelyWrapping: $0) }" - case .nullable, .void, .namespaceEnum, .closure, .unsafePointer, .swiftProtocol: + case .nullable, .void, .namespaceEnum, .closure, .unsafePointer, .swiftProtocol, .generic: fatalError("Invalid nullable wrapped type: \(wrappedType)") } } @@ -941,6 +1011,10 @@ struct StackCodegen { return lowerArrayStatements(elementType: elementType, accessor: accessor, varPrefix: varPrefix) case .dictionary(let valueType): return lowerDictionaryStatements(valueType: valueType, accessor: accessor, varPrefix: varPrefix) + case .generic: + fatalError( + "Generic parameters are only supported on imported declarations, not exported concrete-type codegen" + ) } } @@ -1596,12 +1670,34 @@ extension BridgeType { case .associatedValueEnum: return ["_BridgedSwiftAssociatedValueEnum"] case .rawValueEnum, .void, .unsafePointer, .namespaceEnum, - .swiftProtocol, .closure, .nullable, .array, .dictionary, .alias: + .swiftProtocol, .closure, .nullable, .array, .dictionary, .alias, .generic: // Not supported yet. return nil } } + /// Stack expressions for bare `T` and `T?`, the only generic shapes that + /// cannot reuse the concrete emission: `bridgeJSLowerParameter()` names + /// per-type members that the generic constraint erases to the stack, so + /// `bridgeJSStackPush()`/`bridgeJSStackPop()` is the shared spelling. + /// `[T]` and `[String: T]` go through the ordinary paths via the `Array` + /// and `Dictionary` stack conformances. + var genericStackPopExpression: String? { + switch self { + case .generic(let name): return "\(name).bridgeJSStackPop()" + case .nullable(.generic(let name), _): return "Optional<\(name)>.bridgeJSStackPop()" + default: return nil + } + } + + func genericStackPushStatement(value: String) -> String? { + switch self { + case .generic, .nullable(.generic, _): + return "\(value).bridgeJSStackPush()" + default: return nil + } + } + var swiftType: String { switch self { case .bool: return "Bool" @@ -1631,6 +1727,7 @@ extension BridgeType { let closureType = "(\(paramTypes))\(effectsStr) -> \(signature.returnType.swiftType)" return useJSTypedClosure ? "JSTypedClosure<\(closureType)>" : closureType case .alias(let name, _): return name + case .generic(let name): return name } } @@ -1717,6 +1814,10 @@ extension BridgeType { return LiftingIntrinsicInfo(parameters: []) case .alias(_, let underlying): return try underlying.liftParameterInfo() + case .generic: + throw BridgeJSCoreError( + "Generic parameters are only supported on imported declarations, not exported concrete-type codegen" + ) } } @@ -1770,6 +1871,10 @@ extension BridgeType { return .array case .alias(_, let underlying): return try underlying.loweringReturnInfo() + case .generic: + throw BridgeJSCoreError( + "Generic parameters are only supported on imported declarations, not exported concrete-type codegen" + ) } } } diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift index 286352915..cb5a88e93 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift @@ -143,6 +143,11 @@ public struct ImportTS { } func lowerParameter(param: Parameter) throws { + if let genericPush = param.type.genericStackPushStatement(value: param.name) { + stackLoweringStmts.insert(genericPush, at: 0) + return + } + let loweringInfo = try param.type.loweringParameterInfo(context: context) switch param.type { @@ -237,6 +242,18 @@ public struct ImportTS { abiParameterForwardings.insert(contentsOf: ["resolveRef", "rejectRef"], at: 0) } + private func appendTypeIDParameter(index: Int, genericParameterName: String) { + let abiParamName = ABINameGenerator.genericTypeIdParameterName(index: index) + abiParameterSignatures.append((abiParamName, .i32)) + abiParameterForwardings.append("\(genericParameterName).bridgeJSTypeID") + } + + func appendTypeIDParameters(_ genericParameterNames: [String]) { + for (index, name) in genericParameterNames.enumerated() { + appendTypeIDParameter(index: index, genericParameterName: name) + } + } + func call() throws { for stmt in stackLoweringStmts { body.write(stmt.description) @@ -293,14 +310,18 @@ public struct ImportTS { body.write("return \(returnType.swiftType).bridgeJSLiftReturnFromSideChannel()") } else { let liftExpr: String - switch returnType { - case .closure(let signature, _): - liftExpr = "_BJS_Closure_\(signature.mangleName).bridgeJSLift(ret)" - default: - if liftingInfo.valueToLift != nil { - liftExpr = "\(returnType.swiftType).bridgeJSLiftReturn(ret)" - } else { - liftExpr = "\(returnType.swiftType).bridgeJSLiftReturn()" + if let genericPop = returnType.genericStackPopExpression { + liftExpr = genericPop + } else { + switch returnType { + case .closure(let signature, _): + liftExpr = "_BJS_Closure_\(signature.mangleName).bridgeJSLift(ret)" + default: + if liftingInfo.valueToLift != nil { + liftExpr = "\(returnType.swiftType).bridgeJSLiftReturn(ret)" + } else { + liftExpr = "\(returnType.swiftType).bridgeJSLiftReturn()" + } } } body.write("return \(liftExpr)") @@ -359,7 +380,8 @@ public struct ImportTS { name: String, parameters: [Parameter], returnType: BridgeType, - effects: Effects + effects: Effects, + genericParameters: [String] = [] ) -> DeclSyntax { let printer = CodeFragmentPrinter() let signature = SwiftSignatureBuilder.buildFunctionSignature( @@ -368,7 +390,12 @@ public struct ImportTS { effects: effects, useWildcardLabels: true ) - printer.write("func \(name.backtickIfNeeded())\(signature) {") + let genericClause = + genericParameters.isEmpty + ? "" + : "<" + genericParameters.map { "\($0): BridgedSwiftGenericBridgeable" }.joined(separator: ", ") + + ">" + printer.write("func \(name.backtickIfNeeded())\(genericClause)\(signature) {") printer.indent { printer.write(lines: body.lines) } @@ -428,6 +455,7 @@ public struct ImportTS { for param in function.parameters { try builder.lowerParameter(param: param) } + builder.appendTypeIDParameters(function.genericParameterNames) try builder.call() try builder.liftReturnValue() topLevelDecls.append(builder.renderImportDecl()) @@ -436,7 +464,8 @@ public struct ImportTS { name: Self.thunkName(function: function), parameters: function.parameters, returnType: function.returnType, - effects: function.effects + effects: function.effects, + genericParameters: function.genericParameterNames ) .with(\.leadingTrivia, Self.renderDocumentation(documentation: function.documentation)) ] @@ -457,6 +486,7 @@ public struct ImportTS { for param in method.parameters { try builder.lowerParameter(param: param) } + builder.appendTypeIDParameters(method.genericParameterNames) try builder.call() try builder.liftReturnValue() topLevelDecls.append(builder.renderImportDecl()) @@ -465,7 +495,8 @@ public struct ImportTS { name: Self.thunkName(type: type, method: method), parameters: [selfParameter] + method.parameters, returnType: method.returnType, - effects: method.effects + effects: method.effects, + genericParameters: method.genericParameterNames ) ] } @@ -481,6 +512,7 @@ public struct ImportTS { for param in method.parameters { try builder.lowerParameter(param: param) } + builder.appendTypeIDParameters(method.genericParameterNames) try builder.call() try builder.liftReturnValue() topLevelDecls.append(builder.renderImportDecl()) @@ -489,7 +521,8 @@ public struct ImportTS { name: Self.thunkName(type: type, method: method), parameters: method.parameters, returnType: method.returnType, - effects: method.effects + effects: method.effects, + genericParameters: method.genericParameterNames ) ] } @@ -505,6 +538,7 @@ public struct ImportTS { for param in constructor.parameters { try builder.lowerParameter(param: param) } + builder.appendTypeIDParameters(constructor.genericParameterNames) try builder.call() try builder.liftReturnValue() topLevelDecls.append(builder.renderImportDecl()) @@ -513,7 +547,8 @@ public struct ImportTS { name: Self.thunkName(type: type), parameters: constructor.parameters, returnType: .jsObject(nil), - effects: effects + effects: effects, + genericParameters: constructor.genericParameterNames ) ] } @@ -932,9 +967,6 @@ extension BridgeType { return LoweringParameterInfo(loweredParameters: [("value", wasmType)]) case .associatedValueEnum: return LoweringParameterInfo(loweredParameters: [("caseId", .i32)]) - case .swiftStruct: - // `@JS struct` parameters always use the stack ABI (same as arrays/dictionaries). - return LoweringParameterInfo(loweredParameters: []) case .namespaceEnum: throw BridgeJSCoreError("Namespace enums cannot be used as parameters") case .nullable(let wrappedType, _): @@ -942,7 +974,10 @@ extension BridgeType { var params = [("isSome", WasmCoreType.i32)] params.append(contentsOf: wrappedInfo.loweredParameters) return LoweringParameterInfo(loweredParameters: params, useBorrowing: wrappedInfo.useBorrowing) - case .array, .dictionary: + case .swiftStruct: + // `@JS struct` parameters always use the stack ABI (same as arrays/dictionaries). + return LoweringParameterInfo(loweredParameters: []) + case .array, .dictionary, .generic: return LoweringParameterInfo(loweredParameters: []) case .alias: preconditionFailure("`.alias` must be resolved by `.unaliased` before reaching loweringParameterInfo") @@ -995,9 +1030,6 @@ extension BridgeType { return LiftingReturnInfo(valueToLift: wasmType) case .associatedValueEnum: return LiftingReturnInfo(valueToLift: .i32) - case .swiftStruct: - // `@JS struct` returns always use the stack ABI (same as arrays/dictionaries). - return LiftingReturnInfo(valueToLift: nil) case .namespaceEnum: throw BridgeJSCoreError("Namespace enums cannot be used as return values") case .nullable(let wrappedType, _): @@ -1008,7 +1040,10 @@ extension BridgeType { } let wrappedInfo = try wrappedType.liftingReturnInfo(context: context) return LiftingReturnInfo(valueToLift: wrappedInfo.valueToLift) - case .array, .dictionary: + case .swiftStruct: + // `@JS struct` returns always use the stack ABI (same as arrays/dictionaries). + return LiftingReturnInfo(valueToLift: nil) + case .array, .dictionary, .generic: return LiftingReturnInfo(valueToLift: nil) case .alias: preconditionFailure("`.alias` must be resolved by `.unaliased` before reaching liftingReturnInfo") diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index bfd639ee6..f37bfb822 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -7,6 +7,79 @@ import BridgeJSUtilities import BridgeJSSkeleton #endif +/// Outcome of attempting to resolve a type as a reference to a generic parameter. +enum GenericParameterResolution { + case resolved(BridgeType) + /// A non-nil message is a hard diagnostic; `nil` means the type isn't generic + /// and the caller should fall back to normal type resolution. + case rejected(String?) +} + +func resolveGenericTypeReference( + for type: TypeSyntax, + genericParameterNames: [String] +) -> GenericParameterResolution { + if let identifier = type.as(IdentifierTypeSyntax.self), + identifier.genericArgumentClause == nil, + genericParameterNames.contains(identifier.name.text) + { + return .resolved(.generic(identifier.name.text)) + } + if let wrapped = wrappedGenericBridgeType(for: type, genericParameterNames: genericParameterNames) { + return .resolved(wrapped) + } + if !genericParameterNames.isEmpty, + let wrapped = wrappedGenericParameter(in: type, genericParameterNames: genericParameterNames) + { + return .rejected( + "Generic parameter '\(wrapped)' may only be used as a bare type; wrapping it beyond 'T?', '[T]' and '[String: T]' is not supported." + ) + } + return .rejected(nil) +} + +private func wrappedGenericParameter( + in type: TypeSyntax, + genericParameterNames: [String] +) -> String? { + for token in type.tokens(viewMode: .sourceAccurate) { + if case .identifier(let text) = token.tokenKind, genericParameterNames.contains(text) { + return text + } + } + return nil +} + +private func wrappedGenericBridgeType( + for type: TypeSyntax, + genericParameterNames: [String] +) -> BridgeType? { + func bareGenericName(_ inner: TypeSyntax) -> String? { + guard let identifier = inner.as(IdentifierTypeSyntax.self), + identifier.genericArgumentClause == nil, + genericParameterNames.contains(identifier.name.text) + else { + return nil + } + return identifier.name.text + } + if let arrayType = type.as(ArrayTypeSyntax.self), let name = bareGenericName(arrayType.element) { + return .array(.generic(name)) + } + if let optionalType = type.as(OptionalTypeSyntax.self), let name = bareGenericName(optionalType.wrappedType) { + return .nullable(.generic(name), .null) + } + if let dictType = type.as(DictionaryTypeSyntax.self), + let keyIdentifier = dictType.key.as(IdentifierTypeSyntax.self), + keyIdentifier.genericArgumentClause == nil, + keyIdentifier.name.text == "String", + let name = bareGenericName(dictType.value) + { + return .dictionary(.generic(name)) + } + return nil +} + /// Builds BridgeJS skeletons from Swift source files using SwiftSyntax walk for API collection. /// /// This is a shared entry point for producing: @@ -748,6 +821,11 @@ public final class SwiftToSkeleton { return name.unicodeScalars.dropFirst().allSatisfy { isIdentifierPart($0, isStart: false) } } + fileprivate static func isBridgeableGenericConstraint(_ constraint: String?) -> Bool { + constraint == "BridgedSwiftGenericBridgeable" + || constraint == "JavaScriptKit.BridgedSwiftGenericBridgeable" + } + } private enum ExportSwiftConstants { @@ -1219,10 +1297,6 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { diagnoseNestedOptional(node: param.type, type: param.type.trimmedDescription) continue } - if case .nullable(let wrappedType, _) = type, wrappedType.isOptional { - diagnoseNestedOptional(node: param.type, type: param.type.trimmedDescription) - continue - } let name = param.secondName?.text ?? param.firstName.text let label = param.firstName.text @@ -1307,6 +1381,15 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { return nil } + if let genericClause = node.genericParameterClause, let firstGenericParam = genericClause.parameters.first { + diagnose( + node: firstGenericParam, + message: + "Generic parameters on exported @JS functions are not supported yet. Generic functions are currently only supported on imported @JSFunction declarations." + ) + return nil + } + let name = node.name.text let jsName = extractValidatedJSName(from: jsAttribute) @@ -1784,6 +1867,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { message: "Class visibility must be at least internal" ) let classIdentityMode = extractIdentityMode(from: jsAttribute) + let isFinal = node.modifiers.contains { $0.name.tokenKind == .keyword(.final) } ? true : nil let exportedClass = ExportedClass( name: name, swiftCallName: swiftCallName, @@ -1793,7 +1877,8 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { properties: [], namespace: effectiveNamespace, identityMode: classIdentityMode, - documentation: extractDocumentation(from: node) + documentation: extractDocumentation(from: node), + isFinal: isFinal ) let uniqueKey = makeKey(name: name, namespace: effectiveNamespace) @@ -3204,24 +3289,101 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { // MARK: - Parsing Methods + /// Validates and collects the generic parameter names of an imported + /// `@JSFunction` declaration (function, method or initializer). + /// + /// Returns `nil` when a diagnostic was emitted; an empty array when the + /// declaration is not generic. + private func parseGenericParameterNames( + genericParameterClause: GenericParameterClauseSyntax?, + genericWhereClause: GenericWhereClauseSyntax?, + node: Syntax + ) -> [String]? { + var genericParameterNames: [String] = [] + if let genericParameterClause { + for genericParam in genericParameterClause.parameters { + let paramName = genericParam.name.text + let constraintText = genericParam.inheritedType?.trimmedDescription + guard SwiftToSkeleton.isBridgeableGenericConstraint(constraintText) else { + errors.append( + DiagnosticError( + node: Syntax(genericParam), + message: + "Generic parameter '\(paramName)' must be constrained to 'BridgedSwiftGenericBridgeable' to be used with @JSFunction." + ) + ) + return nil + } + genericParameterNames.append(paramName) + } + } + if genericWhereClause != nil { + errors.append( + DiagnosticError( + node: node, + message: "'where' clauses are not supported on @JSFunction declarations." + ) + ) + return nil + } + return genericParameterNames + } + private func parseConstructor( _ initializer: InitializerDeclSyntax, typeName: String ) -> ImportedConstructorSkeleton? { guard - validateEffects(initializer.signature.effectSpecifiers, node: initializer, attributeName: "JSFunction") - != nil + let effects = validateEffects( + initializer.signature.effectSpecifiers, + node: initializer, + attributeName: "JSFunction" + ) + else { + return nil + } + guard + let genericParameterNames = parseGenericParameterNames( + genericParameterClause: initializer.genericParameterClause, + genericWhereClause: initializer.genericWhereClause, + node: Syntax(initializer) + ) else { return nil } + if !genericParameterNames.isEmpty && effects.isAsync { + errors.append( + DiagnosticError( + node: Syntax(initializer), + message: "Generic @JSFunction declarations cannot be 'async' yet." + ) + ) + return nil + } + let parameters = parseParameters( + from: initializer.signature.parameterClause, + genericParameterNames: genericParameterNames + ) + for genericName in genericParameterNames + where !parameters.contains(where: { $0.type.referencedGenericName == genericName }) { + errors.append( + DiagnosticError( + node: Syntax(initializer), + message: + "The generic parameter '\(genericName)' must be used in a parameter of a generic @JSFunction initializer." + ) + ) + return nil + } // Initializers without an explicit modifier inherit access from the // enclosing `@JSClass` (the user's example pattern: `public init(...)` // inside `public struct JSDocument`). let parentLevel = currentType?.accessLevel ?? .internal let accessLevel = Self.bridgeAccessLevel(from: initializer.modifiers, default: parentLevel) return ImportedConstructorSkeleton( - parameters: parseParameters(from: initializer.signature.parameterClause), - accessLevel: accessLevel + parameters: parameters, + accessLevel: accessLevel, + genericParameters: genericParameterNames.isEmpty ? nil : genericParameterNames ) } @@ -3239,6 +3401,16 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { return nil } + guard + let genericParameterNames = parseGenericParameterNames( + genericParameterClause: node.genericParameterClause, + genericWhereClause: node.genericWhereClause, + node: Syntax(node) + ) + else { + return nil + } + let baseName = SwiftToSkeleton.normalizeIdentifier(node.name.text) let extractedJSName = extractJSName(from: jsFunction) let from = extractJSImportFrom(from: jsFunction) @@ -3246,16 +3418,51 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { let jsName = extractedJSName?.memberName let name = baseName - let parameters = parseParameters(from: node.signature.parameterClause) + let parameters = parseParameters( + from: node.signature.parameterClause, + genericParameterNames: genericParameterNames + ) let returnType: BridgeType if let returnTypeSyntax = node.signature.returnClause?.type { - guard let resolved = withLookupErrors({ parent.lookupType(for: returnTypeSyntax, errors: &$0) }) else { + guard + let resolved = lookupTypeWithGenerics( + for: returnTypeSyntax, + genericParameterNames: genericParameterNames + ) + else { return nil } returnType = resolved } else { returnType = .void } + + if !genericParameterNames.isEmpty { + if effects.isAsync { + errors.append( + DiagnosticError( + node: node, + message: "Generic @JSFunction declarations cannot be 'async' yet." + ) + ) + return nil + } + for genericName in genericParameterNames { + let usedInParameter = parameters.contains { $0.type.referencedGenericName == genericName } + let usedInReturn = returnType.referencedGenericName == genericName + if !usedInParameter && !usedInReturn { + errors.append( + DiagnosticError( + node: node, + message: + "The generic parameter '\(genericName)' must be used in a parameter or return type of a generic @JSFunction declaration." + ) + ) + return nil + } + } + } + let accessLevel = Self.bridgeAccessLevel(from: node.modifiers) return ImportedFunctionSkeleton( name: name, @@ -3265,7 +3472,8 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { returnType: returnType, effects: effects, documentation: nil, - accessLevel: accessLevel + accessLevel: accessLevel, + genericParameters: genericParameterNames.isEmpty ? nil : genericParameterNames ) } @@ -3342,7 +3550,26 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { // MARK: - Type and Parameter Parsing - private func parseParameters(from clause: FunctionParameterClauseSyntax) -> [Parameter] { + private func lookupTypeWithGenerics( + for type: TypeSyntax, + genericParameterNames: [String] + ) -> BridgeType? { + switch resolveGenericTypeReference(for: type, genericParameterNames: genericParameterNames) { + case .resolved(let bridgeType): + return bridgeType + case .rejected(let message): + if let message { + errors.append(DiagnosticError(node: Syntax(type), message: message)) + return nil + } + return withLookupErrors { parent.lookupType(for: type, errors: &$0) } + } + } + + private func parseParameters( + from clause: FunctionParameterClauseSyntax, + genericParameterNames: [String] = [] + ) -> [Parameter] { clause.parameters.compactMap { param in let type = param.type if type.is(MissingTypeSyntax.self) { @@ -3354,7 +3581,8 @@ private final class ImportSwiftMacrosAPICollector: SyntaxAnyVisitor { ) return nil } - guard let bridgeType = withLookupErrors({ parent.lookupType(for: type, errors: &$0) }) else { + guard let bridgeType = lookupTypeWithGenerics(for: type, genericParameterNames: genericParameterNames) + else { return nil } let nameToken = param.secondName ?? param.firstName diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index 6043f3cd1..7a407889f 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -31,6 +31,10 @@ public struct BridgeJSLink { skeletons.compactMap(\.exported).compactMap(\.identityMode).first ?? "none" } + var hasGenerics: Bool { + skeletons.contains { $0.imported?.hasGenericDeclarations ?? false } + } + /// Whether a class should use identity caching based on its annotation and the config default. private func shouldUseIdentityCache(for klass: ExportedClass) -> Bool { // Per-class annotation takes priority @@ -311,7 +315,7 @@ public struct BridgeJSLink { } private func generateVariableDeclarations() -> [String] { - return [ + var declarations: [String] = [ "let \(JSGlueVariableScope.reservedInstance);", "let \(JSGlueVariableScope.reservedMemory);", "let \(JSGlueVariableScope.reservedSetException);", @@ -335,10 +339,29 @@ public struct BridgeJSLink { "let \(JSGlueVariableScope.reservedTaStack) = [];", "const \(JSGlueVariableScope.reservedEnumHelpers) = {};", "const \(JSGlueVariableScope.reservedStructHelpers) = {};", + ] + if hasGenerics { + declarations.append("const \(JSGlueVariableScope.reservedCodecByTypeId) = new Map();") + declarations.append("let __bjs_typeHandlesRegistered = false;") + declarations.append("function __bjs_registerTypeHandles() {") + declarations.append(" if (__bjs_typeHandlesRegistered) {") + declarations.append(" return;") + declarations.append(" }") + declarations.append(" __bjs_typeHandlesRegistered = true;") + for skeleton in skeletons { + guard skeleton.typeRegistrationEntries != nil else { continue } + let name = ABINameGenerator.typeRegistrationFunctionName(moduleName: skeleton.moduleName) + declarations.append(" \(JSGlueVariableScope.reservedInstance).exports[\"\(name)\"]();") + } + declarations.append("}") + declarations.append(contentsOf: GenericJSCodegen.runtimeHelperDeclarations()) + } + declarations.append(contentsOf: [ "", "let _exports = null;", "let bjs = null;", - ] + ]) + return declarations } /// JS const (in the import glue scope) holding the `Symbol` under which a promise's @@ -375,6 +398,79 @@ public struct BridgeJSLink { printer.write(lines: lines) } + /// A print context detached from any thunk, used for codec literal emission. + private func makeCodecPrintContext(printer: CodeFragmentPrinter) -> IntrinsicJSFragment.PrintCodeContext { + IntrinsicJSFragment.PrintCodeContext( + scope: JSGlueVariableScope(intrinsicRegistry: intrinsicRegistry), + printer: printer, + hasDirectAccessToSwiftClass: false, + classNamespaces: intrinsicRegistry.classNamespaces + ) + } + + /// Emits a `{ lower, lift }` codec literal for one bridgeable type. + /// `prefix` is prepended to the opening brace (e.g. an assignment) and + /// `suffix` is appended to the closing brace (e.g. `","` in an array). + private func appendGenericCodecLiteral( + type: BridgeType, + into printer: CodeFragmentPrinter, + prefix: String = "", + suffix: String = "," + ) throws { + try ContainerCodecJS.writeCodecLiteral( + type: type, + into: printer, + context: makeCodecPrintContext(printer: printer), + prefix: prefix, + suffix: suffix + ) + } + + /// Installs the per-module `bjs__register_type_handles` import + /// hooks. A module with a registration function always carries the wasm + /// import, so a hook is always installed; without generics anywhere in the + /// build it is a no-op and the registration export is never called. + private func generateTypeRegistrationHooks(into printer: CodeFragmentPrinter) throws { + for skeleton in skeletons { + guard skeleton.typeRegistrationEntries != nil else { continue } + let hookName = ABINameGenerator.typeRegistrationFunctionName(moduleName: skeleton.moduleName) + guard hasGenerics else { + printer.write("bjs[\"\(hookName)\"] = function() {};") + continue + } + // The hooks resolve type IDs against the shared primitive codec table. + try ContainerCodecJS.registerPrimitiveCodecs(context: makeCodecPrintContext(printer: printer)) + let moduleEntries = skeleton.exported?.genericBridgeableTypeEntries ?? [] + printer.write("bjs[\"\(hookName)\"] = function(base, count) {") + try printer.indent { + // Same canonical order as the Swift registration function: + // primitives first, then the module's own types. + printer.write("const codecs = [") + printer.indent { + for primitive in BridgeType.genericBridgeablePrimitives { + printer.write("\(JSGlueVariableScope.reservedPrimitiveCodecs).\(primitive.token),") + } + } + printer.write("].concat([") + try printer.indent { + for entry in moduleEntries { + try appendGenericCodecLiteral(type: entry.bridgeType, into: printer) + } + } + printer.write("]);") + printer.write( + "const typeIds = new Int32Array(\(JSGlueVariableScope.reservedMemory).buffer, base >>> 0, count >>> 0);" + ) + printer.write("for (let i = 0; i < count; i++) {") + printer.indent { + printer.write("\(JSGlueVariableScope.reservedCodecByTypeId).set(typeIds[i], codecs[i]);") + } + printer.write("}") + } + printer.write("}") + } + } + private func generateAddImports(needsImportsObject: Bool) throws -> CodeFragmentPrinter { let printer = CodeFragmentPrinter() let allStructs = skeletons.compactMap { $0.exported?.structs }.flatMap { $0 } @@ -544,6 +640,7 @@ public struct BridgeJSLink { printer.write("}") } } + try generateTypeRegistrationHooks(into: printer) // Always provided: the runtime's `_bjs_makePromise` imports it unconditionally. // The settlers are stored under a Symbol to avoid clashing with promise fields. @@ -1025,7 +1122,7 @@ public struct BridgeJSLink { self.renderExportedStructExportEntry(structDef) }, renderFunctionEntry: { function in - self.renderJSDoc(documentation: function.documentation, parameters: function.parameters) + return self.renderJSDoc(documentation: function.documentation, parameters: function.parameters) + [ "\(function.resolvedJSName)\(self.renderTSSignature(parameters: function.parameters, returnType: function.returnType, effects: function.effects));" ] @@ -1373,8 +1470,9 @@ public struct BridgeJSLink { // Add methods for method in type.methods { let methodName = method.resolvedJSName + let genericClause = renderGenericClause(method.genericParameterNames) let methodSignature = - "\(renderTSPropertyName(methodName))\(renderTSSignature(parameters: method.parameters, returnType: method.returnType, effects: method.effects));" + "\(renderTSPropertyName(methodName))\(genericClause)\(renderTSSignature(parameters: method.parameters, returnType: method.returnType, effects: method.effects));" printer.write(methodSignature) } @@ -1589,6 +1687,10 @@ public struct BridgeJSLink { return "(\(parameterSignatures.joined(separator: ", "))): \(returnTypeWithEffect)" } + private func renderGenericClause(_ genericParameterNames: [String]) -> String { + genericParameterNames.isEmpty ? "" : "<\(genericParameterNames.joined(separator: ", "))>" + } + private func renderTSPropertyName(_ name: String) -> String { // TypeScript allows quoted property names for keys that aren't valid identifiers. if name.range(of: #"^[$A-Z_][0-9A-Z_$]*$"#, options: [.regularExpression, .caseInsensitive]) != nil { @@ -2385,6 +2487,8 @@ extension BridgeJSLink { var parameterNames: [String] = [] var parameterForwardings: [String] = [] var returnExpr: String? + var genericCodecVariables: [String: String] = [:] + var genericTypeIdParameters: [String: String] = [:] let printContext: IntrinsicJSFragment.PrintCodeContext init( @@ -2410,7 +2514,36 @@ extension BridgeJSLink { parameterNames.append("self") } + func declareGenericCodecs(genericParameters: [String]) { + if !genericParameters.isEmpty { + // Generic call sites instantiate the shared container codec + // combinators with the codecs resolved from type IDs. + ContainerCodecJS.registerCombinators(scope: scope) + } + for genericParam in genericParameters { + let typeIdParam = scope.variable("\(genericParam.lowercased())TypeId") + let codecVar = scope.variable("codec\(genericParam)") + body.write("const \(codecVar) = __bjs_codecForTypeId(\(typeIdParam));") + genericCodecVariables[genericParam] = codecVar + genericTypeIdParameters[genericParam] = typeIdParam + } + } + func liftParameter(param: Parameter) throws { + if let name = param.type.referencedGenericName { + guard let codecVar = genericCodecVariables[name] else { + throw BridgeJSLinkError( + message: "Generic codec for '\(name)' was not declared before lifting parameter '\(param.name)'" + ) + } + let valueVar = scope.variable(param.name) + let liftExpr = + GenericJSCodegen.genericCodecLiftExpression(type: param.type, codec: codecVar) + ?? "\(codecVar).lift()" + body.write("const \(valueVar) = \(liftExpr);") + parameterForwardings.append(valueVar) + return + } let liftingFragment = try IntrinsicJSFragment.liftParameter(type: param.type, context: context) let valuesToLift: [String] if liftingFragment.parameters.count == 0 { @@ -2427,6 +2560,16 @@ extension BridgeJSLink { parameterForwardings.append(contentsOf: liftedValues) } + func liftParametersAndGenericTypeIds(_ parameters: [Parameter], genericParameters: [String]) throws { + declareGenericCodecs(genericParameters: genericParameters) + for param in parameters { + try liftParameter(param: param) + } + for genericParam in genericParameters { + parameterNames.append(genericTypeIdParameters[genericParam] ?? genericParam) + } + } + func renderFunction(name: String?) -> [String] { if effects.isAsync { return renderAsyncFunction(name: name) @@ -2503,6 +2646,25 @@ extension BridgeJSLink { body.write("\(callExpr).then(resolve, reject);") return } + if let name = returnType.referencedGenericName { + guard let codecVar = genericCodecVariables[name] else { + throw BridgeJSLinkError( + message: "Generic codec for return type '\(name)' was not declared before the call" + ) + } + let resultVariable = scope.variable("ret") + body.write("let \(resultVariable) = \(callExpr);") + let lowerStmt = + GenericJSCodegen.genericCodecLowerStatement( + type: returnType, + codec: codecVar, + value: resultVariable + ) + ?? "\(codecVar).lower(\(resultVariable));" + body.write(lowerStmt) + self.returnExpr = nil + return + } let loweringFragment = try IntrinsicJSFragment.lowerReturn(type: returnType, context: context) let returnExpr: String? if loweringFragment.parameters.count == 0 { @@ -3488,9 +3650,11 @@ extension BridgeJSLink { returnType: function.returnType, intrinsicRegistry: intrinsicRegistry ) - for param in function.parameters { - try thunkBuilder.liftParameter(param: param) - } + let genericParameters = function.genericParameterNames + try thunkBuilder.liftParametersAndGenericTypeIds( + function.parameters, + genericParameters: genericParameters + ) let jsName = function.resolvedJSName let calleeExpr = try importedModuleRegistry.memberExpression( swiftModuleName: importObjectBuilder.moduleName, @@ -3501,9 +3665,10 @@ extension BridgeJSLink { try thunkBuilder.call(calleeExpr: calleeExpr) let funcLines = thunkBuilder.renderFunction(name: function.abiName(context: nil)) if function.from == nil { + let genericClause = renderGenericClause(genericParameters) importObjectBuilder.appendDts( [ - "\(renderTSPropertyName(jsName))\(renderTSSignature(parameters: function.parameters, returnType: function.returnType, effects: function.effects));" + "\(renderTSPropertyName(jsName))\(genericClause)\(renderTSSignature(parameters: function.parameters, returnType: function.returnType, effects: function.effects));" ] ) } @@ -3592,14 +3757,16 @@ extension BridgeJSLink { dtsPrinter.indent { if let constructor = type.constructor { let returnType = BridgeType.jsObject(type.name) + let genericClause = renderGenericClause(constructor.genericParameterNames) dtsPrinter.write( - "new\(renderTSSignature(parameters: constructor.parameters, returnType: returnType, effects: Effects(isAsync: false, isThrows: false)));" + "new\(genericClause)\(renderTSSignature(parameters: constructor.parameters, returnType: returnType, effects: Effects(isAsync: false, isThrows: false)));" ) } for method in type.staticMethods { let methodName = method.resolvedJSName + let genericClause = renderGenericClause(method.genericParameterNames) let signature = - "\(renderTSPropertyName(methodName))\(renderTSSignature(parameters: method.parameters, returnType: method.returnType, effects: method.effects));" + "\(renderTSPropertyName(methodName))\(genericClause)\(renderTSSignature(parameters: method.parameters, returnType: method.returnType, effects: method.effects));" dtsPrinter.write(signature) } } @@ -3623,9 +3790,10 @@ extension BridgeJSLink { returnType: BridgeType.jsObject(type.name), intrinsicRegistry: intrinsicRegistry ) - for param in constructor.parameters { - try thunkBuilder.liftParameter(param: param) - } + try thunkBuilder.liftParametersAndGenericTypeIds( + constructor.parameters, + genericParameters: constructor.genericParameterNames + ) let ctorExpr = try importedModuleRegistry.memberExpression( swiftModuleName: importObjectBuilder.moduleName, from: type.from, @@ -3682,9 +3850,10 @@ extension BridgeJSLink { returnType: method.returnType, intrinsicRegistry: intrinsicRegistry ) - for param in method.parameters { - try thunkBuilder.liftParameter(param: param) - } + try thunkBuilder.liftParametersAndGenericTypeIds( + method.parameters, + genericParameters: method.genericParameterNames + ) let constructorExpr = try importedModuleRegistry.memberExpression( swiftModuleName: swiftModuleName, from: context.from, @@ -3706,9 +3875,11 @@ extension BridgeJSLink { intrinsicRegistry: intrinsicRegistry ) thunkBuilder.liftSelf() - for param in method.parameters { - try thunkBuilder.liftParameter(param: param) - } + let genericParameters = method.genericParameterNames + try thunkBuilder.liftParametersAndGenericTypeIds( + method.parameters, + genericParameters: genericParameters + ) try thunkBuilder.callMethod(name: method.resolvedJSName) let funcLines = thunkBuilder.renderFunction(name: method.abiName(context: context)) @@ -4052,6 +4223,8 @@ extension BridgeType { return "Record" case .alias(_, let underlying): return underlying.tsType + case .generic(let name): + return name } } diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift index 2bf656708..8da83fa18 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift @@ -35,6 +35,11 @@ final class JSGlueVariableScope { static let reservedSwiftClosureRegistry = "swiftClosureRegistry" static let reservedMakeSwiftClosure = "makeClosure" static let reservedTaStack = "taStack" + static let reservedCodecByTypeId = "__bjs_codecByTypeId" + static let reservedPrimitiveCodecs = "__bjs_primitiveCodecs" + static let reservedStringCodec = "__bjs_stringCodec" + static let reservedTypeHandlesRegistered = "__bjs_typeHandlesRegistered" + static let reservedRegisterTypeHandles = "__bjs_registerTypeHandles" private let intrinsicRegistry: JSIntrinsicRegistry @@ -65,6 +70,11 @@ final class JSGlueVariableScope { reservedSwiftClosureRegistry, reservedMakeSwiftClosure, reservedTaStack, + reservedCodecByTypeId, + reservedPrimitiveCodecs, + reservedStringCodec, + reservedTypeHandlesRegistered, + reservedRegisterTypeHandles, ] init(intrinsicRegistry: JSIntrinsicRegistry) { @@ -138,6 +148,271 @@ extension JSGlueVariableScope { } } +enum GenericJSCodegen { + /// Wraps a bare element codec into the codec for the wrapped form (`[T]`, + /// `T?`, `[String: T]`) used at a generic call site, or `nil` when the type + /// is not a generic reference. + static func genericCodecExpression(type: BridgeType, codec: String) -> String? { + switch type { + case .generic: return codec + case .array(.generic): return "\(ContainerCodecJS.arrayCodec)(\(codec))" + case .nullable(.generic, let kind): + return ContainerCodecJS.optionalCodecExpression(elementCodec: codec, kind: kind) + case .dictionary(.generic): return "\(ContainerCodecJS.dictCodec)(\(codec))" + default: return nil + } + } + + static func genericCodecLowerStatement(type: BridgeType, codec: String, value: String) -> String? { + genericCodecExpression(type: type, codec: codec).map { "\($0).lower(\(value));" } + } + + static func genericCodecLiftExpression(type: BridgeType, codec: String) -> String? { + genericCodecExpression(type: type, codec: codec).map { "\($0).lift()" } + } + + /// Generic-only runtime: resolves a wasm-side type ID to the codec + /// registered for it. The container codec combinators themselves live in + /// `ContainerCodecJS` and are shared with the non-generic bridging paths. + static func runtimeHelperDeclarations() -> [String] { + let codecByTypeId = JSGlueVariableScope.reservedCodecByTypeId + return [ + "function __bjs_codecForTypeId(typeId) {", + " __bjs_registerTypeHandles();", + " const codec = \(codecByTypeId).get(typeId);", + " if (!codec) {", + " throw new Error(\"BridgeJS: no codec registered for type ID \" + typeId);", + " }", + " return codec;", + "}", + ] + } +} + +/// Shared `{ lower, lift }` codec codegen: each container's stack ABI is +/// described once by a combinator and instantiated with an element codec by +/// both the generic and non-generic paths. Emitted lazily via the intrinsic +/// registry, so builds that bridge no containers pay nothing. +enum ContainerCodecJS { + static let arrayCodec = "__bjs_arrayCodec" + static let optionalCodec = "__bjs_optionalCodec" + static let dictCodec = "__bjs_dictCodec" + static let enumCodec = "__bjs_enumCodec" + + private static let combinatorIntrinsicName = "containerCodecCombinators" + private static let primitiveCodecIntrinsicName = "containerPrimitiveCodecs" + + /// The single description of each container shape's stack ABI. + static func combinatorDeclarations() -> [String] { + let i32 = JSGlueVariableScope.reservedI32Stack + let stringCodec = JSGlueVariableScope.reservedStringCodec + return [ + "function \(arrayCodec)(elementCodec) {", + " return {", + " lower(value) {", + " for (let i = 0; i < value.length; i++) {", + " elementCodec.lower(value[i]);", + " }", + " \(i32).push(value.length);", + " },", + " lift() {", + " const count = \(i32).pop();", + " if (count === -1) {", + " return \(JSGlueVariableScope.reservedTaStack).pop();", + " }", + " const result = new Array(count);", + " for (let i = count - 1; i >= 0; i--) {", + " result[i] = elementCodec.lift();", + " }", + " return result;", + " },", + " };", + "}", + // `isUndefinedOr` selects the `JSUndefinedOr` flavor: `null` is then a + // present value and absence surfaces as `undefined` instead of `null`. + "function \(optionalCodec)(elementCodec, isUndefinedOr = false) {", + " return {", + " lower(value) {", + " const isSome = isUndefinedOr ? value !== undefined : value != null;", + " if (isSome) {", + " elementCodec.lower(value);", + " \(i32).push(1);", + " } else {", + " \(i32).push(0);", + " }", + " },", + " lift() {", + " if (\(i32).pop() === 0) {", + " return isUndefinedOr ? undefined : null;", + " }", + " return elementCodec.lift();", + " },", + " };", + "}", + "function \(dictCodec)(valueCodec) {", + " return {", + " lower(value) {", + " const keys = Object.keys(value);", + " for (let i = 0; i < keys.length; i++) {", + " \(stringCodec).lower(keys[i]);", + " valueCodec.lower(value[keys[i]]);", + " }", + " \(i32).push(keys.length);", + " },", + " lift() {", + " const count = \(i32).pop();", + " const result = {};", + " for (let i = 0; i < count; i++) {", + " const value = valueCodec.lift();", + " const key = \(stringCodec).lift();", + " result[key] = value;", + " }", + " return result;", + " },", + " };", + "}", + // Adapts an associated-value enum helper (whose lower returns the case + // tag and whose lift takes it) to the plain stack codec protocol. + "function \(enumCodec)(helper) {", + " return {", + " lower(value) {", + " \(i32).push(helper.lower(value));", + " },", + " lift() {", + " return helper.lift(\(i32).pop());", + " },", + " };", + "}", + ] + } + + static func optionalCodecExpression(elementCodec: String, kind: JSOptionalKind) -> String { + switch kind { + case .null: return "\(optionalCodec)(\(elementCodec))" + case .undefined: return "\(optionalCodec)(\(elementCodec), true)" + } + } + + static func registerCombinators(scope: JSGlueVariableScope) { + scope.registerIntrinsic(combinatorIntrinsicName) { printer in + printer.write(lines: combinatorDeclarations()) + } + } + + /// Emits `__bjs_stringCodec` and the `__bjs_primitiveCodecs` table shared + /// by combinator instantiations and the generic type-handle registration. + static func registerPrimitiveCodecs(context: IntrinsicJSFragment.PrintCodeContext) throws { + try context.scope.registerIntrinsic(primitiveCodecIntrinsicName) { printer in + let stringCodec = JSGlueVariableScope.reservedStringCodec + // The String codec is named so the dictionary codec combinator can + // lower/lift keys through it. + try writeCodecLiteral( + type: .string, + into: printer, + context: context, + prefix: "const \(stringCodec) = ", + suffix: ";" + ) + printer.write("const \(JSGlueVariableScope.reservedPrimitiveCodecs) = {") + try printer.indent { + for primitive in BridgeType.genericBridgeablePrimitives { + if case .string = primitive.type { + printer.write("\(primitive.token): \(stringCodec),") + } else { + try writeCodecLiteral( + type: primitive.type, + into: printer, + context: context, + prefix: "\(primitive.token): ", + suffix: "," + ) + } + } + } + printer.write("};") + } + } + + /// Emits a `{ lower, lift }` codec literal for one bridgeable type. + /// `prefix` is prepended to the opening brace (e.g. an assignment) and + /// `suffix` is appended to the closing brace (e.g. `","` in an object). + static func writeCodecLiteral( + type: BridgeType, + into printer: CodeFragmentPrinter, + context: IntrinsicJSFragment.PrintCodeContext, + prefix: String = "", + suffix: String = "," + ) throws { + func literalContext() -> IntrinsicJSFragment.PrintCodeContext { + context.with(\.printer, printer).with(\.scope, context.scope.makeChildScope()) + } + let lowerFragment = try IntrinsicJSFragment.stackLowerFragment(elementType: type) + let liftFragment = try IntrinsicJSFragment.stackLiftFragment(elementType: type) + printer.write("\(prefix){") + try printer.indent { + printer.write("lower: (v) => {") + try printer.indent { + _ = try lowerFragment.printCode(["v"], literalContext()) + } + printer.write("},") + printer.write("lift: () => {") + try printer.indent { + let results = try liftFragment.printCode([], literalContext()) + printer.write("return \(results[0]);") + } + printer.write("},") + } + printer.write("}\(suffix)") + } + + /// Returns a JS expression evaluating to the `{ lower, lift }` codec for + /// one element type, registering the shared codec runtime as needed. May + /// write supporting statements (a local codec literal) to the context's + /// printer for element shapes without a named shared codec. + static func codecExpression( + for elementType: BridgeType, + context: IntrinsicJSFragment.PrintCodeContext + ) throws -> String { + registerCombinators(scope: context.scope) + try registerPrimitiveCodecs(context: context) + let type = elementType.unaliased + switch type { + case .array(let element): + return "\(arrayCodec)(\(try codecExpression(for: element, context: context)))" + case .dictionary(let value): + return "\(dictCodec)(\(try codecExpression(for: value, context: context)))" + case .nullable(let wrapped, let kind): + let element = try codecExpression(for: wrapped, context: context) + return optionalCodecExpression(elementCodec: element, kind: kind) + case .string, .rawValueEnum(_, .string): + return JSGlueVariableScope.reservedStringCodec + case .swiftStruct(let fullName): + // `@JS` struct helpers already expose the codec protocol. + let base = fullName.replacingOccurrences(of: ".", with: "_") + return "\(JSGlueVariableScope.reservedStructHelpers).\(base)" + case .associatedValueEnum(let fullName): + let base = fullName.components(separatedBy: ".").last ?? fullName + return "\(enumCodec)(\(JSGlueVariableScope.reservedEnumHelpers).\(base))" + default: + if let token = BridgeType.genericBridgeablePrimitives.first(where: { $0.type == type })?.token { + return "\(JSGlueVariableScope.reservedPrimitiveCodecs).\(token)" + } + // Element shapes without a named shared codec (case enums, non-string + // raw-value enums, JSObject, Swift heap objects, ...) get a local + // codec literal built from the same element stack fragments. + let codecVar = context.scope.variable("elemCodec") + try writeCodecLiteral( + type: type, + into: context.printer, + context: context, + prefix: "const \(codecVar) = ", + suffix: ";" + ) + return codecVar + } + } +} + /// A fragment of JS code used to convert a value between Swift and JS. /// /// See `BridgeJSIntrinsics.swift` in the main JavaScriptKit module for Swift side lowering/lifting implementation. @@ -681,6 +956,12 @@ struct IntrinsicJSFragment: Sendable { ) } + /// Lift an optional parameter whose presence flag arrives as a wasm + /// parameter (not on the i32 stack), with the payload either in further + /// wasm parameters or on the stacks. The shared optional codec combinator + /// pops its flag from the i32 stack, so this ABI cannot go through it; + /// stack-convention payloads still lift through the shared container + /// codecs via `stackLiftFragment`. private static func compositeOptionalLiftParameter( wrappedType: BridgeType, kind: JSOptionalKind, @@ -761,26 +1042,26 @@ struct IntrinsicJSFragment: Sendable { ) } - let innerFragment = - if wrappedType.optionalParameterUsesStackABI { - try stackLowerFragment(elementType: wrappedType) - } else { - try lowerParameter(type: wrappedType) - } + if wrappedType.optionalParameterUsesStackABI { + // Stack convention: the conditional flag-plus-payload protocol is + // the shared optional codec's stack ABI. + return try optionalElementLowerFragment(wrappedType: wrappedType, kind: kind) + } return try compositeOptionalLowerParameter( wrappedType: wrappedType, kind: kind, - innerFragment: innerFragment + innerFragment: try lowerParameter(type: wrappedType) ) } + /// Lower an optional parameter using the direct `(isSome, ...payload)` wasm + /// parameter ABI with zero placeholders for nil. This is not the container + /// stack ABI, so it cannot go through the shared optional codec combinator. private static func compositeOptionalLowerParameter( wrappedType: BridgeType, kind: JSOptionalKind, innerFragment: IntrinsicJSFragment ) throws -> IntrinsicJSFragment { - let isStackConvention = wrappedType.optionalParameterUsesStackABI - return IntrinsicJSFragment( parameters: ["value"], printCode: { arguments, context in @@ -797,7 +1078,7 @@ struct IntrinsicJSFragment: Sendable { let resultVars = innerResults.map { _ in scope.variable("result") } assert( - isStackConvention || resultVars.count == wrappedType.wasmParams.count, + resultVars.count == wrappedType.wasmParams.count, "Inner fragment result count (\(resultVars.count)) must match wasmParams count (\(wrappedType.wasmParams.count)) for \(wrappedType)" ) if !resultVars.isEmpty { @@ -814,8 +1095,7 @@ struct IntrinsicJSFragment: Sendable { } } - let hasPlaceholders = !isStackConvention && !wrappedType.wasmParams.isEmpty - if hasPlaceholders { + if !wrappedType.wasmParams.isEmpty { printer.write("} else {") printer.indent { for (resultVar, param) in zip(resultVars, wrappedType.wasmParams) { @@ -825,12 +1105,7 @@ struct IntrinsicJSFragment: Sendable { } printer.write("}") - if isStackConvention { - scope.emitPushI32Parameter("+\(isSomeVar)", printer: printer) - return [] - } else { - return ["+\(isSomeVar)"] + resultVars - } + return ["+\(isSomeVar)"] + resultVars } ) } @@ -848,6 +1123,9 @@ struct IntrinsicJSFragment: Sendable { ) } + /// Lift an optional return whose presence flag travels on the i32 stack but + /// whose payload uses the wrapped type's regular (non-stack) return ABI, so + /// it cannot go through the shared optional codec combinator. private static func optionalLiftReturnWithPresenceFlag( wrappedType: BridgeType, kind: JSOptionalKind @@ -860,12 +1138,7 @@ struct IntrinsicJSFragment: Sendable { let isSomeVar = scope.variable("isSome") printer.write("const \(isSomeVar) = \(scope.popI32());") - let innerFragment = - if wrappedType.optionalConvention == .stackABI { - try stackLiftFragment(elementType: wrappedType) - } else { - try liftReturn(type: wrappedType) - } + let innerFragment = try liftReturn(type: wrappedType) let innerPrinter = CodeFragmentPrinter() let innerResults = try innerFragment.printCode([], context.with(\.printer, innerPrinter)) @@ -942,31 +1215,13 @@ struct IntrinsicJSFragment: Sendable { ) } - private static func optionalLiftReturnStruct( - fullName: String, - kind: JSOptionalKind - ) -> IntrinsicJSFragment { - let base = fullName.replacingOccurrences(of: ".", with: "_") - let absenceLiteral = kind.absenceLiteral - return IntrinsicJSFragment( - parameters: [], - printCode: { _, context in - let (scope, printer) = (context.scope, context.printer) - let isSomeVar = scope.variable("isSome") - let resultVar = scope.variable("optResult") - printer.write("const \(isSomeVar) = \(scope.popI32());") - printer.write( - "const \(resultVar) = \(isSomeVar) ? \(JSGlueVariableScope.reservedStructHelpers).\(base).lift() : \(absenceLiteral);" - ) - return [resultVar] - } - ) - } - static func optionalLiftReturn( wrappedType: BridgeType, kind: JSOptionalKind - ) -> IntrinsicJSFragment { + ) throws -> IntrinsicJSFragment { + // Side-channel optionals deliver their payload through dedicated + // storage/imports instead of the bridge stacks, so they cannot go + // through the shared optional codec combinator. if let scalarKind = wrappedType.optionalScalarKind { return optionalLiftReturnFromStorage(storage: scalarKind.storageName) } @@ -974,18 +1229,21 @@ struct IntrinsicJSFragment: Sendable { return optionalLiftReturnFromStorage(storage: JSGlueVariableScope.reservedStorageToReturnString) } + // Heap object optionals use the tmpRetOptionalHeapObject side channel. if case .swiftHeapObject(let className) = wrappedType { return optionalLiftReturnHeapObject(className: className, kind: kind) } - if case .swiftStruct(let fullName) = wrappedType { - return optionalLiftReturnStruct(fullName: fullName, kind: kind) - } - + // Sentinel optionals encode nil in-band (tag -1), with no presence flag. if wrappedType.nilSentinel.hasSentinel, case .associatedValueEnum(let fullName) = wrappedType { return optionalLiftReturnAssociatedEnum(fullName: fullName, kind: kind) } + if wrappedType.optionalConvention == .stackABI { + // Stack convention: route through the shared optional codec combinator. + return try optionalElementRaiseFragment(wrappedType: wrappedType, kind: kind) + } + return optionalLiftReturnWithPresenceFlag(wrappedType: wrappedType, kind: kind) } @@ -1111,12 +1369,8 @@ struct IntrinsicJSFragment: Sendable { } if wrappedType.optionalConvention == .stackABI { - let innerFragment = try stackLowerFragment(elementType: wrappedType) - return stackOptionalLower( - wrappedType: wrappedType, - kind: kind, - innerFragment: innerFragment - ) + // Stack convention: route through the shared optional codec combinator. + return try optionalElementLowerFragment(wrappedType: wrappedType, kind: kind) } if wrappedType.nilSentinel.hasSentinel { @@ -1248,39 +1502,6 @@ struct IntrinsicJSFragment: Sendable { } } - /// Lower an optional value to the stack using the **conditional** protocol: - /// push isSome flag, then conditionally push the payload (no placeholders for nil). - private static func stackOptionalLower( - wrappedType: BridgeType, - kind: JSOptionalKind, - innerFragment: IntrinsicJSFragment - ) -> IntrinsicJSFragment { - IntrinsicJSFragment( - parameters: ["value"], - printCode: { arguments, context in - let (scope, printer) = (context.scope, context.printer) - let value = arguments[0] - let isSomeVar = scope.variable("isSome") - printer.write("const \(isSomeVar) = \(kind.presenceCheck(value: value));") - - let ifBodyPrinter = CodeFragmentPrinter() - try ifBodyPrinter.indent { - let _ = try innerFragment.printCode( - [value], - context.with(\.printer, ifBodyPrinter) - ) - } - printer.write("if (\(isSomeVar)) {") - for line in ifBodyPrinter.lines { - printer.write(line) - } - printer.write("}") - scope.emitPushI32Parameter("\(isSomeVar) ? 1 : 0", printer: printer) - return [] - } - ) - } - // MARK: - ExportSwift /// Returns a fragment that lowers a JS value to Wasm core values for parameters @@ -1357,7 +1578,7 @@ struct IntrinsicJSFragment: Sendable { case .swiftProtocol: return .jsObjectLiftReturn case .void: return .void case .nullable(let wrappedType, let kind): - return .optionalLiftReturn(wrappedType: wrappedType, kind: kind) + return try .optionalLiftReturn(wrappedType: wrappedType, kind: kind) case .rawValueEnum(_, .string): return .stringLiftReturn case .associatedValueEnum(let fullName): let base = fullName.components(separatedBy: ".").last ?? fullName @@ -1807,133 +2028,61 @@ struct IntrinsicJSFragment: Sendable { // MARK: - Array Helpers - /// Lowers an array from JS to Swift by iterating elements and pushing to stacks + /// Lowers an array from JS to Swift through the shared array codec combinator static func arrayLower(elementType: BridgeType) throws -> IntrinsicJSFragment { return IntrinsicJSFragment( parameters: ["arr"], printCode: { arguments, context in - let (scope, printer) = (context.scope, context.printer) - let arr = arguments[0] - - let elemVar = scope.variable("elem") - printer.write("for (const \(elemVar) of \(arr)) {") - try printer.indent { - let elementFragment = try stackLowerFragment(elementType: elementType) - let _ = try elementFragment.printCode( - [elemVar], - context - ) - } - printer.write("}") - scope.emitPushI32Parameter("\(arr).length", printer: printer) + let element = try ContainerCodecJS.codecExpression(for: elementType, context: context) + context.printer.write("\(ContainerCodecJS.arrayCodec)(\(element)).lower(\(arguments[0]));") return [] } ) } - /// Lowers a dictionary from JS to Swift by iterating entries and pushing to stacks + /// Lowers a dictionary from JS to Swift through the shared dictionary codec combinator static func dictionaryLower(valueType: BridgeType) throws -> IntrinsicJSFragment { return IntrinsicJSFragment( parameters: ["dict"], printCode: { arguments, context in - let (scope, printer) = (context.scope, context.printer) - let dict = arguments[0] - - let entriesVar = scope.variable("entries") - let entryVar = scope.variable("entry") - printer.write("const \(entriesVar) = Object.entries(\(dict));") - printer.write("for (const \(entryVar) of \(entriesVar)) {") - try printer.indent { - let keyVar = scope.variable("key") - let valueVar = scope.variable("value") - printer.write("const [\(keyVar), \(valueVar)] = \(entryVar);") - - let keyFragment = try stackLowerFragment(elementType: .string) - let _ = try keyFragment.printCode( - [keyVar], - context - ) - - let valueFragment = try stackLowerFragment(elementType: valueType) - let _ = try valueFragment.printCode( - [valueVar], - context - ) - } - printer.write("}") - scope.emitPushI32Parameter("\(entriesVar).length", printer: printer) + let value = try ContainerCodecJS.codecExpression(for: valueType, context: context) + context.printer.write("\(ContainerCodecJS.dictCodec)(\(value)).lower(\(arguments[0]));") return [] } ) } - /// Lifts an array from Swift to JS by popping elements from stacks + /// Lifts an array from Swift to JS through the shared array codec combinator static func arrayLift(elementType: BridgeType) throws -> IntrinsicJSFragment { return IntrinsicJSFragment( parameters: [], - printCode: { arguments, context in - let (scope, printer) = (context.scope, context.printer) - let resultVar = scope.variable("arrayResult") - let lenVar = scope.variable("arrayLen") - - printer.write("const \(lenVar) = \(scope.popI32());") - printer.write("let \(resultVar);") - printer.write("if (\(lenVar) === -1) {") - printer.indent { - // Bulk path: Swift pushed a typed array onto the typed-array stack - printer.write("\(resultVar) = \(JSGlueVariableScope.reservedTaStack).pop();") - } - printer.write("} else {") - try printer.indent { - // Element-by-element path (original behavior) - let iVar = scope.variable("i") - printer.write("\(resultVar) = [];") - printer.write("for (let \(iVar) = 0; \(iVar) < \(lenVar); \(iVar)++) {") - try printer.indent { - let elementFragment = try stackLiftFragment(elementType: elementType) - let elementResults = try elementFragment.printCode([], context) - if let elementExpr = elementResults.first { - printer.write("\(resultVar).push(\(elementExpr));") - } - } - printer.write("}") - printer.write("\(resultVar).reverse();") - } - printer.write("}") + printCode: { _, context in + let element = try ContainerCodecJS.codecExpression(for: elementType, context: context) + let resultVar = context.scope.variable("arrayResult") + context.printer.write( + "const \(resultVar) = \(ContainerCodecJS.arrayCodec)(\(element)).lift();" + ) return [resultVar] } ) } - /// Lifts a dictionary from Swift to JS by popping key/value pairs from stacks + /// Lifts a dictionary from Swift to JS through the shared dictionary codec combinator static func dictionaryLift(valueType: BridgeType) throws -> IntrinsicJSFragment { return IntrinsicJSFragment( parameters: [], - printCode: { arguments, context in - let (scope, printer) = (context.scope, context.printer) - let resultVar = scope.variable("dictResult") - let lenVar = scope.variable("dictLen") - let iVar = scope.variable("i") - - printer.write("const \(lenVar) = \(scope.popI32());") - printer.write("const \(resultVar) = {};") - printer.write("for (let \(iVar) = 0; \(iVar) < \(lenVar); \(iVar)++) {") - try printer.indent { - let valueFragment = try stackLiftFragment(elementType: valueType) - let valueResults = try valueFragment.printCode([], context) - let keyFragment = try stackLiftFragment(elementType: .string) - let keyResults = try keyFragment.printCode([], context) - if let keyExpr = keyResults.first, let valueExpr = valueResults.first { - printer.write("\(resultVar)[\(keyExpr)] = \(valueExpr);") - } - } - printer.write("}") + printCode: { _, context in + let value = try ContainerCodecJS.codecExpression(for: valueType, context: context) + let resultVar = context.scope.variable("dictResult") + context.printer.write( + "const \(resultVar) = \(ContainerCodecJS.dictCodec)(\(value)).lift();" + ) return [resultVar] } ) } - private static func stackLiftFragment(elementType: BridgeType) throws -> IntrinsicJSFragment { + static func stackLiftFragment(elementType: BridgeType) throws -> IntrinsicJSFragment { if case .nullable(let wrappedType, let kind) = elementType { return try optionalElementRaiseFragment(wrappedType: wrappedType, kind: kind) } @@ -2060,7 +2209,7 @@ struct IntrinsicJSFragment: Sendable { } } - private static func stackLowerFragment(elementType: BridgeType) throws -> IntrinsicJSFragment { + static func stackLowerFragment(elementType: BridgeType) throws -> IntrinsicJSFragment { if case .nullable(let wrappedType, let kind) = elementType { return try optionalElementLowerFragment(wrappedType: wrappedType, kind: kind) } @@ -2181,43 +2330,27 @@ struct IntrinsicJSFragment: Sendable { } } + /// Lift an optional from the stack (isSome flag, then conditional payload) + /// through the shared optional codec combinator. private static func optionalElementRaiseFragment( wrappedType: BridgeType, kind: JSOptionalKind ) throws -> IntrinsicJSFragment { - let absenceLiteral = kind.absenceLiteral return IntrinsicJSFragment( parameters: [], - printCode: { arguments, context in - let (scope, printer) = (context.scope, context.printer) - let isSomeVar = scope.variable("isSome") - let resultVar = scope.variable("optValue") - - printer.write("const \(isSomeVar) = \(scope.popI32());") - printer.write("let \(resultVar);") - printer.write("if (\(isSomeVar) === 0) {") - printer.indent { - printer.write("\(resultVar) = \(absenceLiteral);") - } - printer.write("} else {") - try printer.indent { - let innerFragment = try stackLiftFragment(elementType: wrappedType) - let innerResults = try innerFragment.printCode([], context) - if let innerResult = innerResults.first { - printer.write("\(resultVar) = \(innerResult);") - } else { - printer.write("\(resultVar) = undefined;") - } - } - printer.write("}") - + printCode: { _, context in + let element = try ContainerCodecJS.codecExpression(for: wrappedType, context: context) + let resultVar = context.scope.variable("optValue") + let codec = ContainerCodecJS.optionalCodecExpression(elementCodec: element, kind: kind) + context.printer.write("const \(resultVar) = \(codec).lift();") return [resultVar] } ) } - /// Lower an optional element to the stack using the **conditional** protocol: - /// push isSome flag, then conditionally push the payload (no placeholders for nil). + /// Lower an optional value to the stack using the **conditional** protocol + /// (push isSome flag, then conditionally push the payload) through the + /// shared optional codec combinator. private static func optionalElementLowerFragment( wrappedType: BridgeType, kind: JSOptionalKind @@ -2225,23 +2358,9 @@ struct IntrinsicJSFragment: Sendable { return IntrinsicJSFragment( parameters: ["value"], printCode: { arguments, context in - let (scope, printer) = (context.scope, context.printer) - let value = arguments[0] - let isSomeVar = scope.variable("isSome") - - let presenceExpr = kind.presenceCheck(value: value) - printer.write("const \(isSomeVar) = \(presenceExpr) ? 1 : 0;") - printer.write("if (\(isSomeVar)) {") - try printer.indent { - let innerFragment = try stackLowerFragment(elementType: wrappedType) - let _ = try innerFragment.printCode( - [value], - context - ) - } - printer.write("}") - scope.emitPushI32Parameter(isSomeVar, printer: printer) - + let element = try ContainerCodecJS.codecExpression(for: wrappedType, context: context) + let codec = ContainerCodecJS.optionalCodecExpression(elementCodec: element, kind: kind) + context.printer.write("\(codec).lower(\(arguments[0]));") return [] } ) @@ -2608,7 +2727,7 @@ private extension BridgeType { return .inlineFlag case .closure: return .inlineFlag - case .swiftStruct, .array, .dictionary, .void, .namespaceEnum: + case .swiftStruct, .array, .dictionary, .void, .namespaceEnum, .generic: return .stackABI case .nullable(let wrapped, _): return wrapped.optionalConvention @@ -2706,7 +2825,7 @@ private extension BridgeType { return [("caseId", .i32)] case .closure: return [("funcRef", .i32)] - case .void, .namespaceEnum, .swiftStruct, .array, .dictionary: + case .void, .namespaceEnum, .swiftStruct, .array, .dictionary, .generic: return [] case .nullable(let wrapped, _): return wrapped.wasmParams diff --git a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift index 21704d1c9..2cea16fb4 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift @@ -22,6 +22,16 @@ extension NamespacedExportedType { public struct ABINameGenerator { static let prefixComponent = "bjs" + /// ABI parameter name carrying the runtime type ID for the generic parameter at `index`. + public static func genericTypeIdParameterName(index: Int) -> String { "_generic\(index)TypeId" } + + /// Name of the per-module type-handle registration function. The wasm module + /// exports it under this name, and it calls back into a JS import hook of the + /// same name (in the `bjs` import namespace) with a buffer of type IDs. + public static func typeRegistrationFunctionName(moduleName: String) -> String { + "bjs_\(moduleName)_register_type_handles" + } + /// Generates ABI name using standardized namespace + context pattern public static func generateABIName( baseName: String, @@ -273,10 +283,120 @@ public enum BridgeType: Codable, Equatable, Hashable, Sendable { case namespaceEnum(String) case swiftProtocol(String) case swiftStruct(String) + case generic(String) indirect case closure(ClosureSignature, useJSTypedClosure: Bool) indirect case alias(name: String, underlying: BridgeType) } +extension BridgeType { + public var referencedGenericName: String? { + switch self { + case .generic(let name): return name + case .array(.generic(let name)): return name + case .nullable(.generic(let name), _): return name + case .dictionary(.generic(let name)): return name + default: return nil + } + } + + public static let genericBridgeablePrimitives: [(token: String, type: BridgeType)] = [ + ("Bool", .bool), + ("Int", .integer(.int)), + ("Int8", .integer(.int8)), + ("UInt8", .integer(.uint8)), + ("Int16", .integer(.int16)), + ("UInt16", .integer(.uint16)), + ("Int32", .integer(.int32)), + ("UInt32", .integer(.uint32)), + ("UInt", .integer(.uint)), + ("Int64", .integer(.int64)), + ("UInt64", .integer(.uint64)), + ("Float", .float), + ("Double", .double), + ("String", .string), + ("JSValue", .jsValue), + ] + +} + +// MARK: - Generic type registration + +/// One `BridgedSwiftGenericBridgeable` type participating in generic bridging. +/// +/// `swiftName` is the Swift expression naming the type (used by Swift codegen to +/// read `.bridgeJSTypeID`); `bridgeType` describes the stack ABI (used +/// by the JS link layer to emit the matching codec). +public struct GenericBridgeableTypeEntry: Sendable { + public let swiftName: String + public let bridgeType: BridgeType + + public init(swiftName: String, bridgeType: BridgeType) { + self.swiftName = swiftName + self.bridgeType = bridgeType + } +} + +extension ExportedEnum { + /// The `BridgeType` an enum bridges as when used as a generic argument, or + /// `nil` when it can't be one (namespace enums). + public var genericBridgeType: BridgeType? { + switch enumType { + case .simple: + return .caseEnum(name) + case .rawValue: + guard let rawType = rawType else { return nil } + return .rawValueEnum(name, rawType) + case .associatedValue: + return .associatedValueEnum(name) + case .namespace: + return nil + } + } +} + +extension ExportedSkeleton { + /// The module's `@JS` types that conform to `BridgedSwiftGenericBridgeable`. + /// The order is the contract between the Swift registration function and the + /// JS codec array; both derive it from this skeleton, so they line up. + public var genericBridgeableTypeEntries: [GenericBridgeableTypeEntry] { + var entries: [GenericBridgeableTypeEntry] = [] + for structDef in structs { + entries.append( + GenericBridgeableTypeEntry( + swiftName: structDef.swiftCallName, + bridgeType: .swiftStruct(structDef.abiName) + ) + ) + } + for klass in classes where klass.isFinal == true { + entries.append( + GenericBridgeableTypeEntry(swiftName: klass.swiftCallName, bridgeType: .swiftHeapObject(klass.name)) + ) + } + for enumDef in enums { + guard let bridgeType = enumDef.genericBridgeType else { continue } + entries.append(GenericBridgeableTypeEntry(swiftName: enumDef.swiftCallName, bridgeType: bridgeType)) + } + return entries + } +} + +extension BridgeJSSkeleton { + /// The ordered list of types this module registers type handles for, or + /// `nil` when it emits no registration function. Primitive handles are + /// library singletons, so every module re-registering them writes the same + /// ID-to-codec pair, and a pure-import build still gets a populated table. + public var typeRegistrationEntries: [GenericBridgeableTypeEntry]? { + let exportedEntries = exported?.genericBridgeableTypeEntries ?? [] + let hasGenericImports = imported?.hasGenericDeclarations ?? false + guard !exportedEntries.isEmpty || hasGenericImports else { return nil } + let primitives = BridgeType.genericBridgeablePrimitives.map { + GenericBridgeableTypeEntry(swiftName: $0.token, bridgeType: $0.type) + } + return primitives + exportedEntries + } +} + public enum WasmCoreType: String, Codable, Sendable { case i32, i64, f32, f64, pointer } @@ -905,6 +1025,7 @@ public struct ExportedClass: Codable, NamespacedExportedType { public var namespace: [String]? public var identityMode: Bool? // nil = use config default, true/false = override public var documentation: String? + public var isFinal: Bool? public init( name: String, @@ -915,7 +1036,8 @@ public struct ExportedClass: Codable, NamespacedExportedType { properties: [ExportedProperty] = [], namespace: [String]? = nil, identityMode: Bool? = nil, - documentation: String? = nil + documentation: String? = nil, + isFinal: Bool? = nil ) { self.name = name self.swiftCallName = swiftCallName @@ -926,6 +1048,7 @@ public struct ExportedClass: Codable, NamespacedExportedType { self.namespace = namespace self.identityMode = identityMode self.documentation = documentation + self.isFinal = isFinal } } @@ -1254,6 +1377,9 @@ public struct ImportedFunctionSkeleton: Codable { /// determine the access level of bridge-generated helpers (e.g. typed /// closure inits) that surface through this function's signature. public let accessLevel: BridgeJSAccessLevel + public let genericParameters: [String]? + public var genericParameterNames: [String] { genericParameters ?? [] } + public var isGeneric: Bool { !genericParameterNames.isEmpty } public var resolvedJSName: String { jsName ?? name } @@ -1265,7 +1391,8 @@ public struct ImportedFunctionSkeleton: Codable { returnType: BridgeType, effects: Effects = Effects(isAsync: false, isThrows: true), documentation: String? = nil, - accessLevel: BridgeJSAccessLevel = .internal + accessLevel: BridgeJSAccessLevel = .internal, + genericParameters: [String]? = nil ) { self.name = name self.jsName = jsName @@ -1275,10 +1402,11 @@ public struct ImportedFunctionSkeleton: Codable { self.effects = effects self.documentation = documentation self.accessLevel = accessLevel + self.genericParameters = genericParameters } private enum CodingKeys: String, CodingKey { - case name, jsName, from, parameters, returnType, effects, documentation, accessLevel + case name, jsName, from, parameters, returnType, effects, documentation, accessLevel, genericParameters } public init(from decoder: any Decoder) throws { @@ -1291,6 +1419,7 @@ public struct ImportedFunctionSkeleton: Codable { self.effects = try container.decode(Effects.self, forKey: .effects) self.documentation = try container.decodeIfPresent(String.self, forKey: .documentation) self.accessLevel = try container.decodeIfPresent(BridgeJSAccessLevel.self, forKey: .accessLevel) ?? .internal + self.genericParameters = try container.decodeIfPresent([String].self, forKey: .genericParameters) } public func abiName(context: ImportedTypeSkeleton?) -> String { @@ -1311,20 +1440,29 @@ public struct ImportedConstructorSkeleton: Codable { /// Source access level of the originating Swift `init`. Inherits from the /// enclosing `@JSClass` type when not annotated explicitly. public let accessLevel: BridgeJSAccessLevel + public let genericParameters: [String]? + public var genericParameterNames: [String] { genericParameters ?? [] } + public var isGeneric: Bool { !genericParameterNames.isEmpty } - public init(parameters: [Parameter], accessLevel: BridgeJSAccessLevel = .internal) { + public init( + parameters: [Parameter], + accessLevel: BridgeJSAccessLevel = .internal, + genericParameters: [String]? = nil + ) { self.parameters = parameters self.accessLevel = accessLevel + self.genericParameters = genericParameters } private enum CodingKeys: String, CodingKey { - case parameters, accessLevel + case parameters, accessLevel, genericParameters } public init(from decoder: any Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.parameters = try container.decode([Parameter].self, forKey: .parameters) self.accessLevel = try container.decodeIfPresent(BridgeJSAccessLevel.self, forKey: .accessLevel) ?? .internal + self.genericParameters = try container.decodeIfPresent([String].self, forKey: .genericParameters) } public func abiName(context: ImportedTypeSkeleton) -> String { @@ -1571,6 +1709,17 @@ public struct ImportedFileSkeleton: Codable { } } +extension ImportedFileSkeleton { + public var hasGenericDeclarations: Bool { + functions.contains(where: \.isGeneric) + || types.contains { + $0.methods.contains(where: \.isGeneric) + || $0.staticMethods.contains(where: \.isGeneric) + || ($0.constructor?.isGeneric ?? false) + } + } +} + public struct ImportedModuleSkeleton: Codable { public var children: [ImportedFileSkeleton] @@ -1579,6 +1728,12 @@ public struct ImportedModuleSkeleton: Codable { } } +extension ImportedModuleSkeleton { + public var hasGenericDeclarations: Bool { + children.contains { $0.hasGenericDeclarations } + } +} + // MARK: - Closure signature collection visitor public struct ClosureSignatureCollectorVisitor: BridgeSkeletonVisitor { @@ -1753,7 +1908,7 @@ extension BridgeType { case .bool, .integer, .float, .double, .string, .jsValue, .jsObject, .swiftHeapObject, .unsafePointer, .swiftProtocol, .void, .caseEnum, .rawValueEnum, .associatedValueEnum, .swiftStruct, - .namespaceEnum, .closure: + .namespaceEnum, .closure, .generic: return self } } @@ -1800,6 +1955,8 @@ extension BridgeType { return nil case .alias(_, let underlying): return underlying.abiReturnType + case .generic: + return nil } } @@ -1891,6 +2048,8 @@ extension BridgeType { // `name` is the namespace-qualified swiftCallName (unique), so the underlying // representation isn't mangled in - aliases bridge via their JS type's ABI. return "Al\(name.count)\(name)" + case .generic(let name): + return "\(name.count)\(name)T" } } diff --git a/Plugins/BridgeJS/Sources/BridgeJSTool/BridgeJSTool.swift b/Plugins/BridgeJS/Sources/BridgeJSTool/BridgeJSTool.swift index 140ebda63..96d9c4705 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSTool/BridgeJSTool.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSTool/BridgeJSTool.swift @@ -240,9 +240,12 @@ import BridgeJSUtilities return try exporter?.finalize() } + // Type-handle registration is shared by exported types and generic imports. + let typeRegistration = GenericTypeRegistrationCodegen().render(for: skeleton) + // Combine and write unified Swift output let outputSwiftURL = outputDirectory.appending(path: "BridgeJS.swift") - let combinedSwift = [closureSupport, exportResult, importResult].compactMap { $0 } + let combinedSwift = [closureSupport, exportResult, importResult, typeRegistration].compactMap { $0 } let outputSwift = combineGeneratedSwift( combinedSwift, importingExternalModules: skeleton.usedExternalModules diff --git a/Plugins/BridgeJS/Sources/BridgeJSToolInternal/BridgeJSToolInternal.swift b/Plugins/BridgeJS/Sources/BridgeJSToolInternal/BridgeJSToolInternal.swift index cb6a5481c..971c9608e 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSToolInternal/BridgeJSToolInternal.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSToolInternal/BridgeJSToolInternal.swift @@ -98,7 +98,8 @@ import ArgumentParser skeleton: $0 ).finalize() } - let combinedSwift = [exported, imported].compactMap { $0 } + let typeRegistration = GenericTypeRegistrationCodegen().render(for: skeleton) + let combinedSwift = [exported, imported, typeRegistration].compactMap { $0 } print(combinedSwift.joined(separator: "\n\n")) } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.json index bcdc43375..b47afb905 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.json @@ -79,6 +79,7 @@ } ] }, + "isFinal" : true, "methods" : [ { "abiName" : "bjs_PolygonReference_snapshot", @@ -196,6 +197,7 @@ } ] }, + "isFinal" : true, "methods" : [ ], diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.swift index a9252e57f..42b97761c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.swift @@ -257,6 +257,18 @@ fileprivate func _bjs_TagReference_wrap_extern(_ pointer: UnsafeMutableRawPointe return _bjs_TagReference_wrap_extern(pointer) } +extension PolygonReference: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = PolygonReference.bridgeJSMakeTypeHandle() +} + +extension TagReference: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = TagReference.bridgeJSMakeTypeHandle() +} + +extension InnerTag: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = InnerTag.bridgeJSMakeTypeHandle() +} + extension Polygon: _BridgedSwiftAlias, _BridgedSwiftStackType {} extension Tag: _BridgedSwiftAlias, _BridgedSwiftStackType {} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.json index d76761e0b..c9107133d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.json @@ -34,6 +34,7 @@ } ] }, + "isFinal" : true, "methods" : [ ], diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.swift index 3c87bcdcc..b91db4857 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.swift @@ -187,4 +187,8 @@ fileprivate func _bjs_PolygonReference_wrap_extern(_ pointer: UnsafeMutableRawPo return _bjs_PolygonReference_wrap_extern(pointer) } +extension PolygonReference: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = PolygonReference.bridgeJSMakeTypeHandle() +} + extension Polygon: _BridgedSwiftAlias, _BridgedSwiftStackType {} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift index 51c6911bd..cf5208f5d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift @@ -501,6 +501,18 @@ fileprivate func _bjs_MultiArrayContainer_wrap_extern(_ pointer: UnsafeMutableRa return _bjs_MultiArrayContainer_wrap_extern(pointer) } +extension Point: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Point.bridgeJSMakeTypeHandle() +} + +extension Direction: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Direction.bridgeJSMakeTypeHandle() +} + +extension Status: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Status.bridgeJSMakeTypeHandle() +} + #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_checkArray") fileprivate func bjs_checkArray_extern(_ a: Int32) -> Void diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift index f2223ee7c..e4efe4596 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift @@ -335,6 +335,18 @@ public func _bjs_asyncRoundTripEnumDictionary() -> Int32 { #endif } +extension AsyncPoint: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = AsyncPoint.bridgeJSMakeTypeHandle() +} + +extension AsyncDirection: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = AsyncDirection.bridgeJSMakeTypeHandle() +} + +extension AsyncTheme: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = AsyncTheme.bridgeJSMakeTypeHandle() +} + @JSFunction func Promise_reject(_ promise: JSObject, _ value: JSValue) throws(JSException) #if arch(wasm32) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncAssociatedValueEnum.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncAssociatedValueEnum.swift index 3208eda33..5e56f12ad 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncAssociatedValueEnum.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncAssociatedValueEnum.swift @@ -52,6 +52,10 @@ public func _bjs_asyncRoundTripOptionalAssociatedValueEnum(_ valueIsSome: Int32, #endif } +extension AsyncPayloadResult: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = AsyncPayloadResult.bridgeJSMakeTypeHandle() +} + @JSFunction func Promise_reject(_ promise: JSObject, _ value: JSValue) throws(JSException) #if arch(wasm32) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ClassWithNestedTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ClassWithNestedTypes.swift index 52c633045..62511b41c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ClassWithNestedTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ClassWithNestedTypes.swift @@ -174,4 +174,12 @@ fileprivate func _bjs_Account_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> #endif @inline(never) fileprivate func _bjs_Account_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { return _bjs_Account_wrap_extern(pointer) +} + +extension Account.Credentials: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Account.Credentials.bridgeJSMakeTypeHandle() +} + +extension Account.Role: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Account.Role.bridgeJSMakeTypeHandle() } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.swift index 507827646..cca403b68 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.swift @@ -636,4 +636,16 @@ fileprivate func _bjs_ConstructorDefaults_wrap_extern(_ pointer: UnsafeMutableRa #endif @inline(never) fileprivate func _bjs_ConstructorDefaults_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { return _bjs_ConstructorDefaults_wrap_extern(pointer) +} + +extension Config: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Config.bridgeJSMakeTypeHandle() +} + +extension MathOperations: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = MathOperations.bridgeJSMakeTypeHandle() +} + +extension Status: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Status.bridgeJSMakeTypeHandle() } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.swift index 26a4c087e..d57ec170c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.swift @@ -149,6 +149,10 @@ fileprivate func _bjs_Box_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int return _bjs_Box_wrap_extern(pointer) } +extension Counters: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Counters.bridgeJSMakeTypeHandle() +} + #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_importMirrorDictionary") fileprivate func bjs_importMirrorDictionary_extern() -> Void diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DocComments.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DocComments.swift index f91df6c26..042771659 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DocComments.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DocComments.swift @@ -314,4 +314,12 @@ fileprivate func _bjs_Greeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> #endif @inline(never) fileprivate func _bjs_Greeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { return _bjs_Greeter_wrap_extern(pointer) +} + +extension Point: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Point.bridgeJSMakeTypeHandle() +} + +extension Color: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Color.bridgeJSMakeTypeHandle() } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAlias.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAlias.json index 0d63db899..c876db410 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAlias.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAlias.json @@ -31,6 +31,7 @@ } ] }, + "isFinal" : true, "methods" : [ ], diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAlias.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAlias.swift index 1e74a127b..6db98303e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAlias.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAlias.swift @@ -51,4 +51,8 @@ fileprivate func _bjs_ColorBox_wrap_extern(_ pointer: UnsafeMutableRawPointer) - return _bjs_ColorBox_wrap_extern(pointer) } +extension ColorBox: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = ColorBox.bridgeJSMakeTypeHandle() +} + extension Color: _BridgedSwiftAlias, _BridgedSwiftStackType {} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.swift index 6d5549699..0fa414bfe 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.swift @@ -631,4 +631,48 @@ fileprivate func _bjs_User_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> In #endif @inline(never) fileprivate func _bjs_User_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { return _bjs_User_wrap_extern(pointer) +} + +extension Point: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Point.bridgeJSMakeTypeHandle() +} + +extension APIResult: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = APIResult.bridgeJSMakeTypeHandle() +} + +extension ComplexResult: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = ComplexResult.bridgeJSMakeTypeHandle() +} + +extension Utilities.Result: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Utilities.Result.bridgeJSMakeTypeHandle() +} + +extension NetworkingResult: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = NetworkingResult.bridgeJSMakeTypeHandle() +} + +extension APIOptionalResult: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = APIOptionalResult.bridgeJSMakeTypeHandle() +} + +extension Precision: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Precision.bridgeJSMakeTypeHandle() +} + +extension CardinalDirection: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = CardinalDirection.bridgeJSMakeTypeHandle() +} + +extension TypedPayloadResult: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = TypedPayloadResult.bridgeJSMakeTypeHandle() +} + +extension AllTypesResult: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = AllTypesResult.bridgeJSMakeTypeHandle() +} + +extension OptionalAllTypesResult: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = OptionalAllTypesResult.bridgeJSMakeTypeHandle() } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValueImport.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValueImport.swift index 55d1992a3..fcf201eb8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValueImport.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValueImport.swift @@ -26,6 +26,10 @@ extension PayloadSignal: _BridgedSwiftAssociatedValueEnum { } } +extension PayloadSignal: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = PayloadSignal.bridgeJSMakeTypeHandle() +} + #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_PayloadSignalControls_roundTrip_static") fileprivate func bjs_PayloadSignalControls_roundTrip_static_extern(_ signal: Int32) -> Int32 diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCase.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCase.swift index 66692ee14..a3f1f62dd 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCase.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCase.swift @@ -227,4 +227,20 @@ public func _bjs_roundTripOptionalTSDirection(_ inputIsSome: Int32, _ inputValue #else fatalError("Only available on WebAssembly") #endif +} + +extension Direction: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Direction.bridgeJSMakeTypeHandle() +} + +extension Status: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Status.bridgeJSMakeTypeHandle() +} + +extension TSDirection: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = TSDirection.bridgeJSMakeTypeHandle() +} + +extension PublicStatus: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = PublicStatus.bridgeJSMakeTypeHandle() } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCaseImport.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCaseImport.swift index f297e1620..adef86c78 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCaseImport.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCaseImport.swift @@ -33,6 +33,10 @@ extension Signal: _BridgedSwiftCaseEnum { } } +extension Signal: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Signal.bridgeJSMakeTypeHandle() +} + #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_SignalControls_roundTrip_static") fileprivate func bjs_SignalControls_roundTrip_static_extern(_ signal: Int32) -> Int32 diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift index 4f588f6c7..9b2fda572 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift @@ -358,4 +358,20 @@ fileprivate func _bjs_Formatting_Converter_wrap_extern(_ pointer: UnsafeMutableR #endif @inline(never) fileprivate func _bjs_Formatting_Converter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { return _bjs_Formatting_Converter_wrap_extern(pointer) +} + +extension Networking.API.Method: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Networking.API.Method.bridgeJSMakeTypeHandle() +} + +extension Configuration.LogLevel: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Configuration.LogLevel.bridgeJSMakeTypeHandle() +} + +extension Configuration.Port: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Configuration.Port.bridgeJSMakeTypeHandle() +} + +extension Internal.SupportedMethod: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Internal.SupportedMethod.bridgeJSMakeTypeHandle() } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift index 4f588f6c7..9b2fda572 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift @@ -358,4 +358,20 @@ fileprivate func _bjs_Formatting_Converter_wrap_extern(_ pointer: UnsafeMutableR #endif @inline(never) fileprivate func _bjs_Formatting_Converter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { return _bjs_Formatting_Converter_wrap_extern(pointer) +} + +extension Networking.API.Method: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Networking.API.Method.bridgeJSMakeTypeHandle() +} + +extension Configuration.LogLevel: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Configuration.LogLevel.bridgeJSMakeTypeHandle() +} + +extension Configuration.Port: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Configuration.Port.bridgeJSMakeTypeHandle() +} + +extension Internal.SupportedMethod: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Internal.SupportedMethod.bridgeJSMakeTypeHandle() } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.swift index e70a6b0aa..72f481c2d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.swift @@ -451,6 +451,54 @@ public func _bjs_validateSession(_ session: Int64) -> Void { #endif } +extension Theme: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Theme.bridgeJSMakeTypeHandle() +} + +extension TSTheme: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = TSTheme.bridgeJSMakeTypeHandle() +} + +extension FeatureFlag: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = FeatureFlag.bridgeJSMakeTypeHandle() +} + +extension HttpStatus: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = HttpStatus.bridgeJSMakeTypeHandle() +} + +extension TSHttpStatus: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = TSHttpStatus.bridgeJSMakeTypeHandle() +} + +extension Priority: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Priority.bridgeJSMakeTypeHandle() +} + +extension FileSize: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = FileSize.bridgeJSMakeTypeHandle() +} + +extension UserId: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = UserId.bridgeJSMakeTypeHandle() +} + +extension TokenId: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = TokenId.bridgeJSMakeTypeHandle() +} + +extension SessionId: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = SessionId.bridgeJSMakeTypeHandle() +} + +extension Precision: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Precision.bridgeJSMakeTypeHandle() +} + +extension Ratio: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Ratio.bridgeJSMakeTypeHandle() +} + #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_takesFeatureFlag") fileprivate func bjs_takesFeatureFlag_extern(_ flagBytes: Int32, _ flagLength: Int32) -> Void diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.swift index 62f9a3b68..0e36253b7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.swift @@ -104,6 +104,10 @@ public func _bjs_roundtripFooContainer() -> Void { #endif } +extension FooContainer: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = FooContainer.bridgeJSMakeTypeHandle() +} + #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_Foo_init") fileprivate func bjs_Foo_init_extern() -> Int32 diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSNameOverride.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSNameOverride.swift index b525b5152..745843e34 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSNameOverride.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSNameOverride.swift @@ -348,4 +348,12 @@ fileprivate func _bjs_RenamedMembers_wrap_extern(_ pointer: UnsafeMutableRawPoin #endif @inline(never) fileprivate func _bjs_RenamedMembers_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { return _bjs_RenamedMembers_wrap_extern(pointer) +} + +extension RenamedVector: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = RenamedVector.bridgeJSMakeTypeHandle() +} + +extension RenamedEnumMembers: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = RenamedEnumMembers.bridgeJSMakeTypeHandle() } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedType.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedType.swift index ed1a080e9..bc910951f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedType.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedType.swift @@ -176,4 +176,12 @@ fileprivate func _bjs_Player_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> #endif @inline(never) fileprivate func _bjs_Player_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { return _bjs_Player_wrap_extern(pointer) +} + +extension User.Stats: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = User.Stats.bridgeJSMakeTypeHandle() +} + +extension Player.Stats: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Player.Stats.bridgeJSMakeTypeHandle() } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift index cfda92ac0..a92716d44 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift @@ -1043,4 +1043,20 @@ fileprivate func _bjs_DelegateManager_wrap_extern(_ pointer: UnsafeMutableRawPoi #endif @inline(never) fileprivate func _bjs_DelegateManager_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { return _bjs_DelegateManager_wrap_extern(pointer) +} + +extension Direction: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Direction.bridgeJSMakeTypeHandle() +} + +extension ExampleEnum: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = ExampleEnum.bridgeJSMakeTypeHandle() +} + +extension Result: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Result.bridgeJSMakeTypeHandle() +} + +extension Priority: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Priority.bridgeJSMakeTypeHandle() } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift index 896258915..1f33a0b1d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift @@ -207,4 +207,12 @@ fileprivate func _bjs_MathUtils_wrap_extern(_ pointer: UnsafeMutableRawPointer) #endif @inline(never) fileprivate func _bjs_MathUtils_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { return _bjs_MathUtils_wrap_extern(pointer) +} + +extension Calculator: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Calculator.bridgeJSMakeTypeHandle() +} + +extension APIResult: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = APIResult.bridgeJSMakeTypeHandle() } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift index 896258915..1f33a0b1d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift @@ -207,4 +207,12 @@ fileprivate func _bjs_MathUtils_wrap_extern(_ pointer: UnsafeMutableRawPointer) #endif @inline(never) fileprivate func _bjs_MathUtils_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { return _bjs_MathUtils_wrap_extern(pointer) +} + +extension Calculator: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Calculator.bridgeJSMakeTypeHandle() +} + +extension APIResult: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = APIResult.bridgeJSMakeTypeHandle() } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.swift index ded55dbd4..2c6aa9add 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.swift @@ -338,4 +338,8 @@ fileprivate func _bjs_PropertyClass_wrap_extern(_ pointer: UnsafeMutableRawPoint #endif @inline(never) fileprivate func _bjs_PropertyClass_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { return _bjs_PropertyClass_wrap_extern(pointer) +} + +extension PropertyEnum: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = PropertyEnum.bridgeJSMakeTypeHandle() } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.swift index ded55dbd4..2c6aa9add 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.swift @@ -338,4 +338,8 @@ fileprivate func _bjs_PropertyClass_wrap_extern(_ pointer: UnsafeMutableRawPoint #endif @inline(never) fileprivate func _bjs_PropertyClass_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { return _bjs_PropertyClass_wrap_extern(pointer) +} + +extension PropertyEnum: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = PropertyEnum.bridgeJSMakeTypeHandle() } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StructWithNestedTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StructWithNestedTypes.swift index ad99f0a03..b557b423f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StructWithNestedTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StructWithNestedTypes.swift @@ -246,4 +246,32 @@ public func _bjs_Widget_Bounds_static_zero() -> Void { #else fatalError("Only available on WebAssembly") #endif +} + +extension Shape: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Shape.bridgeJSMakeTypeHandle() +} + +extension Widget: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Widget.bridgeJSMakeTypeHandle() +} + +extension Widget.Layout: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Widget.Layout.bridgeJSMakeTypeHandle() +} + +extension Widget.Bounds: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Widget.Bounds.bridgeJSMakeTypeHandle() +} + +extension Shape.Kind: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Shape.Kind.bridgeJSMakeTypeHandle() +} + +extension Widget.Variant: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Widget.Variant.bridgeJSMakeTypeHandle() +} + +extension Widget.Layout.Alignment: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Widget.Layout.Alignment.bridgeJSMakeTypeHandle() } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift index c7ac02fb1..cde864d3c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift @@ -2637,6 +2637,26 @@ fileprivate func _bjs_TestProcessor_wrap_extern(_ pointer: UnsafeMutableRawPoint return _bjs_TestProcessor_wrap_extern(pointer) } +extension Animal: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Animal.bridgeJSMakeTypeHandle() +} + +extension Direction: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Direction.bridgeJSMakeTypeHandle() +} + +extension Theme: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Theme.bridgeJSMakeTypeHandle() +} + +extension HttpStatus: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = HttpStatus.bridgeJSMakeTypeHandle() +} + +extension APIResult: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = APIResult.bridgeJSMakeTypeHandle() +} + @JSFunction func Promise_reject(_ promise: JSObject, _ value: JSValue) throws(JSException) #if arch(wasm32) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift index f98038b45..3414b158d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift @@ -630,4 +630,40 @@ fileprivate func _bjs_Greeter_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> #endif @inline(never) fileprivate func _bjs_Greeter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { return _bjs_Greeter_wrap_extern(pointer) +} + +extension DataPoint: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = DataPoint.bridgeJSMakeTypeHandle() +} + +extension Address: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Address.bridgeJSMakeTypeHandle() +} + +extension Person: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Person.bridgeJSMakeTypeHandle() +} + +extension Session: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Session.bridgeJSMakeTypeHandle() +} + +extension Measurement: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Measurement.bridgeJSMakeTypeHandle() +} + +extension ConfigStruct: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = ConfigStruct.bridgeJSMakeTypeHandle() +} + +extension Container: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Container.bridgeJSMakeTypeHandle() +} + +extension Vector2D: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Vector2D.bridgeJSMakeTypeHandle() +} + +extension Precision: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Precision.bridgeJSMakeTypeHandle() } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.swift index 38ec94c0d..2eb0e70b7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.swift @@ -46,6 +46,10 @@ fileprivate func _bjs_struct_lift_Point_extern() -> Int32 { return _bjs_struct_lift_Point_extern() } +extension Point: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Point.bridgeJSMakeTypeHandle() +} + #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_translate") fileprivate func bjs_translate_extern(_ dx: Int32, _ dy: Int32) -> Void diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/UnsafePointer.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/UnsafePointer.swift index b97729084..93abd19e8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/UnsafePointer.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/UnsafePointer.swift @@ -177,4 +177,8 @@ public func _bjs_roundTripPointerFields() -> Void { #else fatalError("Only available on WebAssembly") #endif +} + +extension PointerFields: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = PointerFields.bridgeJSMakeTypeHandle() } \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.d.ts index e3092afb3..9815b6514 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.d.ts @@ -67,5 +67,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js index 92fb5a109..d8a23090a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js @@ -37,6 +37,316 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + function __bjs_arrayCodec(elementCodec) { + return { + lower(value) { + for (let i = 0; i < value.length; i++) { + elementCodec.lower(value[i]); + } + i32Stack.push(value.length); + }, + lift() { + const count = i32Stack.pop(); + if (count === -1) { + return taStack.pop(); + } + const result = new Array(count); + for (let i = count - 1; i >= 0; i--) { + result[i] = elementCodec.lift(); + } + return result; + }, + }; + } + function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { + return { + lower(value) { + const isSome = isUndefinedOr ? value !== undefined : value != null; + if (isSome) { + elementCodec.lower(value); + i32Stack.push(1); + } else { + i32Stack.push(0); + } + }, + lift() { + if (i32Stack.pop() === 0) { + return isUndefinedOr ? undefined : null; + } + return elementCodec.lift(); + }, + }; + } + function __bjs_dictCodec(valueCodec) { + return { + lower(value) { + const keys = Object.keys(value); + for (let i = 0; i < keys.length; i++) { + __bjs_stringCodec.lower(keys[i]); + valueCodec.lower(value[keys[i]]); + } + i32Stack.push(keys.length); + }, + lift() { + const count = i32Stack.pop(); + const result = {}; + for (let i = 0; i < count; i++) { + const value = valueCodec.lift(); + const key = __bjs_stringCodec.lift(); + result[key] = value; + } + return result; + }, + }; + } + function __bjs_enumCodec(helper) { + return { + lower(value) { + i32Stack.push(helper.lower(value)); + }, + lift() { + return helper.lift(i32Stack.pop()); + }, + }; + } + + const __bjs_stringCodec = { + lower: (v) => { + const bytes = textEncoder.encode(v); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + }, + lift: () => { + const string = strStack.pop(); + return string; + }, + }; + const __bjs_primitiveCodecs = { + Bool: { + lower: (v) => { + i32Stack.push(v ? 1 : 0); + }, + lift: () => { + const bool = i32Stack.pop() !== 0; + return bool; + }, + }, + Int: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + Int8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + UInt: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + UInt64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + Float: { + lower: (v) => { + f32Stack.push(Math.fround(v)); + }, + lift: () => { + const f32 = f32Stack.pop(); + return f32; + }, + }, + Double: { + lower: (v) => { + f64Stack.push(v); + }, + lift: () => { + const f64 = f64Stack.pop(); + return f64; + }, + }, + String: __bjs_stringCodec, + JSValue: { + lower: (v) => { + const [vKind, vPayload1, vPayload2] = __bjs_jsValueLower(v); + i32Stack.push(vKind); + i32Stack.push(vPayload1); + f64Stack.push(vPayload2); + }, + lift: () => { + const jsValuePayload2 = f64Stack.pop(); + const jsValuePayload1 = i32Stack.pop(); + const jsValueKind = i32Stack.pop(); + const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + return jsValue; + }, + }, + }; + + function __bjs_jsValueLower(value) { + let kind; + let payload1; + let payload2; + if (value === null) { + kind = 4; + payload1 = 0; + payload2 = 0; + } else { + switch (typeof value) { + case "boolean": + kind = 0; + payload1 = value ? 1 : 0; + payload2 = 0; + break; + case "number": + kind = 2; + payload1 = 0; + payload2 = value; + break; + case "string": + kind = 1; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "undefined": + kind = 5; + payload1 = 0; + payload2 = 0; + break; + case "object": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "function": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "symbol": + kind = 7; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "bigint": + kind = 8; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + default: + throw new TypeError("Unsupported JSValue type"); + } + } + return [kind, payload1, payload2]; + } + function __bjs_jsValueLift(kind, payload1, payload2) { + let jsValue; + switch (kind) { + case 0: + jsValue = payload1 !== 0; + break; + case 1: + jsValue = swift.memory.getObject(payload1); + break; + case 2: + jsValue = payload2; + break; + case 3: + jsValue = swift.memory.getObject(payload1); + break; + case 4: + jsValue = null; + break; + case 5: + jsValue = undefined; + break; + case 7: + jsValue = swift.memory.getObject(payload1); + break; + case 8: + jsValue = swift.memory.getObject(payload1); + break; + default: + throw new TypeError("Unsupported JSValue kind " + kind); + } + return jsValue; + } + const __bjs_createInnerTagValuesHelpers = () => ({ lower: (value) => { const enumTag = value.tag; @@ -139,6 +449,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; @@ -284,12 +595,19 @@ export async function createInstantiator(options, swift) { TestModule["bjs_produceOptionalCanvas"] = function bjs_produceOptionalCanvas() { try { let ret = imports.produceOptionalCanvas(); - const isSome = ret != null; - if (isSome) { - const objId = swift.memory.retain(ret); - i32Stack.push(objId); - } - i32Stack.push(isSome ? 1 : 0); + const elemCodec = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + __bjs_optionalCodec(elemCodec).lower(ret); } catch (error) { setException(error); } @@ -440,24 +758,29 @@ export async function createInstantiator(options, swift) { return optResult; }, polygonArray: function bjs_polygonArray(polygons) { - for (const elem of polygons) { - ptrStack.push(elem.pointer); - } - i32Stack.push(polygons.length); + const elemCodec = { + lower: (v) => { + ptrStack.push(v.pointer); + }, + lift: () => { + const ptr = ptrStack.pop(); + const obj = PolygonReference.__construct(ptr); + return obj; + }, + }; + __bjs_arrayCodec(elemCodec).lower(polygons); instance.exports.bjs_polygonArray(); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { + const elemCodec1 = { + lower: (v) => { + ptrStack.push(v.pointer); + }, + lift: () => { const ptr = ptrStack.pop(); const obj = PolygonReference.__construct(ptr); - arrayResult.push(obj); - } - arrayResult.reverse(); - } + return obj; + }, + }; + const arrayResult = __bjs_arrayCodec(elemCodec1).lift(); return arrayResult; }, validatePolygon: function bjs_validatePolygon(polygon) { @@ -477,35 +800,9 @@ export async function createInstantiator(options, swift) { return TagReference.__construct(ret); }, roundtripTags: function bjs_roundtripTags(xs) { - for (const elem of xs) { - const isSome = elem != null ? 1 : 0; - if (isSome) { - const caseId = enumHelpers.InnerTag.lower(elem); - i32Stack.push(caseId); - } - i32Stack.push(isSome); - } - i32Stack.push(xs.length); + __bjs_arrayCodec(__bjs_optionalCodec(__bjs_enumCodec(enumHelpers.InnerTag))).lower(xs); instance.exports.bjs_roundtripTags(); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const isSome1 = i32Stack.pop(); - let optValue; - if (isSome1 === 0) { - optValue = null; - } else { - const enumValue = enumHelpers.InnerTag.lift(i32Stack.pop()); - optValue = enumValue; - } - arrayResult.push(optValue); - } - arrayResult.reverse(); - } + const arrayResult = __bjs_arrayCodec(__bjs_optionalCodec(__bjs_enumCodec(enumHelpers.InnerTag))).lift(); return arrayResult; }, describeUser: function bjs_describeUser(owner) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.d.ts index 73ea3b570..4d2bab311 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.d.ts @@ -27,5 +27,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js index a38fa118e..cb130421b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js @@ -131,6 +131,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.d.ts index f48189956..529b16095 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.d.ts @@ -91,5 +91,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js index 419cf15d5..39c0507c1 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js @@ -44,6 +44,316 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + function __bjs_arrayCodec(elementCodec) { + return { + lower(value) { + for (let i = 0; i < value.length; i++) { + elementCodec.lower(value[i]); + } + i32Stack.push(value.length); + }, + lift() { + const count = i32Stack.pop(); + if (count === -1) { + return taStack.pop(); + } + const result = new Array(count); + for (let i = count - 1; i >= 0; i--) { + result[i] = elementCodec.lift(); + } + return result; + }, + }; + } + function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { + return { + lower(value) { + const isSome = isUndefinedOr ? value !== undefined : value != null; + if (isSome) { + elementCodec.lower(value); + i32Stack.push(1); + } else { + i32Stack.push(0); + } + }, + lift() { + if (i32Stack.pop() === 0) { + return isUndefinedOr ? undefined : null; + } + return elementCodec.lift(); + }, + }; + } + function __bjs_dictCodec(valueCodec) { + return { + lower(value) { + const keys = Object.keys(value); + for (let i = 0; i < keys.length; i++) { + __bjs_stringCodec.lower(keys[i]); + valueCodec.lower(value[keys[i]]); + } + i32Stack.push(keys.length); + }, + lift() { + const count = i32Stack.pop(); + const result = {}; + for (let i = 0; i < count; i++) { + const value = valueCodec.lift(); + const key = __bjs_stringCodec.lift(); + result[key] = value; + } + return result; + }, + }; + } + function __bjs_enumCodec(helper) { + return { + lower(value) { + i32Stack.push(helper.lower(value)); + }, + lift() { + return helper.lift(i32Stack.pop()); + }, + }; + } + + const __bjs_stringCodec = { + lower: (v) => { + const bytes = textEncoder.encode(v); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + }, + lift: () => { + const string = strStack.pop(); + return string; + }, + }; + const __bjs_primitiveCodecs = { + Bool: { + lower: (v) => { + i32Stack.push(v ? 1 : 0); + }, + lift: () => { + const bool = i32Stack.pop() !== 0; + return bool; + }, + }, + Int: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + Int8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + UInt: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + UInt64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + Float: { + lower: (v) => { + f32Stack.push(Math.fround(v)); + }, + lift: () => { + const f32 = f32Stack.pop(); + return f32; + }, + }, + Double: { + lower: (v) => { + f64Stack.push(v); + }, + lift: () => { + const f64 = f64Stack.pop(); + return f64; + }, + }, + String: __bjs_stringCodec, + JSValue: { + lower: (v) => { + const [vKind, vPayload1, vPayload2] = __bjs_jsValueLower(v); + i32Stack.push(vKind); + i32Stack.push(vPayload1); + f64Stack.push(vPayload2); + }, + lift: () => { + const jsValuePayload2 = f64Stack.pop(); + const jsValuePayload1 = i32Stack.pop(); + const jsValueKind = i32Stack.pop(); + const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + return jsValue; + }, + }, + }; + + function __bjs_jsValueLower(value) { + let kind; + let payload1; + let payload2; + if (value === null) { + kind = 4; + payload1 = 0; + payload2 = 0; + } else { + switch (typeof value) { + case "boolean": + kind = 0; + payload1 = value ? 1 : 0; + payload2 = 0; + break; + case "number": + kind = 2; + payload1 = 0; + payload2 = value; + break; + case "string": + kind = 1; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "undefined": + kind = 5; + payload1 = 0; + payload2 = 0; + break; + case "object": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "function": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "symbol": + kind = 7; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "bigint": + kind = 8; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + default: + throw new TypeError("Unsupported JSValue type"); + } + } + return [kind, payload1, payload2]; + } + function __bjs_jsValueLift(kind, payload1, payload2) { + let jsValue; + switch (kind) { + case 0: + jsValue = payload1 !== 0; + break; + case 1: + jsValue = swift.memory.getObject(payload1); + break; + case 2: + jsValue = payload2; + break; + case 3: + jsValue = swift.memory.getObject(payload1); + break; + case 4: + jsValue = null; + break; + case 5: + jsValue = undefined; + break; + case 7: + jsValue = swift.memory.getObject(payload1); + break; + case 8: + jsValue = swift.memory.getObject(payload1); + break; + default: + throw new TypeError("Unsupported JSValue kind " + kind); + } + return jsValue; + } + const __bjs_createPointHelpers = () => ({ lower: (value) => { f64Stack.push(value.x); @@ -138,6 +448,7 @@ export async function createInstantiator(options, swift) { const value = structHelpers.Point.lift(); return swift.memory.retain(value); } + bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; @@ -264,18 +575,7 @@ export async function createInstantiator(options, swift) { } TestModule["bjs_importProcessNumbers"] = function bjs_importProcessNumbers() { try { - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const f64 = f64Stack.pop(); - arrayResult.push(f64); - } - arrayResult.reverse(); - } + const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.Double).lift(); imports.importProcessNumbers(arrayResult); } catch (error) { setException(error); @@ -284,82 +584,34 @@ export async function createInstantiator(options, swift) { TestModule["bjs_importGetNumbers"] = function bjs_importGetNumbers() { try { let ret = imports.importGetNumbers(); - for (const elem of ret) { - f64Stack.push(elem); - } - i32Stack.push(ret.length); + __bjs_arrayCodec(__bjs_primitiveCodecs.Double).lower(ret); } catch (error) { setException(error); } } TestModule["bjs_importTransformNumbers"] = function bjs_importTransformNumbers() { try { - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const f64 = f64Stack.pop(); - arrayResult.push(f64); - } - arrayResult.reverse(); - } + const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.Double).lift(); let ret = imports.importTransformNumbers(arrayResult); - for (const elem of ret) { - f64Stack.push(elem); - } - i32Stack.push(ret.length); + __bjs_arrayCodec(__bjs_primitiveCodecs.Double).lower(ret); } catch (error) { setException(error); } } TestModule["bjs_importProcessStrings"] = function bjs_importProcessStrings() { try { - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const string = strStack.pop(); - arrayResult.push(string); - } - arrayResult.reverse(); - } + const arrayResult = __bjs_arrayCodec(__bjs_stringCodec).lift(); let ret = imports.importProcessStrings(arrayResult); - for (const elem of ret) { - const bytes = textEncoder.encode(elem); - const id = swift.memory.retain(bytes); - i32Stack.push(bytes.length); - i32Stack.push(id); - } - i32Stack.push(ret.length); + __bjs_arrayCodec(__bjs_stringCodec).lower(ret); } catch (error) { setException(error); } } TestModule["bjs_importProcessBooleans"] = function bjs_importProcessBooleans() { try { - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const bool = i32Stack.pop() !== 0; - arrayResult.push(bool); - } - arrayResult.reverse(); - } + const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.Bool).lift(); let ret = imports.importProcessBooleans(arrayResult); - for (const elem of ret) { - i32Stack.push(elem ? 1 : 0); - } - i32Stack.push(ret.length); + __bjs_arrayCodec(__bjs_primitiveCodecs.Bool).lower(ret); } catch (error) { setException(error); } @@ -442,50 +694,19 @@ export async function createInstantiator(options, swift) { } constructor(nums, strs) { - for (const elem of nums) { - i32Stack.push((elem | 0)); - } - i32Stack.push(nums.length); - for (const elem1 of strs) { - const bytes = textEncoder.encode(elem1); - const id = swift.memory.retain(bytes); - i32Stack.push(bytes.length); - i32Stack.push(id); - } - i32Stack.push(strs.length); + __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lower(nums); + __bjs_arrayCodec(__bjs_stringCodec).lower(strs); const ret = instance.exports.bjs_MultiArrayContainer_init(); return MultiArrayContainer.__construct(ret); } get numbers() { instance.exports.bjs_MultiArrayContainer_numbers_get(this.pointer); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const int = i32Stack.pop(); - arrayResult.push(int); - } - arrayResult.reverse(); - } + const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lift(); return arrayResult; } get strings() { instance.exports.bjs_MultiArrayContainer_strings_get(this.pointer); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const string = strStack.pop(); - arrayResult.push(string); - } - arrayResult.reverse(); - } + const arrayResult = __bjs_arrayCodec(__bjs_stringCodec).lift(); return arrayResult; } } @@ -494,161 +715,90 @@ export async function createInstantiator(options, swift) { const exports = { processIntArray: function bjs_processIntArray(values) { - for (const elem of values) { - i32Stack.push((elem | 0)); - } - i32Stack.push(values.length); + __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lower(values); instance.exports.bjs_processIntArray(); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const int = i32Stack.pop(); - arrayResult.push(int); - } - arrayResult.reverse(); - } + const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lift(); return arrayResult; }, processStringArray: function bjs_processStringArray(values) { - for (const elem of values) { - const bytes = textEncoder.encode(elem); - const id = swift.memory.retain(bytes); - i32Stack.push(bytes.length); - i32Stack.push(id); - } - i32Stack.push(values.length); + __bjs_arrayCodec(__bjs_stringCodec).lower(values); instance.exports.bjs_processStringArray(); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const string = strStack.pop(); - arrayResult.push(string); - } - arrayResult.reverse(); - } + const arrayResult = __bjs_arrayCodec(__bjs_stringCodec).lift(); return arrayResult; }, processDoubleArray: function bjs_processDoubleArray(values) { - for (const elem of values) { - f64Stack.push(elem); - } - i32Stack.push(values.length); + __bjs_arrayCodec(__bjs_primitiveCodecs.Double).lower(values); instance.exports.bjs_processDoubleArray(); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const f64 = f64Stack.pop(); - arrayResult.push(f64); - } - arrayResult.reverse(); - } + const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.Double).lift(); return arrayResult; }, processBoolArray: function bjs_processBoolArray(values) { - for (const elem of values) { - i32Stack.push(elem ? 1 : 0); - } - i32Stack.push(values.length); + __bjs_arrayCodec(__bjs_primitiveCodecs.Bool).lower(values); instance.exports.bjs_processBoolArray(); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const bool = i32Stack.pop() !== 0; - arrayResult.push(bool); - } - arrayResult.reverse(); - } + const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.Bool).lift(); return arrayResult; }, processPointArray: function bjs_processPointArray(points) { - for (const elem of points) { - structHelpers.Point.lower(elem); - } - i32Stack.push(points.length); + __bjs_arrayCodec(structHelpers.Point).lower(points); instance.exports.bjs_processPointArray(); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const struct = structHelpers.Point.lift(); - arrayResult.push(struct); - } - arrayResult.reverse(); - } + const arrayResult = __bjs_arrayCodec(structHelpers.Point).lift(); return arrayResult; }, processDirectionArray: function bjs_processDirectionArray(directions) { - for (const elem of directions) { - i32Stack.push((elem | 0)); - } - i32Stack.push(directions.length); + const elemCodec = { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const caseId = i32Stack.pop(); + return caseId; + }, + }; + __bjs_arrayCodec(elemCodec).lower(directions); instance.exports.bjs_processDirectionArray(); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { + const elemCodec1 = { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { const caseId = i32Stack.pop(); - arrayResult.push(caseId); - } - arrayResult.reverse(); - } + return caseId; + }, + }; + const arrayResult = __bjs_arrayCodec(elemCodec1).lift(); return arrayResult; }, processStatusArray: function bjs_processStatusArray(statuses) { - for (const elem of statuses) { - i32Stack.push((elem | 0)); - } - i32Stack.push(statuses.length); + const elemCodec = { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const rawValue = i32Stack.pop(); + return rawValue; + }, + }; + __bjs_arrayCodec(elemCodec).lower(statuses); instance.exports.bjs_processStatusArray(); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { + const elemCodec1 = { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { const rawValue = i32Stack.pop(); - arrayResult.push(rawValue); - } - arrayResult.reverse(); - } + return rawValue; + }, + }; + const arrayResult = __bjs_arrayCodec(elemCodec1).lift(); return arrayResult; }, sumIntArray: function bjs_sumIntArray(values) { - for (const elem of values) { - i32Stack.push((elem | 0)); - } - i32Stack.push(values.length); + __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lower(values); const ret = instance.exports.bjs_sumIntArray(); return ret; }, findFirstPoint: function bjs_findFirstPoint(points, matching) { - for (const elem of points) { - structHelpers.Point.lower(elem); - } - i32Stack.push(points.length); + __bjs_arrayCodec(structHelpers.Point).lower(points); const matchingBytes = textEncoder.encode(matching); const matchingId = swift.memory.retain(matchingBytes); instance.exports.bjs_findFirstPoint(matchingId, matchingBytes.length); @@ -656,544 +806,318 @@ export async function createInstantiator(options, swift) { return structValue; }, processUnsafeRawPointerArray: function bjs_processUnsafeRawPointerArray(values) { - for (const elem of values) { - ptrStack.push((elem | 0)); - } - i32Stack.push(values.length); + const elemCodec = { + lower: (v) => { + ptrStack.push((v | 0)); + }, + lift: () => { + const pointer = ptrStack.pop(); + return pointer; + }, + }; + __bjs_arrayCodec(elemCodec).lower(values); instance.exports.bjs_processUnsafeRawPointerArray(); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { + const elemCodec1 = { + lower: (v) => { + ptrStack.push((v | 0)); + }, + lift: () => { const pointer = ptrStack.pop(); - arrayResult.push(pointer); - } - arrayResult.reverse(); - } + return pointer; + }, + }; + const arrayResult = __bjs_arrayCodec(elemCodec1).lift(); return arrayResult; }, processUnsafeMutableRawPointerArray: function bjs_processUnsafeMutableRawPointerArray(values) { - for (const elem of values) { - ptrStack.push((elem | 0)); - } - i32Stack.push(values.length); + const elemCodec = { + lower: (v) => { + ptrStack.push((v | 0)); + }, + lift: () => { + const pointer = ptrStack.pop(); + return pointer; + }, + }; + __bjs_arrayCodec(elemCodec).lower(values); instance.exports.bjs_processUnsafeMutableRawPointerArray(); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { + const elemCodec1 = { + lower: (v) => { + ptrStack.push((v | 0)); + }, + lift: () => { const pointer = ptrStack.pop(); - arrayResult.push(pointer); - } - arrayResult.reverse(); - } + return pointer; + }, + }; + const arrayResult = __bjs_arrayCodec(elemCodec1).lift(); return arrayResult; }, processOpaquePointerArray: function bjs_processOpaquePointerArray(values) { - for (const elem of values) { - ptrStack.push((elem | 0)); - } - i32Stack.push(values.length); + const elemCodec = { + lower: (v) => { + ptrStack.push((v | 0)); + }, + lift: () => { + const pointer = ptrStack.pop(); + return pointer; + }, + }; + __bjs_arrayCodec(elemCodec).lower(values); instance.exports.bjs_processOpaquePointerArray(); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { + const elemCodec1 = { + lower: (v) => { + ptrStack.push((v | 0)); + }, + lift: () => { const pointer = ptrStack.pop(); - arrayResult.push(pointer); - } - arrayResult.reverse(); - } + return pointer; + }, + }; + const arrayResult = __bjs_arrayCodec(elemCodec1).lift(); return arrayResult; }, processOptionalIntArray: function bjs_processOptionalIntArray(values) { - for (const elem of values) { - const isSome = elem != null ? 1 : 0; - if (isSome) { - i32Stack.push((elem | 0)); - } - i32Stack.push(isSome); - } - i32Stack.push(values.length); + __bjs_arrayCodec(__bjs_optionalCodec(__bjs_primitiveCodecs.Int)).lower(values); instance.exports.bjs_processOptionalIntArray(); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const isSome1 = i32Stack.pop(); - let optValue; - if (isSome1 === 0) { - optValue = null; - } else { - const int = i32Stack.pop(); - optValue = int; - } - arrayResult.push(optValue); - } - arrayResult.reverse(); - } + const arrayResult = __bjs_arrayCodec(__bjs_optionalCodec(__bjs_primitiveCodecs.Int)).lift(); return arrayResult; }, processOptionalStringArray: function bjs_processOptionalStringArray(values) { - for (const elem of values) { - const isSome = elem != null ? 1 : 0; - if (isSome) { - const bytes = textEncoder.encode(elem); - const id = swift.memory.retain(bytes); - i32Stack.push(bytes.length); - i32Stack.push(id); - } - i32Stack.push(isSome); - } - i32Stack.push(values.length); + __bjs_arrayCodec(__bjs_optionalCodec(__bjs_stringCodec)).lower(values); instance.exports.bjs_processOptionalStringArray(); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const isSome1 = i32Stack.pop(); - let optValue; - if (isSome1 === 0) { - optValue = null; - } else { - const string = strStack.pop(); - optValue = string; - } - arrayResult.push(optValue); - } - arrayResult.reverse(); - } + const arrayResult = __bjs_arrayCodec(__bjs_optionalCodec(__bjs_stringCodec)).lift(); return arrayResult; }, processOptionalArray: function bjs_processOptionalArray(values) { - const isSome = values != null; - if (isSome) { - for (const elem of values) { - i32Stack.push((elem | 0)); - } - i32Stack.push(values.length); - } - i32Stack.push(+isSome); + __bjs_optionalCodec(__bjs_arrayCodec(__bjs_primitiveCodecs.Int)).lower(values); instance.exports.bjs_processOptionalArray(); - const isSome1 = i32Stack.pop(); - let optResult; - if (isSome1) { - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const int = i32Stack.pop(); - arrayResult.push(int); - } - arrayResult.reverse(); - } - optResult = arrayResult; - } else { - optResult = null; - } - return optResult; + const optValue = __bjs_optionalCodec(__bjs_arrayCodec(__bjs_primitiveCodecs.Int)).lift(); + return optValue; }, processOptionalPointArray: function bjs_processOptionalPointArray(points) { - for (const elem of points) { - const isSome = elem != null ? 1 : 0; - if (isSome) { - structHelpers.Point.lower(elem); - } - i32Stack.push(isSome); - } - i32Stack.push(points.length); + __bjs_arrayCodec(__bjs_optionalCodec(structHelpers.Point)).lower(points); instance.exports.bjs_processOptionalPointArray(); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const isSome1 = i32Stack.pop(); - let optValue; - if (isSome1 === 0) { - optValue = null; - } else { - const struct = structHelpers.Point.lift(); - optValue = struct; - } - arrayResult.push(optValue); - } - arrayResult.reverse(); - } + const arrayResult = __bjs_arrayCodec(__bjs_optionalCodec(structHelpers.Point)).lift(); return arrayResult; }, processOptionalDirectionArray: function bjs_processOptionalDirectionArray(directions) { - for (const elem of directions) { - const isSome = elem != null ? 1 : 0; - if (isSome) { - i32Stack.push((elem | 0)); - } - i32Stack.push(isSome); - } - i32Stack.push(directions.length); + const elemCodec = { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const caseId = i32Stack.pop(); + return caseId; + }, + }; + __bjs_arrayCodec(__bjs_optionalCodec(elemCodec)).lower(directions); instance.exports.bjs_processOptionalDirectionArray(); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const isSome1 = i32Stack.pop(); - let optValue; - if (isSome1 === 0) { - optValue = null; - } else { - const caseId = i32Stack.pop(); - optValue = caseId; - } - arrayResult.push(optValue); - } - arrayResult.reverse(); - } + const elemCodec1 = { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const caseId = i32Stack.pop(); + return caseId; + }, + }; + const arrayResult = __bjs_arrayCodec(__bjs_optionalCodec(elemCodec1)).lift(); return arrayResult; }, processOptionalStatusArray: function bjs_processOptionalStatusArray(statuses) { - for (const elem of statuses) { - const isSome = elem != null ? 1 : 0; - if (isSome) { - i32Stack.push((elem | 0)); - } - i32Stack.push(isSome); - } - i32Stack.push(statuses.length); + const elemCodec = { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const rawValue = i32Stack.pop(); + return rawValue; + }, + }; + __bjs_arrayCodec(__bjs_optionalCodec(elemCodec)).lower(statuses); instance.exports.bjs_processOptionalStatusArray(); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const isSome1 = i32Stack.pop(); - let optValue; - if (isSome1 === 0) { - optValue = null; - } else { - const rawValue = i32Stack.pop(); - optValue = rawValue; - } - arrayResult.push(optValue); - } - arrayResult.reverse(); - } + const elemCodec1 = { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const rawValue = i32Stack.pop(); + return rawValue; + }, + }; + const arrayResult = __bjs_arrayCodec(__bjs_optionalCodec(elemCodec1)).lift(); return arrayResult; }, processNestedIntArray: function bjs_processNestedIntArray(values) { - for (const elem of values) { - for (const elem1 of elem) { - i32Stack.push((elem1 | 0)); - } - i32Stack.push(elem.length); - } - i32Stack.push(values.length); + __bjs_arrayCodec(__bjs_arrayCodec(__bjs_primitiveCodecs.Int)).lower(values); instance.exports.bjs_processNestedIntArray(); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const arrayLen1 = i32Stack.pop(); - let arrayResult1; - if (arrayLen1 === -1) { - arrayResult1 = taStack.pop(); - } else { - arrayResult1 = []; - for (let i1 = 0; i1 < arrayLen1; i1++) { - const int = i32Stack.pop(); - arrayResult1.push(int); - } - arrayResult1.reverse(); - } - arrayResult.push(arrayResult1); - } - arrayResult.reverse(); - } + const arrayResult = __bjs_arrayCodec(__bjs_arrayCodec(__bjs_primitiveCodecs.Int)).lift(); return arrayResult; }, processNestedStringArray: function bjs_processNestedStringArray(values) { - for (const elem of values) { - for (const elem1 of elem) { - const bytes = textEncoder.encode(elem1); - const id = swift.memory.retain(bytes); - i32Stack.push(bytes.length); - i32Stack.push(id); - } - i32Stack.push(elem.length); - } - i32Stack.push(values.length); + __bjs_arrayCodec(__bjs_arrayCodec(__bjs_stringCodec)).lower(values); instance.exports.bjs_processNestedStringArray(); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const arrayLen1 = i32Stack.pop(); - let arrayResult1; - if (arrayLen1 === -1) { - arrayResult1 = taStack.pop(); - } else { - arrayResult1 = []; - for (let i1 = 0; i1 < arrayLen1; i1++) { - const string = strStack.pop(); - arrayResult1.push(string); - } - arrayResult1.reverse(); - } - arrayResult.push(arrayResult1); - } - arrayResult.reverse(); - } + const arrayResult = __bjs_arrayCodec(__bjs_arrayCodec(__bjs_stringCodec)).lift(); return arrayResult; }, processNestedPointArray: function bjs_processNestedPointArray(points) { - for (const elem of points) { - for (const elem1 of elem) { - structHelpers.Point.lower(elem1); - } - i32Stack.push(elem.length); - } - i32Stack.push(points.length); + __bjs_arrayCodec(__bjs_arrayCodec(structHelpers.Point)).lower(points); instance.exports.bjs_processNestedPointArray(); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const arrayLen1 = i32Stack.pop(); - let arrayResult1; - if (arrayLen1 === -1) { - arrayResult1 = taStack.pop(); - } else { - arrayResult1 = []; - for (let i1 = 0; i1 < arrayLen1; i1++) { - const struct = structHelpers.Point.lift(); - arrayResult1.push(struct); - } - arrayResult1.reverse(); - } - arrayResult.push(arrayResult1); - } - arrayResult.reverse(); - } + const arrayResult = __bjs_arrayCodec(__bjs_arrayCodec(structHelpers.Point)).lift(); return arrayResult; }, processItemArray: function bjs_processItemArray(items) { - for (const elem of items) { - ptrStack.push(elem.pointer); - } - i32Stack.push(items.length); + const elemCodec = { + lower: (v) => { + ptrStack.push(v.pointer); + }, + lift: () => { + const ptr = ptrStack.pop(); + const obj = Item.__construct(ptr); + return obj; + }, + }; + __bjs_arrayCodec(elemCodec).lower(items); instance.exports.bjs_processItemArray(); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { + const elemCodec1 = { + lower: (v) => { + ptrStack.push(v.pointer); + }, + lift: () => { const ptr = ptrStack.pop(); const obj = Item.__construct(ptr); - arrayResult.push(obj); - } - arrayResult.reverse(); - } + return obj; + }, + }; + const arrayResult = __bjs_arrayCodec(elemCodec1).lift(); return arrayResult; }, processNestedItemArray: function bjs_processNestedItemArray(items) { - for (const elem of items) { - for (const elem1 of elem) { - ptrStack.push(elem1.pointer); - } - i32Stack.push(elem.length); - } - i32Stack.push(items.length); + const elemCodec = { + lower: (v) => { + ptrStack.push(v.pointer); + }, + lift: () => { + const ptr = ptrStack.pop(); + const obj = Item.__construct(ptr); + return obj; + }, + }; + __bjs_arrayCodec(__bjs_arrayCodec(elemCodec)).lower(items); instance.exports.bjs_processNestedItemArray(); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const arrayLen1 = i32Stack.pop(); - let arrayResult1; - if (arrayLen1 === -1) { - arrayResult1 = taStack.pop(); - } else { - arrayResult1 = []; - for (let i1 = 0; i1 < arrayLen1; i1++) { - const ptr = ptrStack.pop(); - const obj = Item.__construct(ptr); - arrayResult1.push(obj); - } - arrayResult1.reverse(); - } - arrayResult.push(arrayResult1); - } - arrayResult.reverse(); - } + const elemCodec1 = { + lower: (v) => { + ptrStack.push(v.pointer); + }, + lift: () => { + const ptr = ptrStack.pop(); + const obj = Item.__construct(ptr); + return obj; + }, + }; + const arrayResult = __bjs_arrayCodec(__bjs_arrayCodec(elemCodec1)).lift(); return arrayResult; }, processJSObjectArray: function bjs_processJSObjectArray(objects) { - for (const elem of objects) { - const objId = swift.memory.retain(elem); - i32Stack.push(objId); - } - i32Stack.push(objects.length); + const elemCodec = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + __bjs_arrayCodec(elemCodec).lower(objects); instance.exports.bjs_processJSObjectArray(); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const objId1 = i32Stack.pop(); - const obj = swift.memory.getObject(objId1); - swift.memory.release(objId1); - arrayResult.push(obj); - } - arrayResult.reverse(); - } + const elemCodec1 = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + const arrayResult = __bjs_arrayCodec(elemCodec1).lift(); return arrayResult; }, processOptionalJSObjectArray: function bjs_processOptionalJSObjectArray(objects) { - for (const elem of objects) { - const isSome = elem != null ? 1 : 0; - if (isSome) { - const objId = swift.memory.retain(elem); + const elemCodec = { + lower: (v) => { + const objId = swift.memory.retain(v); i32Stack.push(objId); - } - i32Stack.push(isSome); - } - i32Stack.push(objects.length); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + __bjs_arrayCodec(__bjs_optionalCodec(elemCodec)).lower(objects); instance.exports.bjs_processOptionalJSObjectArray(); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const isSome1 = i32Stack.pop(); - let optValue; - if (isSome1 === 0) { - optValue = null; - } else { - const objId1 = i32Stack.pop(); - const obj = swift.memory.getObject(objId1); - swift.memory.release(objId1); - optValue = obj; - } - arrayResult.push(optValue); - } - arrayResult.reverse(); - } + const elemCodec1 = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + const arrayResult = __bjs_arrayCodec(__bjs_optionalCodec(elemCodec1)).lift(); return arrayResult; }, processNestedJSObjectArray: function bjs_processNestedJSObjectArray(objects) { - for (const elem of objects) { - for (const elem1 of elem) { - const objId = swift.memory.retain(elem1); + const elemCodec = { + lower: (v) => { + const objId = swift.memory.retain(v); i32Stack.push(objId); - } - i32Stack.push(elem.length); - } - i32Stack.push(objects.length); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + __bjs_arrayCodec(__bjs_arrayCodec(elemCodec)).lower(objects); instance.exports.bjs_processNestedJSObjectArray(); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const arrayLen1 = i32Stack.pop(); - let arrayResult1; - if (arrayLen1 === -1) { - arrayResult1 = taStack.pop(); - } else { - arrayResult1 = []; - for (let i1 = 0; i1 < arrayLen1; i1++) { - const objId1 = i32Stack.pop(); - const obj = swift.memory.getObject(objId1); - swift.memory.release(objId1); - arrayResult1.push(obj); - } - arrayResult1.reverse(); - } - arrayResult.push(arrayResult1); - } - arrayResult.reverse(); - } + const elemCodec1 = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + const arrayResult = __bjs_arrayCodec(__bjs_arrayCodec(elemCodec1)).lift(); return arrayResult; }, multiArrayParams: function bjs_multiArrayParams(nums, strs) { - for (const elem of nums) { - i32Stack.push((elem | 0)); - } - i32Stack.push(nums.length); - for (const elem1 of strs) { - const bytes = textEncoder.encode(elem1); - const id = swift.memory.retain(bytes); - i32Stack.push(bytes.length); - i32Stack.push(id); - } - i32Stack.push(strs.length); + __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lower(nums); + __bjs_arrayCodec(__bjs_stringCodec).lower(strs); const ret = instance.exports.bjs_multiArrayParams(); return ret; }, multiOptionalArrayParams: function bjs_multiOptionalArrayParams(a, b) { - const isSome = a != null; - if (isSome) { - for (const elem of a) { - i32Stack.push((elem | 0)); - } - i32Stack.push(a.length); - } - i32Stack.push(+isSome); - const isSome1 = b != null; - if (isSome1) { - for (const elem1 of b) { - const bytes = textEncoder.encode(elem1); - const id = swift.memory.retain(bytes); - i32Stack.push(bytes.length); - i32Stack.push(id); - } - i32Stack.push(b.length); - } - i32Stack.push(+isSome1); + __bjs_optionalCodec(__bjs_arrayCodec(__bjs_primitiveCodecs.Int)).lower(a); + __bjs_optionalCodec(__bjs_arrayCodec(__bjs_stringCodec)).lower(b); const ret = instance.exports.bjs_multiOptionalArrayParams(); return ret; }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.d.ts index 507a96d4a..fefbf0039 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.d.ts @@ -55,5 +55,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js index 9f2faf589..497c71bf8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js @@ -41,6 +41,227 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + function __bjs_arrayCodec(elementCodec) { + return { + lower(value) { + for (let i = 0; i < value.length; i++) { + elementCodec.lower(value[i]); + } + i32Stack.push(value.length); + }, + lift() { + const count = i32Stack.pop(); + if (count === -1) { + return taStack.pop(); + } + const result = new Array(count); + for (let i = count - 1; i >= 0; i--) { + result[i] = elementCodec.lift(); + } + return result; + }, + }; + } + function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { + return { + lower(value) { + const isSome = isUndefinedOr ? value !== undefined : value != null; + if (isSome) { + elementCodec.lower(value); + i32Stack.push(1); + } else { + i32Stack.push(0); + } + }, + lift() { + if (i32Stack.pop() === 0) { + return isUndefinedOr ? undefined : null; + } + return elementCodec.lift(); + }, + }; + } + function __bjs_dictCodec(valueCodec) { + return { + lower(value) { + const keys = Object.keys(value); + for (let i = 0; i < keys.length; i++) { + __bjs_stringCodec.lower(keys[i]); + valueCodec.lower(value[keys[i]]); + } + i32Stack.push(keys.length); + }, + lift() { + const count = i32Stack.pop(); + const result = {}; + for (let i = 0; i < count; i++) { + const value = valueCodec.lift(); + const key = __bjs_stringCodec.lift(); + result[key] = value; + } + return result; + }, + }; + } + function __bjs_enumCodec(helper) { + return { + lower(value) { + i32Stack.push(helper.lower(value)); + }, + lift() { + return helper.lift(i32Stack.pop()); + }, + }; + } + + const __bjs_stringCodec = { + lower: (v) => { + const bytes = textEncoder.encode(v); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + }, + lift: () => { + const string = strStack.pop(); + return string; + }, + }; + const __bjs_primitiveCodecs = { + Bool: { + lower: (v) => { + i32Stack.push(v ? 1 : 0); + }, + lift: () => { + const bool = i32Stack.pop() !== 0; + return bool; + }, + }, + Int: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + Int8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + UInt: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + UInt64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + Float: { + lower: (v) => { + f32Stack.push(Math.fround(v)); + }, + lift: () => { + const f32 = f32Stack.pop(); + return f32; + }, + }, + Double: { + lower: (v) => { + f64Stack.push(v); + }, + lift: () => { + const f64 = f64Stack.pop(); + return f64; + }, + }, + String: __bjs_stringCodec, + JSValue: { + lower: (v) => { + const [vKind, vPayload1, vPayload2] = __bjs_jsValueLower(v); + i32Stack.push(vKind); + i32Stack.push(vPayload1); + f64Stack.push(vPayload2); + }, + lift: () => { + const jsValuePayload2 = f64Stack.pop(); + const jsValuePayload1 = i32Stack.pop(); + const jsValueKind = i32Stack.pop(); + const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + return jsValue; + }, + }, + }; + function __bjs_jsValueLower(value) { let kind; let payload1; @@ -223,6 +444,7 @@ export async function createInstantiator(options, swift) { const value = structHelpers.AsyncPoint.lift(); return swift.memory.retain(value); } + bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; @@ -340,18 +562,7 @@ export async function createInstantiator(options, swift) { } bjs["promise_resolve_TestModule_Sa10AsyncPointV"] = function(promise) { try { - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const struct = structHelpers.AsyncPoint.lift(); - arrayResult.push(struct); - } - arrayResult.reverse(); - } + const arrayResult = __bjs_arrayCodec(structHelpers.AsyncPoint).lift(); swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(arrayResult); } catch (error) { setException(error); @@ -359,18 +570,16 @@ export async function createInstantiator(options, swift) { } bjs["promise_resolve_TestModule_Sa14AsyncDirectionO"] = function(promise) { try { - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { + const elemCodec = { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { const caseId = i32Stack.pop(); - arrayResult.push(caseId); - } - arrayResult.reverse(); - } + return caseId; + }, + }; + const arrayResult = __bjs_arrayCodec(elemCodec).lift(); swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(arrayResult); } catch (error) { setException(error); @@ -378,13 +587,7 @@ export async function createInstantiator(options, swift) { } bjs["promise_resolve_TestModule_SD10AsyncPointV"] = function(promise) { try { - const dictLen = i32Stack.pop(); - const dictResult = {}; - for (let i = 0; i < dictLen; i++) { - const struct = structHelpers.AsyncPoint.lift(); - const string = strStack.pop(); - dictResult[string] = struct; - } + const dictResult = __bjs_dictCodec(structHelpers.AsyncPoint).lift(); swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(dictResult); } catch (error) { setException(error); @@ -392,13 +595,16 @@ export async function createInstantiator(options, swift) { } bjs["promise_resolve_TestModule_SD14AsyncDirectionO"] = function(promise) { try { - const dictLen = i32Stack.pop(); - const dictResult = {}; - for (let i = 0; i < dictLen; i++) { - const caseId = i32Stack.pop(); - const string = strStack.pop(); - dictResult[string] = caseId; - } + const elemCodec = { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const caseId = i32Stack.pop(); + return caseId; + }, + }; + const dictResult = __bjs_dictCodec(elemCodec).lift(); swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(dictResult); } catch (error) { setException(error); @@ -643,63 +849,53 @@ export async function createInstantiator(options, swift) { return ret1; }, asyncRoundTripOptionalStruct: function bjs_asyncRoundTripOptionalStruct(v) { - const isSome = v != null; - if (isSome) { - structHelpers.AsyncPoint.lower(v); - } - i32Stack.push(+isSome); + __bjs_optionalCodec(structHelpers.AsyncPoint).lower(v); const ret = instance.exports.bjs_asyncRoundTripOptionalStruct(); const ret1 = swift.memory.getObject(ret); swift.memory.release(ret); return ret1; }, asyncRoundTripStructArray: function bjs_asyncRoundTripStructArray(v) { - for (const elem of v) { - structHelpers.AsyncPoint.lower(elem); - } - i32Stack.push(v.length); + __bjs_arrayCodec(structHelpers.AsyncPoint).lower(v); const ret = instance.exports.bjs_asyncRoundTripStructArray(); const ret1 = swift.memory.getObject(ret); swift.memory.release(ret); return ret1; }, asyncRoundTripEnumArray: function bjs_asyncRoundTripEnumArray(v) { - for (const elem of v) { - i32Stack.push((elem | 0)); - } - i32Stack.push(v.length); + const elemCodec = { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const caseId = i32Stack.pop(); + return caseId; + }, + }; + __bjs_arrayCodec(elemCodec).lower(v); const ret = instance.exports.bjs_asyncRoundTripEnumArray(); const ret1 = swift.memory.getObject(ret); swift.memory.release(ret); return ret1; }, asyncRoundTripStructDictionary: function bjs_asyncRoundTripStructDictionary(v) { - const entries = Object.entries(v); - for (const entry of entries) { - const [key, value] = entry; - const bytes = textEncoder.encode(key); - const id = swift.memory.retain(bytes); - i32Stack.push(bytes.length); - i32Stack.push(id); - structHelpers.AsyncPoint.lower(value); - } - i32Stack.push(entries.length); + __bjs_dictCodec(structHelpers.AsyncPoint).lower(v); const ret = instance.exports.bjs_asyncRoundTripStructDictionary(); const ret1 = swift.memory.getObject(ret); swift.memory.release(ret); return ret1; }, asyncRoundTripEnumDictionary: function bjs_asyncRoundTripEnumDictionary(v) { - const entries = Object.entries(v); - for (const entry of entries) { - const [key, value] = entry; - const bytes = textEncoder.encode(key); - const id = swift.memory.retain(bytes); - i32Stack.push(bytes.length); - i32Stack.push(id); - i32Stack.push((value | 0)); - } - i32Stack.push(entries.length); + const elemCodec = { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const caseId = i32Stack.pop(); + return caseId; + }, + }; + __bjs_dictCodec(elemCodec).lower(v); const ret = instance.exports.bjs_asyncRoundTripEnumDictionary(); const ret1 = swift.memory.getObject(ret); swift.memory.release(ret); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.d.ts index d25336ef7..c0c8900d7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.d.ts @@ -29,5 +29,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js index 98c0aff46..8e09e38d9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js @@ -239,6 +239,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.d.ts index e612ae1e1..f1bf7e0c6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.d.ts @@ -19,5 +19,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.d.ts index 491a66795..97a9c23ad 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.d.ts @@ -19,5 +19,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.d.ts index 5537696c4..a2bd7b41b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.d.ts @@ -47,5 +47,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.js index 272bb8c49..db3288037 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.js @@ -130,6 +130,7 @@ export async function createInstantiator(options, swift) { const value = structHelpers.Account_Credentials.lift(); return swift.memory.retain(value); } + bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.d.ts index 961b9fa5b..7cec6e66b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.d.ts @@ -161,5 +161,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js index ba2b7cc77..16505d112 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js @@ -37,6 +37,316 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + function __bjs_arrayCodec(elementCodec) { + return { + lower(value) { + for (let i = 0; i < value.length; i++) { + elementCodec.lower(value[i]); + } + i32Stack.push(value.length); + }, + lift() { + const count = i32Stack.pop(); + if (count === -1) { + return taStack.pop(); + } + const result = new Array(count); + for (let i = count - 1; i >= 0; i--) { + result[i] = elementCodec.lift(); + } + return result; + }, + }; + } + function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { + return { + lower(value) { + const isSome = isUndefinedOr ? value !== undefined : value != null; + if (isSome) { + elementCodec.lower(value); + i32Stack.push(1); + } else { + i32Stack.push(0); + } + }, + lift() { + if (i32Stack.pop() === 0) { + return isUndefinedOr ? undefined : null; + } + return elementCodec.lift(); + }, + }; + } + function __bjs_dictCodec(valueCodec) { + return { + lower(value) { + const keys = Object.keys(value); + for (let i = 0; i < keys.length; i++) { + __bjs_stringCodec.lower(keys[i]); + valueCodec.lower(value[keys[i]]); + } + i32Stack.push(keys.length); + }, + lift() { + const count = i32Stack.pop(); + const result = {}; + for (let i = 0; i < count; i++) { + const value = valueCodec.lift(); + const key = __bjs_stringCodec.lift(); + result[key] = value; + } + return result; + }, + }; + } + function __bjs_enumCodec(helper) { + return { + lower(value) { + i32Stack.push(helper.lower(value)); + }, + lift() { + return helper.lift(i32Stack.pop()); + }, + }; + } + + const __bjs_stringCodec = { + lower: (v) => { + const bytes = textEncoder.encode(v); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + }, + lift: () => { + const string = strStack.pop(); + return string; + }, + }; + const __bjs_primitiveCodecs = { + Bool: { + lower: (v) => { + i32Stack.push(v ? 1 : 0); + }, + lift: () => { + const bool = i32Stack.pop() !== 0; + return bool; + }, + }, + Int: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + Int8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + UInt: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + UInt64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + Float: { + lower: (v) => { + f32Stack.push(Math.fround(v)); + }, + lift: () => { + const f32 = f32Stack.pop(); + return f32; + }, + }, + Double: { + lower: (v) => { + f64Stack.push(v); + }, + lift: () => { + const f64 = f64Stack.pop(); + return f64; + }, + }, + String: __bjs_stringCodec, + JSValue: { + lower: (v) => { + const [vKind, vPayload1, vPayload2] = __bjs_jsValueLower(v); + i32Stack.push(vKind); + i32Stack.push(vPayload1); + f64Stack.push(vPayload2); + }, + lift: () => { + const jsValuePayload2 = f64Stack.pop(); + const jsValuePayload1 = i32Stack.pop(); + const jsValueKind = i32Stack.pop(); + const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + return jsValue; + }, + }, + }; + + function __bjs_jsValueLower(value) { + let kind; + let payload1; + let payload2; + if (value === null) { + kind = 4; + payload1 = 0; + payload2 = 0; + } else { + switch (typeof value) { + case "boolean": + kind = 0; + payload1 = value ? 1 : 0; + payload2 = 0; + break; + case "number": + kind = 2; + payload1 = 0; + payload2 = value; + break; + case "string": + kind = 1; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "undefined": + kind = 5; + payload1 = 0; + payload2 = 0; + break; + case "object": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "function": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "symbol": + kind = 7; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "bigint": + kind = 8; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + default: + throw new TypeError("Unsupported JSValue type"); + } + } + return [kind, payload1, payload2]; + } + function __bjs_jsValueLift(kind, payload1, payload2) { + let jsValue; + switch (kind) { + case 0: + jsValue = payload1 !== 0; + break; + case 1: + jsValue = swift.memory.getObject(payload1); + break; + case 2: + jsValue = payload2; + break; + case 3: + jsValue = swift.memory.getObject(payload1); + break; + case 4: + jsValue = null; + break; + case 5: + jsValue = undefined; + break; + case 7: + jsValue = swift.memory.getObject(payload1); + break; + case 8: + jsValue = swift.memory.getObject(payload1); + break; + default: + throw new TypeError("Unsupported JSValue kind " + kind); + } + return jsValue; + } + const __bjs_createConfigHelpers = () => ({ lower: (value) => { const bytes = textEncoder.encode(value.name); @@ -162,6 +472,7 @@ export async function createInstantiator(options, swift) { const value = structHelpers.MathOperations.lift(); return swift.memory.retain(value); } + bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; @@ -535,137 +846,51 @@ export async function createInstantiator(options, swift) { return EmptyGreeter.__construct(ret); }, testOptionalStructDefault: function bjs_testOptionalStructDefault(point = null) { - const isSome = point != null; - if (isSome) { - structHelpers.Config.lower(point); - } - i32Stack.push(+isSome); + __bjs_optionalCodec(structHelpers.Config).lower(point); instance.exports.bjs_testOptionalStructDefault(); - const isSome1 = i32Stack.pop(); - const optResult = isSome1 ? structHelpers.Config.lift() : null; - return optResult; + const optValue = __bjs_optionalCodec(structHelpers.Config).lift(); + return optValue; }, testOptionalStructWithValueDefault: function bjs_testOptionalStructWithValueDefault(point = { name: "default", value: 42, enabled: true }) { - const isSome = point != null; - if (isSome) { - structHelpers.Config.lower(point); - } - i32Stack.push(+isSome); + __bjs_optionalCodec(structHelpers.Config).lower(point); instance.exports.bjs_testOptionalStructWithValueDefault(); - const isSome1 = i32Stack.pop(); - const optResult = isSome1 ? structHelpers.Config.lift() : null; - return optResult; + const optValue = __bjs_optionalCodec(structHelpers.Config).lift(); + return optValue; }, testIntArrayDefault: function bjs_testIntArrayDefault(values = [1, 2, 3]) { - for (const elem of values) { - i32Stack.push((elem | 0)); - } - i32Stack.push(values.length); + __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lower(values); instance.exports.bjs_testIntArrayDefault(); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const int = i32Stack.pop(); - arrayResult.push(int); - } - arrayResult.reverse(); - } + const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lift(); return arrayResult; }, testStringArrayDefault: function bjs_testStringArrayDefault(names = ["a", "b", "c"]) { - for (const elem of names) { - const bytes = textEncoder.encode(elem); - const id = swift.memory.retain(bytes); - i32Stack.push(bytes.length); - i32Stack.push(id); - } - i32Stack.push(names.length); + __bjs_arrayCodec(__bjs_stringCodec).lower(names); instance.exports.bjs_testStringArrayDefault(); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const string = strStack.pop(); - arrayResult.push(string); - } - arrayResult.reverse(); - } + const arrayResult = __bjs_arrayCodec(__bjs_stringCodec).lift(); return arrayResult; }, testDoubleArrayDefault: function bjs_testDoubleArrayDefault(values = [1.5, 2.5, 3.5]) { - for (const elem of values) { - f64Stack.push(elem); - } - i32Stack.push(values.length); + __bjs_arrayCodec(__bjs_primitiveCodecs.Double).lower(values); instance.exports.bjs_testDoubleArrayDefault(); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const f64 = f64Stack.pop(); - arrayResult.push(f64); - } - arrayResult.reverse(); - } + const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.Double).lift(); return arrayResult; }, testBoolArrayDefault: function bjs_testBoolArrayDefault(flags = [true, false, true]) { - for (const elem of flags) { - i32Stack.push(elem ? 1 : 0); - } - i32Stack.push(flags.length); + __bjs_arrayCodec(__bjs_primitiveCodecs.Bool).lower(flags); instance.exports.bjs_testBoolArrayDefault(); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const bool = i32Stack.pop() !== 0; - arrayResult.push(bool); - } - arrayResult.reverse(); - } + const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.Bool).lift(); return arrayResult; }, testEmptyArrayDefault: function bjs_testEmptyArrayDefault(items = []) { - for (const elem of items) { - i32Stack.push((elem | 0)); - } - i32Stack.push(items.length); + __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lower(items); instance.exports.bjs_testEmptyArrayDefault(); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const int = i32Stack.pop(); - arrayResult.push(int); - } - arrayResult.reverse(); - } + const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lift(); return arrayResult; }, testMixedWithArrayDefault: function bjs_testMixedWithArrayDefault(name = "test", values = [10, 20, 30], enabled = true) { const nameBytes = textEncoder.encode(name); const nameId = swift.memory.retain(nameBytes); - for (const elem of values) { - i32Stack.push((elem | 0)); - } - i32Stack.push(values.length); + __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lower(values); instance.exports.bjs_testMixedWithArrayDefault(nameId, nameBytes.length, enabled); const ret = tmpRetString; tmpRetString = undefined; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.d.ts index 652177cd8..2479e3f25 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.d.ts @@ -35,5 +35,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js index d0ac5307f..78e1d4c54 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js @@ -31,44 +31,328 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + function __bjs_arrayCodec(elementCodec) { + return { + lower(value) { + for (let i = 0; i < value.length; i++) { + elementCodec.lower(value[i]); + } + i32Stack.push(value.length); + }, + lift() { + const count = i32Stack.pop(); + if (count === -1) { + return taStack.pop(); + } + const result = new Array(count); + for (let i = count - 1; i >= 0; i--) { + result[i] = elementCodec.lift(); + } + return result; + }, + }; + } + function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { + return { + lower(value) { + const isSome = isUndefinedOr ? value !== undefined : value != null; + if (isSome) { + elementCodec.lower(value); + i32Stack.push(1); + } else { + i32Stack.push(0); + } + }, + lift() { + if (i32Stack.pop() === 0) { + return isUndefinedOr ? undefined : null; + } + return elementCodec.lift(); + }, + }; + } + function __bjs_dictCodec(valueCodec) { + return { + lower(value) { + const keys = Object.keys(value); + for (let i = 0; i < keys.length; i++) { + __bjs_stringCodec.lower(keys[i]); + valueCodec.lower(value[keys[i]]); + } + i32Stack.push(keys.length); + }, + lift() { + const count = i32Stack.pop(); + const result = {}; + for (let i = 0; i < count; i++) { + const value = valueCodec.lift(); + const key = __bjs_stringCodec.lift(); + result[key] = value; + } + return result; + }, + }; + } + function __bjs_enumCodec(helper) { + return { + lower(value) { + i32Stack.push(helper.lower(value)); + }, + lift() { + return helper.lift(i32Stack.pop()); + }, + }; + } + + const __bjs_stringCodec = { + lower: (v) => { + const bytes = textEncoder.encode(v); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + }, + lift: () => { + const string = strStack.pop(); + return string; + }, + }; + const __bjs_primitiveCodecs = { + Bool: { + lower: (v) => { + i32Stack.push(v ? 1 : 0); + }, + lift: () => { + const bool = i32Stack.pop() !== 0; + return bool; + }, + }, + Int: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + Int8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + UInt: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + UInt64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + Float: { + lower: (v) => { + f32Stack.push(Math.fround(v)); + }, + lift: () => { + const f32 = f32Stack.pop(); + return f32; + }, + }, + Double: { + lower: (v) => { + f64Stack.push(v); + }, + lift: () => { + const f64 = f64Stack.pop(); + return f64; + }, + }, + String: __bjs_stringCodec, + JSValue: { + lower: (v) => { + const [vKind, vPayload1, vPayload2] = __bjs_jsValueLower(v); + i32Stack.push(vKind); + i32Stack.push(vPayload1); + f64Stack.push(vPayload2); + }, + lift: () => { + const jsValuePayload2 = f64Stack.pop(); + const jsValuePayload1 = i32Stack.pop(); + const jsValueKind = i32Stack.pop(); + const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + return jsValue; + }, + }, + }; + + function __bjs_jsValueLower(value) { + let kind; + let payload1; + let payload2; + if (value === null) { + kind = 4; + payload1 = 0; + payload2 = 0; + } else { + switch (typeof value) { + case "boolean": + kind = 0; + payload1 = value ? 1 : 0; + payload2 = 0; + break; + case "number": + kind = 2; + payload1 = 0; + payload2 = value; + break; + case "string": + kind = 1; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "undefined": + kind = 5; + payload1 = 0; + payload2 = 0; + break; + case "object": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "function": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "symbol": + kind = 7; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "bigint": + kind = 8; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + default: + throw new TypeError("Unsupported JSValue type"); + } + } + return [kind, payload1, payload2]; + } + function __bjs_jsValueLift(kind, payload1, payload2) { + let jsValue; + switch (kind) { + case 0: + jsValue = payload1 !== 0; + break; + case 1: + jsValue = swift.memory.getObject(payload1); + break; + case 2: + jsValue = payload2; + break; + case 3: + jsValue = swift.memory.getObject(payload1); + break; + case 4: + jsValue = null; + break; + case 5: + jsValue = undefined; + break; + case 7: + jsValue = swift.memory.getObject(payload1); + break; + case 8: + jsValue = swift.memory.getObject(payload1); + break; + default: + throw new TypeError("Unsupported JSValue kind " + kind); + } + return jsValue; + } + const __bjs_createCountersHelpers = () => ({ lower: (value) => { const bytes = textEncoder.encode(value.name); const id = swift.memory.retain(bytes); i32Stack.push(bytes.length); i32Stack.push(id); - const entries = Object.entries(value.counts); - for (const entry of entries) { - const [key, value] = entry; - const bytes1 = textEncoder.encode(key); - const id1 = swift.memory.retain(bytes1); - i32Stack.push(bytes1.length); - i32Stack.push(id1); - const isSome = value != null ? 1 : 0; - if (isSome) { - i32Stack.push((value | 0)); - } - i32Stack.push(isSome); - } - i32Stack.push(entries.length); + __bjs_dictCodec(__bjs_optionalCodec(__bjs_primitiveCodecs.Int)).lower(value.counts); }, lift: () => { - const dictLen = i32Stack.pop(); - const dictResult = {}; - for (let i = 0; i < dictLen; i++) { - const isSome = i32Stack.pop(); - let optValue; - if (isSome === 0) { - optValue = null; - } else { - const int = i32Stack.pop(); - optValue = int; - } - const string = strStack.pop(); - dictResult[string] = optValue; - } - const string1 = strStack.pop(); - return { name: string1, counts: dictResult }; + const dictResult = __bjs_dictCodec(__bjs_optionalCodec(__bjs_primitiveCodecs.Int)).lift(); + const string = strStack.pop(); + return { name: string, counts: dictResult }; } }); @@ -154,6 +438,7 @@ export async function createInstantiator(options, swift) { const value = structHelpers.Counters.lift(); return swift.memory.retain(value); } + bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; @@ -262,24 +547,9 @@ export async function createInstantiator(options, swift) { const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; TestModule["bjs_importMirrorDictionary"] = function bjs_importMirrorDictionary() { try { - const dictLen = i32Stack.pop(); - const dictResult = {}; - for (let i = 0; i < dictLen; i++) { - const f64 = f64Stack.pop(); - const string = strStack.pop(); - dictResult[string] = f64; - } + const dictResult = __bjs_dictCodec(__bjs_primitiveCodecs.Double).lift(); let ret = imports.importMirrorDictionary(dictResult); - const entries = Object.entries(ret); - for (const entry of entries) { - const [key, value] = entry; - const bytes = textEncoder.encode(key); - const id = swift.memory.retain(bytes); - i32Stack.push(bytes.length); - i32Stack.push(id); - f64Stack.push(value); - } - i32Stack.push(entries.length); + __bjs_dictCodec(__bjs_primitiveCodecs.Double).lower(ret); } catch (error) { setException(error); } @@ -361,149 +631,73 @@ export async function createInstantiator(options, swift) { const exports = { mirrorDictionary: function bjs_mirrorDictionary(values) { - const entries = Object.entries(values); - for (const entry of entries) { - const [key, value] = entry; - const bytes = textEncoder.encode(key); - const id = swift.memory.retain(bytes); - i32Stack.push(bytes.length); - i32Stack.push(id); - i32Stack.push((value | 0)); - } - i32Stack.push(entries.length); + __bjs_dictCodec(__bjs_primitiveCodecs.Int).lower(values); instance.exports.bjs_mirrorDictionary(); - const dictLen = i32Stack.pop(); - const dictResult = {}; - for (let i = 0; i < dictLen; i++) { - const int = i32Stack.pop(); - const string = strStack.pop(); - dictResult[string] = int; - } + const dictResult = __bjs_dictCodec(__bjs_primitiveCodecs.Int).lift(); return dictResult; }, optionalDictionary: function bjs_optionalDictionary(values) { - const isSome = values != null; - if (isSome) { - const entries = Object.entries(values); - for (const entry of entries) { - const [key, value] = entry; - const bytes = textEncoder.encode(key); - const id = swift.memory.retain(bytes); - i32Stack.push(bytes.length); - i32Stack.push(id); - const bytes1 = textEncoder.encode(value); - const id1 = swift.memory.retain(bytes1); - i32Stack.push(bytes1.length); - i32Stack.push(id1); - } - i32Stack.push(entries.length); - } - i32Stack.push(+isSome); + __bjs_optionalCodec(__bjs_dictCodec(__bjs_stringCodec)).lower(values); instance.exports.bjs_optionalDictionary(); - const isSome1 = i32Stack.pop(); - let optResult; - if (isSome1) { - const dictLen = i32Stack.pop(); - const dictResult = {}; - for (let i = 0; i < dictLen; i++) { - const string = strStack.pop(); - const string1 = strStack.pop(); - dictResult[string1] = string; - } - optResult = dictResult; - } else { - optResult = null; - } - return optResult; + const optValue = __bjs_optionalCodec(__bjs_dictCodec(__bjs_stringCodec)).lift(); + return optValue; }, nestedDictionary: function bjs_nestedDictionary(values) { - const entries = Object.entries(values); - for (const entry of entries) { - const [key, value] = entry; - const bytes = textEncoder.encode(key); - const id = swift.memory.retain(bytes); - i32Stack.push(bytes.length); - i32Stack.push(id); - for (const elem of value) { - i32Stack.push((elem | 0)); - } - i32Stack.push(value.length); - } - i32Stack.push(entries.length); + __bjs_dictCodec(__bjs_arrayCodec(__bjs_primitiveCodecs.Int)).lower(values); instance.exports.bjs_nestedDictionary(); - const dictLen = i32Stack.pop(); - const dictResult = {}; - for (let i = 0; i < dictLen; i++) { - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i1 = 0; i1 < arrayLen; i1++) { - const int = i32Stack.pop(); - arrayResult.push(int); - } - arrayResult.reverse(); - } - const string = strStack.pop(); - dictResult[string] = arrayResult; - } + const dictResult = __bjs_dictCodec(__bjs_arrayCodec(__bjs_primitiveCodecs.Int)).lift(); return dictResult; }, boxDictionary: function bjs_boxDictionary(boxes) { - const entries = Object.entries(boxes); - for (const entry of entries) { - const [key, value] = entry; - const bytes = textEncoder.encode(key); - const id = swift.memory.retain(bytes); - i32Stack.push(bytes.length); - i32Stack.push(id); - ptrStack.push(value.pointer); - } - i32Stack.push(entries.length); + const elemCodec = { + lower: (v) => { + ptrStack.push(v.pointer); + }, + lift: () => { + const ptr = ptrStack.pop(); + const obj = Box.__construct(ptr); + return obj; + }, + }; + __bjs_dictCodec(elemCodec).lower(boxes); instance.exports.bjs_boxDictionary(); - const dictLen = i32Stack.pop(); - const dictResult = {}; - for (let i = 0; i < dictLen; i++) { - const ptr = ptrStack.pop(); - const obj = Box.__construct(ptr); - const string = strStack.pop(); - dictResult[string] = obj; - } + const elemCodec1 = { + lower: (v) => { + ptrStack.push(v.pointer); + }, + lift: () => { + const ptr = ptrStack.pop(); + const obj = Box.__construct(ptr); + return obj; + }, + }; + const dictResult = __bjs_dictCodec(elemCodec1).lift(); return dictResult; }, optionalBoxDictionary: function bjs_optionalBoxDictionary(boxes) { - const entries = Object.entries(boxes); - for (const entry of entries) { - const [key, value] = entry; - const bytes = textEncoder.encode(key); - const id = swift.memory.retain(bytes); - i32Stack.push(bytes.length); - i32Stack.push(id); - const isSome = value != null ? 1 : 0; - if (isSome) { - ptrStack.push(value.pointer); - } - i32Stack.push(isSome); - } - i32Stack.push(entries.length); + const elemCodec = { + lower: (v) => { + ptrStack.push(v.pointer); + }, + lift: () => { + const ptr = ptrStack.pop(); + const obj = Box.__construct(ptr); + return obj; + }, + }; + __bjs_dictCodec(__bjs_optionalCodec(elemCodec)).lower(boxes); instance.exports.bjs_optionalBoxDictionary(); - const dictLen = i32Stack.pop(); - const dictResult = {}; - for (let i = 0; i < dictLen; i++) { - const isSome1 = i32Stack.pop(); - let optValue; - if (isSome1 === 0) { - optValue = null; - } else { + const elemCodec1 = { + lower: (v) => { + ptrStack.push(v.pointer); + }, + lift: () => { const ptr = ptrStack.pop(); const obj = Box.__construct(ptr); - optValue = obj; - } - const string = strStack.pop(); - dictResult[string] = optValue; - } + return obj; + }, + }; + const dictResult = __bjs_dictCodec(__bjs_optionalCodec(elemCodec1)).lift(); return dictResult; }, roundtripCounters: function bjs_roundtripCounters(counters) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.d.ts index 196ef73fe..f37d8945d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.d.ts @@ -136,5 +136,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.js index f29814675..53cd64917 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.js @@ -130,6 +130,7 @@ export async function createInstantiator(options, swift) { const value = structHelpers.Point.lift(); return swift.memory.retain(value); } + bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.d.ts index d2772fa8b..4921cd937 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.d.ts @@ -26,5 +26,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js index 42f3fd958..43ff590b4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js @@ -106,6 +106,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.d.ts index 36fc92474..9e6d967ff 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.d.ts @@ -195,5 +195,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js index 36683fd58..814736050 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js @@ -112,6 +112,316 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + function __bjs_arrayCodec(elementCodec) { + return { + lower(value) { + for (let i = 0; i < value.length; i++) { + elementCodec.lower(value[i]); + } + i32Stack.push(value.length); + }, + lift() { + const count = i32Stack.pop(); + if (count === -1) { + return taStack.pop(); + } + const result = new Array(count); + for (let i = count - 1; i >= 0; i--) { + result[i] = elementCodec.lift(); + } + return result; + }, + }; + } + function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { + return { + lower(value) { + const isSome = isUndefinedOr ? value !== undefined : value != null; + if (isSome) { + elementCodec.lower(value); + i32Stack.push(1); + } else { + i32Stack.push(0); + } + }, + lift() { + if (i32Stack.pop() === 0) { + return isUndefinedOr ? undefined : null; + } + return elementCodec.lift(); + }, + }; + } + function __bjs_dictCodec(valueCodec) { + return { + lower(value) { + const keys = Object.keys(value); + for (let i = 0; i < keys.length; i++) { + __bjs_stringCodec.lower(keys[i]); + valueCodec.lower(value[keys[i]]); + } + i32Stack.push(keys.length); + }, + lift() { + const count = i32Stack.pop(); + const result = {}; + for (let i = 0; i < count; i++) { + const value = valueCodec.lift(); + const key = __bjs_stringCodec.lift(); + result[key] = value; + } + return result; + }, + }; + } + function __bjs_enumCodec(helper) { + return { + lower(value) { + i32Stack.push(helper.lower(value)); + }, + lift() { + return helper.lift(i32Stack.pop()); + }, + }; + } + + const __bjs_stringCodec = { + lower: (v) => { + const bytes = textEncoder.encode(v); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + }, + lift: () => { + const string = strStack.pop(); + return string; + }, + }; + const __bjs_primitiveCodecs = { + Bool: { + lower: (v) => { + i32Stack.push(v ? 1 : 0); + }, + lift: () => { + const bool = i32Stack.pop() !== 0; + return bool; + }, + }, + Int: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + Int8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + UInt: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + UInt64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + Float: { + lower: (v) => { + f32Stack.push(Math.fround(v)); + }, + lift: () => { + const f32 = f32Stack.pop(); + return f32; + }, + }, + Double: { + lower: (v) => { + f64Stack.push(v); + }, + lift: () => { + const f64 = f64Stack.pop(); + return f64; + }, + }, + String: __bjs_stringCodec, + JSValue: { + lower: (v) => { + const [vKind, vPayload1, vPayload2] = __bjs_jsValueLower(v); + i32Stack.push(vKind); + i32Stack.push(vPayload1); + f64Stack.push(vPayload2); + }, + lift: () => { + const jsValuePayload2 = f64Stack.pop(); + const jsValuePayload1 = i32Stack.pop(); + const jsValueKind = i32Stack.pop(); + const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + return jsValue; + }, + }, + }; + + function __bjs_jsValueLower(value) { + let kind; + let payload1; + let payload2; + if (value === null) { + kind = 4; + payload1 = 0; + payload2 = 0; + } else { + switch (typeof value) { + case "boolean": + kind = 0; + payload1 = value ? 1 : 0; + payload2 = 0; + break; + case "number": + kind = 2; + payload1 = 0; + payload2 = value; + break; + case "string": + kind = 1; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "undefined": + kind = 5; + payload1 = 0; + payload2 = 0; + break; + case "object": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "function": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "symbol": + kind = 7; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "bigint": + kind = 8; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + default: + throw new TypeError("Unsupported JSValue type"); + } + } + return [kind, payload1, payload2]; + } + function __bjs_jsValueLift(kind, payload1, payload2) { + let jsValue; + switch (kind) { + case 0: + jsValue = payload1 !== 0; + break; + case 1: + jsValue = swift.memory.getObject(payload1); + break; + case 2: + jsValue = payload2; + break; + case 3: + jsValue = swift.memory.getObject(payload1); + break; + case 4: + jsValue = null; + break; + case 5: + jsValue = undefined; + break; + case 7: + jsValue = swift.memory.getObject(payload1); + break; + case 8: + jsValue = swift.memory.getObject(payload1); + break; + default: + throw new TypeError("Unsupported JSValue kind " + kind); + } + return jsValue; + } + const __bjs_createPointHelpers = () => ({ lower: (value) => { f64Stack.push(value.x); @@ -382,48 +692,18 @@ export async function createInstantiator(options, swift) { const enumTag = value.tag; switch (enumTag) { case APIOptionalResultValues.Tag.Success: { - const isSome = value.param0 != null ? 1 : 0; - if (isSome) { - const bytes = textEncoder.encode(value.param0); - const id = swift.memory.retain(bytes); - i32Stack.push(bytes.length); - i32Stack.push(id); - } - i32Stack.push(isSome); + __bjs_optionalCodec(__bjs_stringCodec).lower(value.param0); return APIOptionalResultValues.Tag.Success; } case APIOptionalResultValues.Tag.Failure: { - const isSome = value.param1 != null ? 1 : 0; - if (isSome) { - i32Stack.push(value.param1 ? 1 : 0); - } - i32Stack.push(isSome); - const isSome1 = value.param0 != null ? 1 : 0; - if (isSome1) { - i32Stack.push((value.param0 | 0)); - } - i32Stack.push(isSome1); + __bjs_optionalCodec(__bjs_primitiveCodecs.Bool).lower(value.param1); + __bjs_optionalCodec(__bjs_primitiveCodecs.Int).lower(value.param0); return APIOptionalResultValues.Tag.Failure; } case APIOptionalResultValues.Tag.Status: { - const isSome = value.param2 != null ? 1 : 0; - if (isSome) { - const bytes = textEncoder.encode(value.param2); - const id = swift.memory.retain(bytes); - i32Stack.push(bytes.length); - i32Stack.push(id); - } - i32Stack.push(isSome); - const isSome1 = value.param1 != null ? 1 : 0; - if (isSome1) { - i32Stack.push((value.param1 | 0)); - } - i32Stack.push(isSome1); - const isSome2 = value.param0 != null ? 1 : 0; - if (isSome2) { - i32Stack.push(value.param0 ? 1 : 0); - } - i32Stack.push(isSome2); + __bjs_optionalCodec(__bjs_stringCodec).lower(value.param2); + __bjs_optionalCodec(__bjs_primitiveCodecs.Int).lower(value.param1); + __bjs_optionalCodec(__bjs_primitiveCodecs.Bool).lower(value.param0); return APIOptionalResultValues.Tag.Status; } default: throw new Error("Unknown APIOptionalResultValues tag: " + String(enumTag)); @@ -433,60 +713,18 @@ export async function createInstantiator(options, swift) { tag = tag | 0; switch (tag) { case APIOptionalResultValues.Tag.Success: { - const isSome = i32Stack.pop(); - let optValue; - if (isSome === 0) { - optValue = null; - } else { - const string = strStack.pop(); - optValue = string; - } + const optValue = __bjs_optionalCodec(__bjs_stringCodec).lift(); return { tag: APIOptionalResultValues.Tag.Success, param0: optValue }; } case APIOptionalResultValues.Tag.Failure: { - const isSome = i32Stack.pop(); - let optValue; - if (isSome === 0) { - optValue = null; - } else { - const bool = i32Stack.pop() !== 0; - optValue = bool; - } - const isSome1 = i32Stack.pop(); - let optValue1; - if (isSome1 === 0) { - optValue1 = null; - } else { - const int = i32Stack.pop(); - optValue1 = int; - } + const optValue = __bjs_optionalCodec(__bjs_primitiveCodecs.Bool).lift(); + const optValue1 = __bjs_optionalCodec(__bjs_primitiveCodecs.Int).lift(); return { tag: APIOptionalResultValues.Tag.Failure, param0: optValue1, param1: optValue }; } case APIOptionalResultValues.Tag.Status: { - const isSome = i32Stack.pop(); - let optValue; - if (isSome === 0) { - optValue = null; - } else { - const string = strStack.pop(); - optValue = string; - } - const isSome1 = i32Stack.pop(); - let optValue1; - if (isSome1 === 0) { - optValue1 = null; - } else { - const int = i32Stack.pop(); - optValue1 = int; - } - const isSome2 = i32Stack.pop(); - let optValue2; - if (isSome2 === 0) { - optValue2 = null; - } else { - const bool = i32Stack.pop() !== 0; - optValue2 = bool; - } + const optValue = __bjs_optionalCodec(__bjs_stringCodec).lift(); + const optValue1 = __bjs_optionalCodec(__bjs_primitiveCodecs.Int).lift(); + const optValue2 = __bjs_optionalCodec(__bjs_primitiveCodecs.Bool).lift(); return { tag: APIOptionalResultValues.Tag.Status, param0: optValue2, param1: optValue1, param2: optValue }; } default: throw new Error("Unknown APIOptionalResultValues tag returned from Swift: " + String(tag)); @@ -506,19 +744,29 @@ export async function createInstantiator(options, swift) { return TypedPayloadResultValues.Tag.Direction; } case TypedPayloadResultValues.Tag.OptPrecision: { - const isSome = value.param0 != null ? 1 : 0; - if (isSome) { - f32Stack.push(Math.fround(value.param0)); - } - i32Stack.push(isSome); + const elemCodec = { + lower: (v) => { + f32Stack.push(Math.fround(v)); + }, + lift: () => { + const rawValue = f32Stack.pop(); + return rawValue; + }, + }; + __bjs_optionalCodec(elemCodec).lower(value.param0); return TypedPayloadResultValues.Tag.OptPrecision; } case TypedPayloadResultValues.Tag.OptDirection: { - const isSome = value.param0 != null ? 1 : 0; - if (isSome) { - i32Stack.push((value.param0 | 0)); - } - i32Stack.push(isSome); + const elemCodec = { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const caseId = i32Stack.pop(); + return caseId; + }, + }; + __bjs_optionalCodec(elemCodec).lower(value.param0); return TypedPayloadResultValues.Tag.OptDirection; } case TypedPayloadResultValues.Tag.Empty: { @@ -539,25 +787,29 @@ export async function createInstantiator(options, swift) { return { tag: TypedPayloadResultValues.Tag.Direction, param0: caseId }; } case TypedPayloadResultValues.Tag.OptPrecision: { - const isSome = i32Stack.pop(); - let optValue; - if (isSome === 0) { - optValue = null; - } else { - const rawValue = f32Stack.pop(); - optValue = rawValue; - } + const elemCodec = { + lower: (v) => { + f32Stack.push(Math.fround(v)); + }, + lift: () => { + const rawValue = f32Stack.pop(); + return rawValue; + }, + }; + const optValue = __bjs_optionalCodec(elemCodec).lift(); return { tag: TypedPayloadResultValues.Tag.OptPrecision, param0: optValue }; } case TypedPayloadResultValues.Tag.OptDirection: { - const isSome = i32Stack.pop(); - let optValue; - if (isSome === 0) { - optValue = null; - } else { - const caseId = i32Stack.pop(); - optValue = caseId; - } + const elemCodec = { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const caseId = i32Stack.pop(); + return caseId; + }, + }; + const optValue = __bjs_optionalCodec(elemCodec).lift(); return { tag: TypedPayloadResultValues.Tag.OptDirection, param0: optValue }; } case TypedPayloadResultValues.Tag.Empty: return { tag: TypedPayloadResultValues.Tag.Empty }; @@ -588,10 +840,7 @@ export async function createInstantiator(options, swift) { return AllTypesResultValues.Tag.NestedEnum; } case AllTypesResultValues.Tag.ArrayPayload: { - for (const elem of value.param0) { - i32Stack.push((elem | 0)); - } - i32Stack.push(value.param0.length); + __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lower(value.param0); return AllTypesResultValues.Tag.ArrayPayload; } case AllTypesResultValues.Tag.Empty: { @@ -623,18 +872,7 @@ export async function createInstantiator(options, swift) { return { tag: AllTypesResultValues.Tag.NestedEnum, param0: enumValue }; } case AllTypesResultValues.Tag.ArrayPayload: { - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const int = i32Stack.pop(); - arrayResult.push(int); - } - arrayResult.reverse(); - } + const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lift(); return { tag: AllTypesResultValues.Tag.ArrayPayload, param0: arrayResult }; } case AllTypesResultValues.Tag.Empty: return { tag: AllTypesResultValues.Tag.Empty }; @@ -647,48 +885,45 @@ export async function createInstantiator(options, swift) { const enumTag = value.tag; switch (enumTag) { case OptionalAllTypesResultValues.Tag.OptStruct: { - const isSome = value.param0 != null ? 1 : 0; - if (isSome) { - structHelpers.Point.lower(value.param0); - } - i32Stack.push(isSome); + __bjs_optionalCodec(structHelpers.Point).lower(value.param0); return OptionalAllTypesResultValues.Tag.OptStruct; } case OptionalAllTypesResultValues.Tag.OptClass: { - const isSome = value.param0 != null ? 1 : 0; - if (isSome) { - ptrStack.push(value.param0.pointer); - } - i32Stack.push(isSome); + const elemCodec = { + lower: (v) => { + ptrStack.push(v.pointer); + }, + lift: () => { + const ptr = ptrStack.pop(); + const obj = _exports['User'].__construct(ptr); + return obj; + }, + }; + __bjs_optionalCodec(elemCodec).lower(value.param0); return OptionalAllTypesResultValues.Tag.OptClass; } case OptionalAllTypesResultValues.Tag.OptJSObject: { - const isSome = value.param0 != null ? 1 : 0; - if (isSome) { - const objId = swift.memory.retain(value.param0); - i32Stack.push(objId); - } - i32Stack.push(isSome); + const elemCodec = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + __bjs_optionalCodec(elemCodec).lower(value.param0); return OptionalAllTypesResultValues.Tag.OptJSObject; } case OptionalAllTypesResultValues.Tag.OptNestedEnum: { - const isSome = value.param0 != null ? 1 : 0; - if (isSome) { - const caseId = enumHelpers.APIResult.lower(value.param0); - i32Stack.push(caseId); - } - i32Stack.push(isSome); + __bjs_optionalCodec(__bjs_enumCodec(enumHelpers.APIResult)).lower(value.param0); return OptionalAllTypesResultValues.Tag.OptNestedEnum; } case OptionalAllTypesResultValues.Tag.OptArray: { - const isSome = value.param0 != null ? 1 : 0; - if (isSome) { - for (const elem of value.param0) { - i32Stack.push((elem | 0)); - } - i32Stack.push(value.param0.length); - } - i32Stack.push(isSome); + __bjs_optionalCodec(__bjs_arrayCodec(__bjs_primitiveCodecs.Int)).lower(value.param0); return OptionalAllTypesResultValues.Tag.OptArray; } case OptionalAllTypesResultValues.Tag.Empty: { @@ -701,72 +936,45 @@ export async function createInstantiator(options, swift) { tag = tag | 0; switch (tag) { case OptionalAllTypesResultValues.Tag.OptStruct: { - const isSome = i32Stack.pop(); - let optValue; - if (isSome === 0) { - optValue = null; - } else { - const struct = structHelpers.Point.lift(); - optValue = struct; - } + const optValue = __bjs_optionalCodec(structHelpers.Point).lift(); return { tag: OptionalAllTypesResultValues.Tag.OptStruct, param0: optValue }; } case OptionalAllTypesResultValues.Tag.OptClass: { - const isSome = i32Stack.pop(); - let optValue; - if (isSome === 0) { - optValue = null; - } else { - const ptr = ptrStack.pop(); - const obj = _exports['User'].__construct(ptr); - optValue = obj; - } + const elemCodec = { + lower: (v) => { + ptrStack.push(v.pointer); + }, + lift: () => { + const ptr = ptrStack.pop(); + const obj = _exports['User'].__construct(ptr); + return obj; + }, + }; + const optValue = __bjs_optionalCodec(elemCodec).lift(); return { tag: OptionalAllTypesResultValues.Tag.OptClass, param0: optValue }; } case OptionalAllTypesResultValues.Tag.OptJSObject: { - const isSome = i32Stack.pop(); - let optValue; - if (isSome === 0) { - optValue = null; - } else { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - optValue = obj; - } + const elemCodec = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + const optValue = __bjs_optionalCodec(elemCodec).lift(); return { tag: OptionalAllTypesResultValues.Tag.OptJSObject, param0: optValue }; } case OptionalAllTypesResultValues.Tag.OptNestedEnum: { - const isSome = i32Stack.pop(); - let optValue; - if (isSome === 0) { - optValue = null; - } else { - const enumValue = enumHelpers.APIResult.lift(i32Stack.pop()); - optValue = enumValue; - } + const optValue = __bjs_optionalCodec(__bjs_enumCodec(enumHelpers.APIResult)).lift(); return { tag: OptionalAllTypesResultValues.Tag.OptNestedEnum, param0: optValue }; } case OptionalAllTypesResultValues.Tag.OptArray: { - const isSome = i32Stack.pop(); - let optValue; - if (isSome === 0) { - optValue = null; - } else { - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const int = i32Stack.pop(); - arrayResult.push(int); - } - arrayResult.reverse(); - } - optValue = arrayResult; - } + const optValue = __bjs_optionalCodec(__bjs_arrayCodec(__bjs_primitiveCodecs.Int)).lift(); return { tag: OptionalAllTypesResultValues.Tag.OptArray, param0: optValue }; } case OptionalAllTypesResultValues.Tag.Empty: return { tag: OptionalAllTypesResultValues.Tag.Empty }; @@ -856,6 +1064,7 @@ export async function createInstantiator(options, swift) { const value = structHelpers.Point.lift(); return swift.memory.retain(value); } + bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.d.ts index d29256af4..c980b7dbf 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.d.ts @@ -35,5 +35,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js index de374bd70..a31c96450 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js @@ -150,6 +150,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.d.ts index 5581df31e..8ea0aa79b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.d.ts @@ -56,5 +56,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js index c2ae031bb..169ade160 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js @@ -130,6 +130,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.d.ts index fe48c9174..03e210f3c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.d.ts @@ -29,5 +29,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js index f2d6b8750..fa128130a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js @@ -111,6 +111,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.d.ts index 0ca8b16b9..403ef2149 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.d.ts @@ -154,5 +154,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js index 6c45f0333..859703175 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js @@ -150,6 +150,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.d.ts index b5a85a082..f5d357a64 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.d.ts @@ -115,5 +115,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js index 2a9e7948a..81c1eacd9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js @@ -131,6 +131,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.d.ts index fbd5ad637..e43673e7a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.d.ts @@ -169,5 +169,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js index 9e18a8d80..ac8dc0ff5 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js @@ -106,6 +106,316 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + function __bjs_arrayCodec(elementCodec) { + return { + lower(value) { + for (let i = 0; i < value.length; i++) { + elementCodec.lower(value[i]); + } + i32Stack.push(value.length); + }, + lift() { + const count = i32Stack.pop(); + if (count === -1) { + return taStack.pop(); + } + const result = new Array(count); + for (let i = count - 1; i >= 0; i--) { + result[i] = elementCodec.lift(); + } + return result; + }, + }; + } + function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { + return { + lower(value) { + const isSome = isUndefinedOr ? value !== undefined : value != null; + if (isSome) { + elementCodec.lower(value); + i32Stack.push(1); + } else { + i32Stack.push(0); + } + }, + lift() { + if (i32Stack.pop() === 0) { + return isUndefinedOr ? undefined : null; + } + return elementCodec.lift(); + }, + }; + } + function __bjs_dictCodec(valueCodec) { + return { + lower(value) { + const keys = Object.keys(value); + for (let i = 0; i < keys.length; i++) { + __bjs_stringCodec.lower(keys[i]); + valueCodec.lower(value[keys[i]]); + } + i32Stack.push(keys.length); + }, + lift() { + const count = i32Stack.pop(); + const result = {}; + for (let i = 0; i < count; i++) { + const value = valueCodec.lift(); + const key = __bjs_stringCodec.lift(); + result[key] = value; + } + return result; + }, + }; + } + function __bjs_enumCodec(helper) { + return { + lower(value) { + i32Stack.push(helper.lower(value)); + }, + lift() { + return helper.lift(i32Stack.pop()); + }, + }; + } + + const __bjs_stringCodec = { + lower: (v) => { + const bytes = textEncoder.encode(v); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + }, + lift: () => { + const string = strStack.pop(); + return string; + }, + }; + const __bjs_primitiveCodecs = { + Bool: { + lower: (v) => { + i32Stack.push(v ? 1 : 0); + }, + lift: () => { + const bool = i32Stack.pop() !== 0; + return bool; + }, + }, + Int: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + Int8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + UInt: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + UInt64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + Float: { + lower: (v) => { + f32Stack.push(Math.fround(v)); + }, + lift: () => { + const f32 = f32Stack.pop(); + return f32; + }, + }, + Double: { + lower: (v) => { + f64Stack.push(v); + }, + lift: () => { + const f64 = f64Stack.pop(); + return f64; + }, + }, + String: __bjs_stringCodec, + JSValue: { + lower: (v) => { + const [vKind, vPayload1, vPayload2] = __bjs_jsValueLower(v); + i32Stack.push(vKind); + i32Stack.push(vPayload1); + f64Stack.push(vPayload2); + }, + lift: () => { + const jsValuePayload2 = f64Stack.pop(); + const jsValuePayload1 = i32Stack.pop(); + const jsValueKind = i32Stack.pop(); + const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + return jsValue; + }, + }, + }; + + function __bjs_jsValueLower(value) { + let kind; + let payload1; + let payload2; + if (value === null) { + kind = 4; + payload1 = 0; + payload2 = 0; + } else { + switch (typeof value) { + case "boolean": + kind = 0; + payload1 = value ? 1 : 0; + payload2 = 0; + break; + case "number": + kind = 2; + payload1 = 0; + payload2 = value; + break; + case "string": + kind = 1; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "undefined": + kind = 5; + payload1 = 0; + payload2 = 0; + break; + case "object": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "function": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "symbol": + kind = 7; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "bigint": + kind = 8; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + default: + throw new TypeError("Unsupported JSValue type"); + } + } + return [kind, payload1, payload2]; + } + function __bjs_jsValueLift(kind, payload1, payload2) { + let jsValue; + switch (kind) { + case 0: + jsValue = payload1 !== 0; + break; + case 1: + jsValue = swift.memory.getObject(payload1); + break; + case 2: + jsValue = payload2; + break; + case 3: + jsValue = swift.memory.getObject(payload1); + break; + case 4: + jsValue = null; + break; + case 5: + jsValue = undefined; + break; + case 7: + jsValue = swift.memory.getObject(payload1); + break; + case 8: + jsValue = swift.memory.getObject(payload1); + break; + default: + throw new TypeError("Unsupported JSValue kind " + kind); + } + return jsValue; + } + return { /** @@ -182,6 +492,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; @@ -448,15 +759,17 @@ export async function createInstantiator(options, swift) { roundTripOptionalFileSize: function bjs_roundTripOptionalFileSize(input) { const isSome = input != null; instance.exports.bjs_roundTripOptionalFileSize(+isSome, isSome ? input : 0n); - const isSome1 = i32Stack.pop(); - let optResult; - if (isSome1) { - const rawValue = i64Stack.pop(); - optResult = rawValue; - } else { - optResult = null; - } - return optResult; + const elemCodec = { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const rawValue = i64Stack.pop(); + return rawValue; + }, + }; + const optValue = __bjs_optionalCodec(elemCodec).lift(); + return optValue; }, setUserId: function bjs_setUserId(id) { instance.exports.bjs_setUserId(id); @@ -496,15 +809,17 @@ export async function createInstantiator(options, swift) { roundTripOptionalSessionId: function bjs_roundTripOptionalSessionId(input) { const isSome = input != null; instance.exports.bjs_roundTripOptionalSessionId(+isSome, isSome ? input : 0n); - const isSome1 = i32Stack.pop(); - let optResult; - if (isSome1) { - const rawValue = i64Stack.pop(); - optResult = rawValue; - } else { - optResult = null; - } - return optResult; + const elemCodec = { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const rawValue = i64Stack.pop(); + return rawValue; + }, + }; + const optValue = __bjs_optionalCodec(elemCodec).lift(); + return optValue; }, setPrecision: function bjs_setPrecision(precision) { instance.exports.bjs_setPrecision(precision); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.d.ts index d6ab5aa8f..3eea52594 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.d.ts @@ -29,5 +29,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.d.ts index 312f56786..e4754d8e0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.d.ts @@ -17,5 +17,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.d.ts index ae1152016..0dbdafe7b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.d.ts @@ -19,5 +19,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.d.ts index 02d17c011..64acfac35 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.d.ts @@ -38,5 +38,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.d.ts index 02d17c011..64acfac35 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.d.ts @@ -38,5 +38,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.d.ts index 02d17c011..64acfac35 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.d.ts @@ -38,5 +38,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.d.ts index cd4f822e2..e0da68c50 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.d.ts @@ -17,5 +17,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js index 07341894e..bf1707b56 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js @@ -31,6 +31,316 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + function __bjs_arrayCodec(elementCodec) { + return { + lower(value) { + for (let i = 0; i < value.length; i++) { + elementCodec.lower(value[i]); + } + i32Stack.push(value.length); + }, + lift() { + const count = i32Stack.pop(); + if (count === -1) { + return taStack.pop(); + } + const result = new Array(count); + for (let i = count - 1; i >= 0; i--) { + result[i] = elementCodec.lift(); + } + return result; + }, + }; + } + function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { + return { + lower(value) { + const isSome = isUndefinedOr ? value !== undefined : value != null; + if (isSome) { + elementCodec.lower(value); + i32Stack.push(1); + } else { + i32Stack.push(0); + } + }, + lift() { + if (i32Stack.pop() === 0) { + return isUndefinedOr ? undefined : null; + } + return elementCodec.lift(); + }, + }; + } + function __bjs_dictCodec(valueCodec) { + return { + lower(value) { + const keys = Object.keys(value); + for (let i = 0; i < keys.length; i++) { + __bjs_stringCodec.lower(keys[i]); + valueCodec.lower(value[keys[i]]); + } + i32Stack.push(keys.length); + }, + lift() { + const count = i32Stack.pop(); + const result = {}; + for (let i = 0; i < count; i++) { + const value = valueCodec.lift(); + const key = __bjs_stringCodec.lift(); + result[key] = value; + } + return result; + }, + }; + } + function __bjs_enumCodec(helper) { + return { + lower(value) { + i32Stack.push(helper.lower(value)); + }, + lift() { + return helper.lift(i32Stack.pop()); + }, + }; + } + + const __bjs_stringCodec = { + lower: (v) => { + const bytes = textEncoder.encode(v); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + }, + lift: () => { + const string = strStack.pop(); + return string; + }, + }; + const __bjs_primitiveCodecs = { + Bool: { + lower: (v) => { + i32Stack.push(v ? 1 : 0); + }, + lift: () => { + const bool = i32Stack.pop() !== 0; + return bool; + }, + }, + Int: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + Int8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + UInt: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + UInt64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + Float: { + lower: (v) => { + f32Stack.push(Math.fround(v)); + }, + lift: () => { + const f32 = f32Stack.pop(); + return f32; + }, + }, + Double: { + lower: (v) => { + f64Stack.push(v); + }, + lift: () => { + const f64 = f64Stack.pop(); + return f64; + }, + }, + String: __bjs_stringCodec, + JSValue: { + lower: (v) => { + const [vKind, vPayload1, vPayload2] = __bjs_jsValueLower(v); + i32Stack.push(vKind); + i32Stack.push(vPayload1); + f64Stack.push(vPayload2); + }, + lift: () => { + const jsValuePayload2 = f64Stack.pop(); + const jsValuePayload1 = i32Stack.pop(); + const jsValueKind = i32Stack.pop(); + const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + return jsValue; + }, + }, + }; + + function __bjs_jsValueLower(value) { + let kind; + let payload1; + let payload2; + if (value === null) { + kind = 4; + payload1 = 0; + payload2 = 0; + } else { + switch (typeof value) { + case "boolean": + kind = 0; + payload1 = value ? 1 : 0; + payload2 = 0; + break; + case "number": + kind = 2; + payload1 = 0; + payload2 = value; + break; + case "string": + kind = 1; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "undefined": + kind = 5; + payload1 = 0; + payload2 = 0; + break; + case "object": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "function": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "symbol": + kind = 7; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "bigint": + kind = 8; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + default: + throw new TypeError("Unsupported JSValue type"); + } + } + return [kind, payload1, payload2]; + } + function __bjs_jsValueLift(kind, payload1, payload2) { + let jsValue; + switch (kind) { + case 0: + jsValue = payload1 !== 0; + break; + case 1: + jsValue = swift.memory.getObject(payload1); + break; + case 2: + jsValue = payload2; + break; + case 3: + jsValue = swift.memory.getObject(payload1); + break; + case 4: + jsValue = null; + break; + case 5: + jsValue = undefined; + break; + case 7: + jsValue = swift.memory.getObject(payload1); + break; + case 8: + jsValue = swift.memory.getObject(payload1); + break; + default: + throw new TypeError("Unsupported JSValue kind " + kind); + } + return jsValue; + } + return { /** @@ -207,41 +517,16 @@ export async function createInstantiator(options, swift) { const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; TestModule["bjs_roundtrip"] = function bjs_roundtrip() { try { - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const int = i32Stack.pop(); - arrayResult.push(int); - } - arrayResult.reverse(); - } + const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lift(); let ret = imports.roundtrip(arrayResult); - for (const elem of ret) { - i32Stack.push((elem | 0)); - } - i32Stack.push(ret.length); + __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lower(ret); } catch (error) { setException(error); } } TestModule["bjs_logStrings"] = function bjs_logStrings() { try { - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const string = strStack.pop(); - arrayResult.push(string); - } - arrayResult.reverse(); - } + const arrayResult = __bjs_arrayCodec(__bjs_stringCodec).lift(); imports.logStrings(arrayResult); } catch (error) { setException(error); @@ -251,34 +536,12 @@ export async function createInstantiator(options, swift) { try { let optResult; if (a) { - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const int = i32Stack.pop(); - arrayResult.push(int); - } - arrayResult.reverse(); - } + const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lift(); optResult = arrayResult; } else { optResult = null; } - const arrayLen1 = i32Stack.pop(); - let arrayResult1; - if (arrayLen1 === -1) { - arrayResult1 = taStack.pop(); - } else { - arrayResult1 = []; - for (let i1 = 0; i1 < arrayLen1; i1++) { - const int1 = i32Stack.pop(); - arrayResult1.push(int1); - } - arrayResult1.reverse(); - } + const arrayResult1 = __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lift(); let ret = imports.optionalArrayThenArray(optResult, arrayResult1); return ret; } catch (error) { @@ -291,34 +554,12 @@ export async function createInstantiator(options, swift) { const string = decodeString(sBytes, sCount); let optResult; if (a) { - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const int = i32Stack.pop(); - arrayResult.push(int); - } - arrayResult.reverse(); - } + const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lift(); optResult = arrayResult; } else { optResult = null; } - const arrayLen1 = i32Stack.pop(); - let arrayResult1; - if (arrayLen1 === -1) { - arrayResult1 = taStack.pop(); - } else { - arrayResult1 = []; - for (let i1 = 0; i1 < arrayLen1; i1++) { - const int1 = i32Stack.pop(); - arrayResult1.push(int1); - } - arrayResult1.reverse(); - } + const arrayResult1 = __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lift(); let ret = imports.borrowedStringAroundStackParams(string, optResult, arrayResult1); return ret; } catch (error) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.d.ts index 22b4e6a1c..1d5f31efd 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.d.ts @@ -26,5 +26,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js index 4328e4d4e..8974e3722 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js @@ -31,6 +31,316 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + function __bjs_arrayCodec(elementCodec) { + return { + lower(value) { + for (let i = 0; i < value.length; i++) { + elementCodec.lower(value[i]); + } + i32Stack.push(value.length); + }, + lift() { + const count = i32Stack.pop(); + if (count === -1) { + return taStack.pop(); + } + const result = new Array(count); + for (let i = count - 1; i >= 0; i--) { + result[i] = elementCodec.lift(); + } + return result; + }, + }; + } + function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { + return { + lower(value) { + const isSome = isUndefinedOr ? value !== undefined : value != null; + if (isSome) { + elementCodec.lower(value); + i32Stack.push(1); + } else { + i32Stack.push(0); + } + }, + lift() { + if (i32Stack.pop() === 0) { + return isUndefinedOr ? undefined : null; + } + return elementCodec.lift(); + }, + }; + } + function __bjs_dictCodec(valueCodec) { + return { + lower(value) { + const keys = Object.keys(value); + for (let i = 0; i < keys.length; i++) { + __bjs_stringCodec.lower(keys[i]); + valueCodec.lower(value[keys[i]]); + } + i32Stack.push(keys.length); + }, + lift() { + const count = i32Stack.pop(); + const result = {}; + for (let i = 0; i < count; i++) { + const value = valueCodec.lift(); + const key = __bjs_stringCodec.lift(); + result[key] = value; + } + return result; + }, + }; + } + function __bjs_enumCodec(helper) { + return { + lower(value) { + i32Stack.push(helper.lower(value)); + }, + lift() { + return helper.lift(i32Stack.pop()); + }, + }; + } + + const __bjs_stringCodec = { + lower: (v) => { + const bytes = textEncoder.encode(v); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + }, + lift: () => { + const string = strStack.pop(); + return string; + }, + }; + const __bjs_primitiveCodecs = { + Bool: { + lower: (v) => { + i32Stack.push(v ? 1 : 0); + }, + lift: () => { + const bool = i32Stack.pop() !== 0; + return bool; + }, + }, + Int: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + Int8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + UInt: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + UInt64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + Float: { + lower: (v) => { + f32Stack.push(Math.fround(v)); + }, + lift: () => { + const f32 = f32Stack.pop(); + return f32; + }, + }, + Double: { + lower: (v) => { + f64Stack.push(v); + }, + lift: () => { + const f64 = f64Stack.pop(); + return f64; + }, + }, + String: __bjs_stringCodec, + JSValue: { + lower: (v) => { + const [vKind, vPayload1, vPayload2] = __bjs_jsValueLower(v); + i32Stack.push(vKind); + i32Stack.push(vPayload1); + f64Stack.push(vPayload2); + }, + lift: () => { + const jsValuePayload2 = f64Stack.pop(); + const jsValuePayload1 = i32Stack.pop(); + const jsValueKind = i32Stack.pop(); + const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + return jsValue; + }, + }, + }; + + function __bjs_jsValueLower(value) { + let kind; + let payload1; + let payload2; + if (value === null) { + kind = 4; + payload1 = 0; + payload2 = 0; + } else { + switch (typeof value) { + case "boolean": + kind = 0; + payload1 = value ? 1 : 0; + payload2 = 0; + break; + case "number": + kind = 2; + payload1 = 0; + payload2 = value; + break; + case "string": + kind = 1; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "undefined": + kind = 5; + payload1 = 0; + payload2 = 0; + break; + case "object": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "function": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "symbol": + kind = 7; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "bigint": + kind = 8; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + default: + throw new TypeError("Unsupported JSValue type"); + } + } + return [kind, payload1, payload2]; + } + function __bjs_jsValueLift(kind, payload1, payload2) { + let jsValue; + switch (kind) { + case 0: + jsValue = payload1 !== 0; + break; + case 1: + jsValue = swift.memory.getObject(payload1); + break; + case 2: + jsValue = payload2; + break; + case 3: + jsValue = swift.memory.getObject(payload1); + break; + case 4: + jsValue = null; + break; + case 5: + jsValue = undefined; + break; + case 7: + jsValue = swift.memory.getObject(payload1); + break; + case 8: + jsValue = swift.memory.getObject(payload1); + break; + default: + throw new TypeError("Unsupported JSValue kind " + kind); + } + return jsValue; + } + const __bjs_createFooContainerHelpers = () => ({ lower: (value) => { let id; @@ -40,24 +350,34 @@ export async function createInstantiator(options, swift) { id = undefined; } i32Stack.push(id !== undefined ? id : 0); - const isSome = value.optionalFoo != null ? 1 : 0; - if (isSome) { - const objId = swift.memory.retain(value.optionalFoo); - i32Stack.push(objId); - } - i32Stack.push(isSome); + const elemCodec = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + __bjs_optionalCodec(elemCodec).lower(value.optionalFoo); }, lift: () => { - const isSome = i32Stack.pop(); - let optValue; - if (isSome === 0) { - optValue = null; - } else { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - optValue = obj; - } + const elemCodec = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + const optValue = __bjs_optionalCodec(elemCodec).lift(); const objectId = i32Stack.pop(); let value; if (objectId !== 0) { @@ -152,6 +472,7 @@ export async function createInstantiator(options, swift) { const value = structHelpers.FooContainer.lift(); return swift.memory.retain(value); } + bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; @@ -289,60 +610,63 @@ export async function createInstantiator(options, swift) { return ret1; }, processFooArray: function bjs_processFooArray(foos) { - for (const elem of foos) { - const objId = swift.memory.retain(elem); - i32Stack.push(objId); - } - i32Stack.push(foos.length); + const elemCodec = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + __bjs_arrayCodec(elemCodec).lower(foos); instance.exports.bjs_processFooArray(); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const objId1 = i32Stack.pop(); - const obj = swift.memory.getObject(objId1); - swift.memory.release(objId1); - arrayResult.push(obj); - } - arrayResult.reverse(); - } + const elemCodec1 = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + const arrayResult = __bjs_arrayCodec(elemCodec1).lift(); return arrayResult; }, processOptionalFooArray: function bjs_processOptionalFooArray(foos) { - for (const elem of foos) { - const isSome = elem != null ? 1 : 0; - if (isSome) { - const objId = swift.memory.retain(elem); + const elemCodec = { + lower: (v) => { + const objId = swift.memory.retain(v); i32Stack.push(objId); - } - i32Stack.push(isSome); - } - i32Stack.push(foos.length); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + __bjs_arrayCodec(__bjs_optionalCodec(elemCodec)).lower(foos); instance.exports.bjs_processOptionalFooArray(); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const isSome1 = i32Stack.pop(); - let optValue; - if (isSome1 === 0) { - optValue = null; - } else { - const objId1 = i32Stack.pop(); - const obj = swift.memory.getObject(objId1); - swift.memory.release(objId1); - optValue = obj; - } - arrayResult.push(optValue); - } - arrayResult.reverse(); - } + const elemCodec1 = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + const arrayResult = __bjs_arrayCodec(__bjs_optionalCodec(elemCodec1)).lift(); return arrayResult; }, roundtripFooContainer: function bjs_roundtripFooContainer(container) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.d.ts index ac0e05a91..edc243baa 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.d.ts @@ -33,5 +33,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.d.ts index aaf227cf7..e6dfad7fa 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.d.ts @@ -27,5 +27,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.d.ts index 3b2b5de99..3cb232260 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.d.ts @@ -28,5 +28,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModule.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModule.d.ts index a6267bd31..b0c2eff74 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModule.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModule.d.ts @@ -17,5 +17,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModuleFallback.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModuleFallback.d.ts index 818d57a9d..e9f73cfae 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModuleFallback.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModuleFallback.d.ts @@ -13,5 +13,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.d.ts index 624691d83..9afd16f74 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.d.ts @@ -17,5 +17,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.d.ts index d31aeebe3..d6cbf725c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.d.ts @@ -64,5 +64,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.js index 543ae05f0..026acf3f4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.js @@ -135,6 +135,7 @@ export async function createInstantiator(options, swift) { const value = structHelpers.RenamedVector.lift(); return swift.memory.retain(value); } + bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.d.ts index b842e7d7d..c77ca0828 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.d.ts @@ -17,5 +17,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.d.ts index 85109479e..951f1e7aa 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.d.ts @@ -36,5 +36,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js index ae59008ba..f39091a1f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js @@ -31,6 +31,227 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + function __bjs_arrayCodec(elementCodec) { + return { + lower(value) { + for (let i = 0; i < value.length; i++) { + elementCodec.lower(value[i]); + } + i32Stack.push(value.length); + }, + lift() { + const count = i32Stack.pop(); + if (count === -1) { + return taStack.pop(); + } + const result = new Array(count); + for (let i = count - 1; i >= 0; i--) { + result[i] = elementCodec.lift(); + } + return result; + }, + }; + } + function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { + return { + lower(value) { + const isSome = isUndefinedOr ? value !== undefined : value != null; + if (isSome) { + elementCodec.lower(value); + i32Stack.push(1); + } else { + i32Stack.push(0); + } + }, + lift() { + if (i32Stack.pop() === 0) { + return isUndefinedOr ? undefined : null; + } + return elementCodec.lift(); + }, + }; + } + function __bjs_dictCodec(valueCodec) { + return { + lower(value) { + const keys = Object.keys(value); + for (let i = 0; i < keys.length; i++) { + __bjs_stringCodec.lower(keys[i]); + valueCodec.lower(value[keys[i]]); + } + i32Stack.push(keys.length); + }, + lift() { + const count = i32Stack.pop(); + const result = {}; + for (let i = 0; i < count; i++) { + const value = valueCodec.lift(); + const key = __bjs_stringCodec.lift(); + result[key] = value; + } + return result; + }, + }; + } + function __bjs_enumCodec(helper) { + return { + lower(value) { + i32Stack.push(helper.lower(value)); + }, + lift() { + return helper.lift(i32Stack.pop()); + }, + }; + } + + const __bjs_stringCodec = { + lower: (v) => { + const bytes = textEncoder.encode(v); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + }, + lift: () => { + const string = strStack.pop(); + return string; + }, + }; + const __bjs_primitiveCodecs = { + Bool: { + lower: (v) => { + i32Stack.push(v ? 1 : 0); + }, + lift: () => { + const bool = i32Stack.pop() !== 0; + return bool; + }, + }, + Int: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + Int8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + UInt: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + UInt64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + Float: { + lower: (v) => { + f32Stack.push(Math.fround(v)); + }, + lift: () => { + const f32 = f32Stack.pop(); + return f32; + }, + }, + Double: { + lower: (v) => { + f64Stack.push(v); + }, + lift: () => { + const f64 = f64Stack.pop(); + return f64; + }, + }, + String: __bjs_stringCodec, + JSValue: { + lower: (v) => { + const [vKind, vPayload1, vPayload2] = __bjs_jsValueLower(v); + i32Stack.push(vKind); + i32Stack.push(vPayload1); + f64Stack.push(vPayload2); + }, + lift: () => { + const jsValuePayload2 = f64Stack.pop(); + const jsValuePayload1 = i32Stack.pop(); + const jsValueKind = i32Stack.pop(); + const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + return jsValue; + }, + }, + }; + function __bjs_jsValueLower(value) { let kind; let payload1; @@ -316,29 +537,9 @@ export async function createInstantiator(options, swift) { } TestModule["bjs_jsEchoJSValueArray"] = function bjs_jsEchoJSValueArray() { try { - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const jsValuePayload2 = f64Stack.pop(); - const jsValuePayload1 = i32Stack.pop(); - const jsValueKind = i32Stack.pop(); - const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); - arrayResult.push(jsValue); - } - arrayResult.reverse(); - } + const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.JSValue).lift(); let ret = imports.jsEchoJSValueArray(arrayResult); - for (const elem of ret) { - const [elemKind, elemPayload1, elemPayload2] = __bjs_jsValueLower(elem); - i32Stack.push(elemKind); - i32Stack.push(elemPayload1); - f64Stack.push(elemPayload2); - } - i32Stack.push(ret.length); + __bjs_arrayCodec(__bjs_primitiveCodecs.JSValue).lower(ret); } catch (error) { setException(error); } @@ -564,67 +765,16 @@ export async function createInstantiator(options, swift) { return optResult; }, roundTripJSValueArray: function bjs_roundTripJSValueArray(values) { - for (const elem of values) { - const [elemKind, elemPayload1, elemPayload2] = __bjs_jsValueLower(elem); - i32Stack.push(elemKind); - i32Stack.push(elemPayload1); - f64Stack.push(elemPayload2); - } - i32Stack.push(values.length); + __bjs_arrayCodec(__bjs_primitiveCodecs.JSValue).lower(values); instance.exports.bjs_roundTripJSValueArray(); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const jsValuePayload2 = f64Stack.pop(); - const jsValuePayload1 = i32Stack.pop(); - const jsValueKind = i32Stack.pop(); - const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); - arrayResult.push(jsValue); - } - arrayResult.reverse(); - } + const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.JSValue).lift(); return arrayResult; }, roundTripOptionalJSValueArray: function bjs_roundTripOptionalJSValueArray(values) { - const isSome = values != null; - if (isSome) { - for (const elem of values) { - const [elemKind, elemPayload1, elemPayload2] = __bjs_jsValueLower(elem); - i32Stack.push(elemKind); - i32Stack.push(elemPayload1); - f64Stack.push(elemPayload2); - } - i32Stack.push(values.length); - } - i32Stack.push(+isSome); + __bjs_optionalCodec(__bjs_arrayCodec(__bjs_primitiveCodecs.JSValue)).lower(values); instance.exports.bjs_roundTripOptionalJSValueArray(); - const isSome1 = i32Stack.pop(); - let optResult; - if (isSome1) { - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const jsValuePayload2 = f64Stack.pop(); - const jsValuePayload1 = i32Stack.pop(); - const jsValueKind = i32Stack.pop(); - const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); - arrayResult.push(jsValue); - } - arrayResult.reverse(); - } - optResult = arrayResult; - } else { - optResult = null; - } - return optResult; + const optValue = __bjs_optionalCodec(__bjs_arrayCodec(__bjs_primitiveCodecs.JSValue)).lift(); + return optValue; }, JSValueHolder, }; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.d.ts index c7ff9a39c..737e94bce 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.d.ts @@ -29,5 +29,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.d.ts index 01a392e91..88d337296 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.d.ts @@ -51,5 +51,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.d.ts index 89aad5c32..634065017 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.d.ts @@ -29,5 +29,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.d.ts index ac9ea13c4..76daa290c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.d.ts @@ -126,5 +126,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js index aa5e3dbb4..fcb6dd88d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js @@ -31,6 +31,316 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + function __bjs_arrayCodec(elementCodec) { + return { + lower(value) { + for (let i = 0; i < value.length; i++) { + elementCodec.lower(value[i]); + } + i32Stack.push(value.length); + }, + lift() { + const count = i32Stack.pop(); + if (count === -1) { + return taStack.pop(); + } + const result = new Array(count); + for (let i = count - 1; i >= 0; i--) { + result[i] = elementCodec.lift(); + } + return result; + }, + }; + } + function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { + return { + lower(value) { + const isSome = isUndefinedOr ? value !== undefined : value != null; + if (isSome) { + elementCodec.lower(value); + i32Stack.push(1); + } else { + i32Stack.push(0); + } + }, + lift() { + if (i32Stack.pop() === 0) { + return isUndefinedOr ? undefined : null; + } + return elementCodec.lift(); + }, + }; + } + function __bjs_dictCodec(valueCodec) { + return { + lower(value) { + const keys = Object.keys(value); + for (let i = 0; i < keys.length; i++) { + __bjs_stringCodec.lower(keys[i]); + valueCodec.lower(value[keys[i]]); + } + i32Stack.push(keys.length); + }, + lift() { + const count = i32Stack.pop(); + const result = {}; + for (let i = 0; i < count; i++) { + const value = valueCodec.lift(); + const key = __bjs_stringCodec.lift(); + result[key] = value; + } + return result; + }, + }; + } + function __bjs_enumCodec(helper) { + return { + lower(value) { + i32Stack.push(helper.lower(value)); + }, + lift() { + return helper.lift(i32Stack.pop()); + }, + }; + } + + const __bjs_stringCodec = { + lower: (v) => { + const bytes = textEncoder.encode(v); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + }, + lift: () => { + const string = strStack.pop(); + return string; + }, + }; + const __bjs_primitiveCodecs = { + Bool: { + lower: (v) => { + i32Stack.push(v ? 1 : 0); + }, + lift: () => { + const bool = i32Stack.pop() !== 0; + return bool; + }, + }, + Int: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + Int8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + UInt: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + UInt64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + Float: { + lower: (v) => { + f32Stack.push(Math.fround(v)); + }, + lift: () => { + const f32 = f32Stack.pop(); + return f32; + }, + }, + Double: { + lower: (v) => { + f64Stack.push(v); + }, + lift: () => { + const f64 = f64Stack.pop(); + return f64; + }, + }, + String: __bjs_stringCodec, + JSValue: { + lower: (v) => { + const [vKind, vPayload1, vPayload2] = __bjs_jsValueLower(v); + i32Stack.push(vKind); + i32Stack.push(vPayload1); + f64Stack.push(vPayload2); + }, + lift: () => { + const jsValuePayload2 = f64Stack.pop(); + const jsValuePayload1 = i32Stack.pop(); + const jsValueKind = i32Stack.pop(); + const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + return jsValue; + }, + }, + }; + + function __bjs_jsValueLower(value) { + let kind; + let payload1; + let payload2; + if (value === null) { + kind = 4; + payload1 = 0; + payload2 = 0; + } else { + switch (typeof value) { + case "boolean": + kind = 0; + payload1 = value ? 1 : 0; + payload2 = 0; + break; + case "number": + kind = 2; + payload1 = 0; + payload2 = value; + break; + case "string": + kind = 1; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "undefined": + kind = 5; + payload1 = 0; + payload2 = 0; + break; + case "object": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "function": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "symbol": + kind = 7; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "bigint": + kind = 8; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + default: + throw new TypeError("Unsupported JSValue type"); + } + } + return [kind, payload1, payload2]; + } + function __bjs_jsValueLift(kind, payload1, payload2) { + let jsValue; + switch (kind) { + case 0: + jsValue = payload1 !== 0; + break; + case 1: + jsValue = swift.memory.getObject(payload1); + break; + case 2: + jsValue = payload2; + break; + case 3: + jsValue = swift.memory.getObject(payload1); + break; + case 4: + jsValue = null; + break; + case 5: + jsValue = undefined; + break; + case 7: + jsValue = swift.memory.getObject(payload1); + break; + case 8: + jsValue = swift.memory.getObject(payload1); + break; + default: + throw new TypeError("Unsupported JSValue kind " + kind); + } + return jsValue; + } + return { /** @@ -356,19 +666,17 @@ export async function createInstantiator(options, swift) { } getItems() { instance.exports.bjs_Collections_Container_getItems(this.pointer); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { + const elemCodec = { + lower: (v) => { + ptrStack.push(v.pointer); + }, + lift: () => { const ptr = ptrStack.pop(); const obj = Greeter.__construct(ptr); - arrayResult.push(obj); - } - arrayResult.reverse(); - } + return obj; + }, + }; + const arrayResult = __bjs_arrayCodec(elemCodec).lift(); return arrayResult; } addItem(item) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.d.ts index debd3ffcf..59961720b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.d.ts @@ -73,5 +73,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js index 9a5c6473e..ef083c4d7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js @@ -31,6 +31,316 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + function __bjs_arrayCodec(elementCodec) { + return { + lower(value) { + for (let i = 0; i < value.length; i++) { + elementCodec.lower(value[i]); + } + i32Stack.push(value.length); + }, + lift() { + const count = i32Stack.pop(); + if (count === -1) { + return taStack.pop(); + } + const result = new Array(count); + for (let i = count - 1; i >= 0; i--) { + result[i] = elementCodec.lift(); + } + return result; + }, + }; + } + function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { + return { + lower(value) { + const isSome = isUndefinedOr ? value !== undefined : value != null; + if (isSome) { + elementCodec.lower(value); + i32Stack.push(1); + } else { + i32Stack.push(0); + } + }, + lift() { + if (i32Stack.pop() === 0) { + return isUndefinedOr ? undefined : null; + } + return elementCodec.lift(); + }, + }; + } + function __bjs_dictCodec(valueCodec) { + return { + lower(value) { + const keys = Object.keys(value); + for (let i = 0; i < keys.length; i++) { + __bjs_stringCodec.lower(keys[i]); + valueCodec.lower(value[keys[i]]); + } + i32Stack.push(keys.length); + }, + lift() { + const count = i32Stack.pop(); + const result = {}; + for (let i = 0; i < count; i++) { + const value = valueCodec.lift(); + const key = __bjs_stringCodec.lift(); + result[key] = value; + } + return result; + }, + }; + } + function __bjs_enumCodec(helper) { + return { + lower(value) { + i32Stack.push(helper.lower(value)); + }, + lift() { + return helper.lift(i32Stack.pop()); + }, + }; + } + + const __bjs_stringCodec = { + lower: (v) => { + const bytes = textEncoder.encode(v); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + }, + lift: () => { + const string = strStack.pop(); + return string; + }, + }; + const __bjs_primitiveCodecs = { + Bool: { + lower: (v) => { + i32Stack.push(v ? 1 : 0); + }, + lift: () => { + const bool = i32Stack.pop() !== 0; + return bool; + }, + }, + Int: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + Int8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + UInt: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + UInt64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + Float: { + lower: (v) => { + f32Stack.push(Math.fround(v)); + }, + lift: () => { + const f32 = f32Stack.pop(); + return f32; + }, + }, + Double: { + lower: (v) => { + f64Stack.push(v); + }, + lift: () => { + const f64 = f64Stack.pop(); + return f64; + }, + }, + String: __bjs_stringCodec, + JSValue: { + lower: (v) => { + const [vKind, vPayload1, vPayload2] = __bjs_jsValueLower(v); + i32Stack.push(vKind); + i32Stack.push(vPayload1); + f64Stack.push(vPayload2); + }, + lift: () => { + const jsValuePayload2 = f64Stack.pop(); + const jsValuePayload1 = i32Stack.pop(); + const jsValueKind = i32Stack.pop(); + const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + return jsValue; + }, + }, + }; + + function __bjs_jsValueLower(value) { + let kind; + let payload1; + let payload2; + if (value === null) { + kind = 4; + payload1 = 0; + payload2 = 0; + } else { + switch (typeof value) { + case "boolean": + kind = 0; + payload1 = value ? 1 : 0; + payload2 = 0; + break; + case "number": + kind = 2; + payload1 = 0; + payload2 = value; + break; + case "string": + kind = 1; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "undefined": + kind = 5; + payload1 = 0; + payload2 = 0; + break; + case "object": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "function": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "symbol": + kind = 7; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "bigint": + kind = 8; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + default: + throw new TypeError("Unsupported JSValue type"); + } + } + return [kind, payload1, payload2]; + } + function __bjs_jsValueLift(kind, payload1, payload2) { + let jsValue; + switch (kind) { + case 0: + jsValue = payload1 !== 0; + break; + case 1: + jsValue = swift.memory.getObject(payload1); + break; + case 2: + jsValue = payload2; + break; + case 3: + jsValue = swift.memory.getObject(payload1); + break; + case 4: + jsValue = null; + break; + case 5: + jsValue = undefined; + break; + case 7: + jsValue = swift.memory.getObject(payload1); + break; + case 8: + jsValue = swift.memory.getObject(payload1); + break; + default: + throw new TypeError("Unsupported JSValue kind " + kind); + } + return jsValue; + } + return { /** @@ -356,19 +666,17 @@ export async function createInstantiator(options, swift) { } getItems() { instance.exports.bjs_Collections_Container_getItems(this.pointer); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { + const elemCodec = { + lower: (v) => { + ptrStack.push(v.pointer); + }, + lift: () => { const ptr = ptrStack.pop(); const obj = Greeter.__construct(ptr); - arrayResult.push(obj); - } - arrayResult.reverse(); - } + return obj; + }, + }; + const arrayResult = __bjs_arrayCodec(elemCodec).lift(); return arrayResult; } addItem(item) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.d.ts index c418ed8a5..5dfb48fcf 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.d.ts @@ -42,5 +42,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js index 972f9ae74..e03b09221 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js @@ -145,6 +145,7 @@ export async function createInstantiator(options, swift) { const value = structHelpers.Player_Stats.lift(); return swift.memory.retain(value); } + bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.d.ts index 0f64324cd..324947e18 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.d.ts @@ -82,5 +82,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js index 5a253cdc0..0a4fcc28c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js @@ -31,6 +31,316 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + function __bjs_arrayCodec(elementCodec) { + return { + lower(value) { + for (let i = 0; i < value.length; i++) { + elementCodec.lower(value[i]); + } + i32Stack.push(value.length); + }, + lift() { + const count = i32Stack.pop(); + if (count === -1) { + return taStack.pop(); + } + const result = new Array(count); + for (let i = count - 1; i >= 0; i--) { + result[i] = elementCodec.lift(); + } + return result; + }, + }; + } + function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { + return { + lower(value) { + const isSome = isUndefinedOr ? value !== undefined : value != null; + if (isSome) { + elementCodec.lower(value); + i32Stack.push(1); + } else { + i32Stack.push(0); + } + }, + lift() { + if (i32Stack.pop() === 0) { + return isUndefinedOr ? undefined : null; + } + return elementCodec.lift(); + }, + }; + } + function __bjs_dictCodec(valueCodec) { + return { + lower(value) { + const keys = Object.keys(value); + for (let i = 0; i < keys.length; i++) { + __bjs_stringCodec.lower(keys[i]); + valueCodec.lower(value[keys[i]]); + } + i32Stack.push(keys.length); + }, + lift() { + const count = i32Stack.pop(); + const result = {}; + for (let i = 0; i < count; i++) { + const value = valueCodec.lift(); + const key = __bjs_stringCodec.lift(); + result[key] = value; + } + return result; + }, + }; + } + function __bjs_enumCodec(helper) { + return { + lower(value) { + i32Stack.push(helper.lower(value)); + }, + lift() { + return helper.lift(i32Stack.pop()); + }, + }; + } + + const __bjs_stringCodec = { + lower: (v) => { + const bytes = textEncoder.encode(v); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + }, + lift: () => { + const string = strStack.pop(); + return string; + }, + }; + const __bjs_primitiveCodecs = { + Bool: { + lower: (v) => { + i32Stack.push(v ? 1 : 0); + }, + lift: () => { + const bool = i32Stack.pop() !== 0; + return bool; + }, + }, + Int: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + Int8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + UInt: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + UInt64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + Float: { + lower: (v) => { + f32Stack.push(Math.fround(v)); + }, + lift: () => { + const f32 = f32Stack.pop(); + return f32; + }, + }, + Double: { + lower: (v) => { + f64Stack.push(v); + }, + lift: () => { + const f64 = f64Stack.pop(); + return f64; + }, + }, + String: __bjs_stringCodec, + JSValue: { + lower: (v) => { + const [vKind, vPayload1, vPayload2] = __bjs_jsValueLower(v); + i32Stack.push(vKind); + i32Stack.push(vPayload1); + f64Stack.push(vPayload2); + }, + lift: () => { + const jsValuePayload2 = f64Stack.pop(); + const jsValuePayload1 = i32Stack.pop(); + const jsValueKind = i32Stack.pop(); + const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + return jsValue; + }, + }, + }; + + function __bjs_jsValueLower(value) { + let kind; + let payload1; + let payload2; + if (value === null) { + kind = 4; + payload1 = 0; + payload2 = 0; + } else { + switch (typeof value) { + case "boolean": + kind = 0; + payload1 = value ? 1 : 0; + payload2 = 0; + break; + case "number": + kind = 2; + payload1 = 0; + payload2 = value; + break; + case "string": + kind = 1; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "undefined": + kind = 5; + payload1 = 0; + payload2 = 0; + break; + case "object": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "function": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "symbol": + kind = 7; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "bigint": + kind = 8; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + default: + throw new TypeError("Unsupported JSValue type"); + } + } + return [kind, payload1, payload2]; + } + function __bjs_jsValueLift(kind, payload1, payload2) { + let jsValue; + switch (kind) { + case 0: + jsValue = payload1 !== 0; + break; + case 1: + jsValue = swift.memory.getObject(payload1); + break; + case 2: + jsValue = payload2; + break; + case 3: + jsValue = swift.memory.getObject(payload1); + break; + case 4: + jsValue = null; + break; + case 5: + jsValue = undefined; + break; + case 7: + jsValue = swift.memory.getObject(payload1); + break; + case 8: + jsValue = swift.memory.getObject(payload1); + break; + default: + throw new TypeError("Unsupported JSValue kind " + kind); + } + return jsValue; + } + return { /** @@ -314,12 +624,19 @@ export async function createInstantiator(options, swift) { TestModule["bjs_WithOptionalJSClass_childOrNull_get"] = function bjs_WithOptionalJSClass_childOrNull_get(self) { try { let ret = swift.memory.getObject(self).childOrNull; - const isSome = ret != null; - if (isSome) { - const objId = swift.memory.retain(ret); - i32Stack.push(objId); - } - i32Stack.push(isSome ? 1 : 0); + const elemCodec = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + __bjs_optionalCodec(elemCodec).lower(ret); } catch (error) { setException(error); } @@ -490,12 +807,19 @@ export async function createInstantiator(options, swift) { TestModule["bjs_WithOptionalJSClass_roundTripChildOrNull"] = function bjs_WithOptionalJSClass_roundTripChildOrNull(self, valueIsSome, valueObjectId) { try { let ret = swift.memory.getObject(self).roundTripChildOrNull(valueIsSome ? swift.memory.getObject(valueObjectId) : null); - const isSome = ret != null; - if (isSome) { - const objId = swift.memory.retain(ret); - i32Stack.push(objId); - } - i32Stack.push(isSome ? 1 : 0); + const elemCodec = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + __bjs_optionalCodec(elemCodec).lower(ret); } catch (error) { setException(error); } @@ -722,17 +1046,20 @@ export async function createInstantiator(options, swift) { result = 0; } instance.exports.bjs_roundTripExportedOptionalJSObject(+isSome, result); - const isSome1 = i32Stack.pop(); - let optResult; - if (isSome1) { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - optResult = obj; - } else { - optResult = null; - } - return optResult; + const elemCodec = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + const optValue = __bjs_optionalCodec(elemCodec).lift(); + return optValue; }, roundTripExportedOptionalJSClass: function bjs_roundTripExportedOptionalJSClass(value) { const isSome = value != null; @@ -743,17 +1070,20 @@ export async function createInstantiator(options, swift) { result = 0; } instance.exports.bjs_roundTripExportedOptionalJSClass(+isSome, result); - const isSome1 = i32Stack.pop(); - let optResult; - if (isSome1) { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - optResult = obj; - } else { - optResult = null; - } - return optResult; + const elemCodec = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + const optValue = __bjs_optionalCodec(elemCodec).lift(); + return optValue; }, roundTripString: function bjs_roundTripString(name) { const isSome = name != null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.d.ts index 961f97635..19680ec06 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.d.ts @@ -15,5 +15,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.d.ts index 77e269d16..a28a7b4bb 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.d.ts @@ -20,5 +20,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.d.ts index 5872a3020..d7cd0e2e6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.d.ts @@ -44,5 +44,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.d.ts index a413fa500..f55109d2b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.d.ts @@ -119,5 +119,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js index b2a894ffa..e2c711f8f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js @@ -55,6 +55,316 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + function __bjs_arrayCodec(elementCodec) { + return { + lower(value) { + for (let i = 0; i < value.length; i++) { + elementCodec.lower(value[i]); + } + i32Stack.push(value.length); + }, + lift() { + const count = i32Stack.pop(); + if (count === -1) { + return taStack.pop(); + } + const result = new Array(count); + for (let i = count - 1; i >= 0; i--) { + result[i] = elementCodec.lift(); + } + return result; + }, + }; + } + function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { + return { + lower(value) { + const isSome = isUndefinedOr ? value !== undefined : value != null; + if (isSome) { + elementCodec.lower(value); + i32Stack.push(1); + } else { + i32Stack.push(0); + } + }, + lift() { + if (i32Stack.pop() === 0) { + return isUndefinedOr ? undefined : null; + } + return elementCodec.lift(); + }, + }; + } + function __bjs_dictCodec(valueCodec) { + return { + lower(value) { + const keys = Object.keys(value); + for (let i = 0; i < keys.length; i++) { + __bjs_stringCodec.lower(keys[i]); + valueCodec.lower(value[keys[i]]); + } + i32Stack.push(keys.length); + }, + lift() { + const count = i32Stack.pop(); + const result = {}; + for (let i = 0; i < count; i++) { + const value = valueCodec.lift(); + const key = __bjs_stringCodec.lift(); + result[key] = value; + } + return result; + }, + }; + } + function __bjs_enumCodec(helper) { + return { + lower(value) { + i32Stack.push(helper.lower(value)); + }, + lift() { + return helper.lift(i32Stack.pop()); + }, + }; + } + + const __bjs_stringCodec = { + lower: (v) => { + const bytes = textEncoder.encode(v); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + }, + lift: () => { + const string = strStack.pop(); + return string; + }, + }; + const __bjs_primitiveCodecs = { + Bool: { + lower: (v) => { + i32Stack.push(v ? 1 : 0); + }, + lift: () => { + const bool = i32Stack.pop() !== 0; + return bool; + }, + }, + Int: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + Int8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + UInt: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + UInt64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + Float: { + lower: (v) => { + f32Stack.push(Math.fround(v)); + }, + lift: () => { + const f32 = f32Stack.pop(); + return f32; + }, + }, + Double: { + lower: (v) => { + f64Stack.push(v); + }, + lift: () => { + const f64 = f64Stack.pop(); + return f64; + }, + }, + String: __bjs_stringCodec, + JSValue: { + lower: (v) => { + const [vKind, vPayload1, vPayload2] = __bjs_jsValueLower(v); + i32Stack.push(vKind); + i32Stack.push(vPayload1); + f64Stack.push(vPayload2); + }, + lift: () => { + const jsValuePayload2 = f64Stack.pop(); + const jsValuePayload1 = i32Stack.pop(); + const jsValueKind = i32Stack.pop(); + const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + return jsValue; + }, + }, + }; + + function __bjs_jsValueLower(value) { + let kind; + let payload1; + let payload2; + if (value === null) { + kind = 4; + payload1 = 0; + payload2 = 0; + } else { + switch (typeof value) { + case "boolean": + kind = 0; + payload1 = value ? 1 : 0; + payload2 = 0; + break; + case "number": + kind = 2; + payload1 = 0; + payload2 = value; + break; + case "string": + kind = 1; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "undefined": + kind = 5; + payload1 = 0; + payload2 = 0; + break; + case "object": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "function": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "symbol": + kind = 7; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "bigint": + kind = 8; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + default: + throw new TypeError("Unsupported JSValue type"); + } + } + return [kind, payload1, payload2]; + } + function __bjs_jsValueLift(kind, payload1, payload2) { + let jsValue; + switch (kind) { + case 0: + jsValue = payload1 !== 0; + break; + case 1: + jsValue = swift.memory.getObject(payload1); + break; + case 2: + jsValue = payload2; + break; + case 3: + jsValue = swift.memory.getObject(payload1); + break; + case 4: + jsValue = null; + break; + case 5: + jsValue = undefined; + break; + case 7: + jsValue = swift.memory.getObject(payload1); + break; + case 8: + jsValue = swift.memory.getObject(payload1); + break; + default: + throw new TypeError("Unsupported JSValue kind " + kind); + } + return jsValue; + } + const __bjs_createResultValuesHelpers = () => ({ lower: (value) => { const enumTag = value.tag; @@ -163,6 +473,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; @@ -724,11 +1035,19 @@ export async function createInstantiator(options, swift) { } constructor(delegates) { - for (const elem of delegates) { - const objId = swift.memory.retain(elem); - i32Stack.push(objId); - } - i32Stack.push(delegates.length); + const elemCodec = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + __bjs_arrayCodec(elemCodec).lower(delegates); const ret = instance.exports.bjs_DelegateManager_init(); return DelegateManager.__construct(ret); } @@ -737,55 +1056,68 @@ export async function createInstantiator(options, swift) { } get delegates() { instance.exports.bjs_DelegateManager_delegates_get(this.pointer); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { + const elemCodec = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { const objId = i32Stack.pop(); const obj = swift.memory.getObject(objId); swift.memory.release(objId); - arrayResult.push(obj); - } - arrayResult.reverse(); - } + return obj; + }, + }; + const arrayResult = __bjs_arrayCodec(elemCodec).lift(); return arrayResult; } set delegates(value) { - for (const elem of value) { - const objId = swift.memory.retain(elem); - i32Stack.push(objId); - } - i32Stack.push(value.length); + const elemCodec = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + __bjs_arrayCodec(elemCodec).lower(value); instance.exports.bjs_DelegateManager_delegates_set(this.pointer); } get delegatesByName() { instance.exports.bjs_DelegateManager_delegatesByName_get(this.pointer); - const dictLen = i32Stack.pop(); - const dictResult = {}; - for (let i = 0; i < dictLen; i++) { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - const string = strStack.pop(); - dictResult[string] = obj; - } + const elemCodec = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + const dictResult = __bjs_dictCodec(elemCodec).lift(); return dictResult; } set delegatesByName(value) { - const entries = Object.entries(value); - for (const entry of entries) { - const [key, value1] = entry; - const bytes = textEncoder.encode(key); - const id = swift.memory.retain(bytes); - i32Stack.push(bytes.length); - i32Stack.push(id); - const objId = swift.memory.retain(value1); - i32Stack.push(objId); - } - i32Stack.push(entries.length); + const elemCodec = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + __bjs_dictCodec(elemCodec).lower(value); instance.exports.bjs_DelegateManager_delegatesByName_set(this.pointer); } } @@ -794,50 +1126,63 @@ export async function createInstantiator(options, swift) { const exports = { processDelegates: function bjs_processDelegates(delegates) { - for (const elem of delegates) { - const objId = swift.memory.retain(elem); - i32Stack.push(objId); - } - i32Stack.push(delegates.length); + const elemCodec = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + __bjs_arrayCodec(elemCodec).lower(delegates); instance.exports.bjs_processDelegates(); - const arrayLen = i32Stack.pop(); - let arrayResult; - if (arrayLen === -1) { - arrayResult = taStack.pop(); - } else { - arrayResult = []; - for (let i = 0; i < arrayLen; i++) { - const objId1 = i32Stack.pop(); - const obj = swift.memory.getObject(objId1); - swift.memory.release(objId1); - arrayResult.push(obj); - } - arrayResult.reverse(); - } + const elemCodec1 = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + const arrayResult = __bjs_arrayCodec(elemCodec1).lift(); return arrayResult; }, processDelegatesByName: function bjs_processDelegatesByName(delegates) { - const entries = Object.entries(delegates); - for (const entry of entries) { - const [key, value] = entry; - const bytes = textEncoder.encode(key); - const id = swift.memory.retain(bytes); - i32Stack.push(bytes.length); - i32Stack.push(id); - const objId = swift.memory.retain(value); - i32Stack.push(objId); - } - i32Stack.push(entries.length); + const elemCodec = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + __bjs_dictCodec(elemCodec).lower(delegates); instance.exports.bjs_processDelegatesByName(); - const dictLen = i32Stack.pop(); - const dictResult = {}; - for (let i = 0; i < dictLen; i++) { - const objId1 = i32Stack.pop(); - const obj = swift.memory.getObject(objId1); - swift.memory.release(objId1); - const string = strStack.pop(); - dictResult[string] = obj; - } + const elemCodec1 = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + const dictResult = __bjs_dictCodec(elemCodec1).lift(); return dictResult; }, Direction: DirectionValues, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.d.ts index 7d5a3c9aa..ce87ccd29 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.d.ts @@ -34,5 +34,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.d.ts index e5602e42d..b97a1bd8e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.d.ts @@ -73,5 +73,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js index 25f989a00..8f783865e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js @@ -150,6 +150,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.d.ts index a168f3ad1..6176abb6f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.d.ts @@ -63,5 +63,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js index ca4093992..4841e3350 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js @@ -150,6 +150,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.d.ts index b54e14def..42cfe5870 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.d.ts @@ -68,5 +68,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js index 63dd9cba5..189db1f0e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js @@ -111,6 +111,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.d.ts index aea927c79..42ff8507c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.d.ts @@ -54,5 +54,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js index b5680b9b0..a5a003a1c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js @@ -111,6 +111,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.d.ts index 5e45162a1..8d562d13a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.d.ts @@ -17,5 +17,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.d.ts index b43ff062c..667db342e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.d.ts @@ -15,5 +15,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.d.ts index fe4708fd8..cf231e076 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.d.ts @@ -69,5 +69,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.js index ee5cc0a3e..3270abd58 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.js @@ -193,6 +193,7 @@ export async function createInstantiator(options, swift) { const value = structHelpers.Widget_Bounds.lift(); return swift.memory.retain(value); } + bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.d.ts index 2f56a1cb8..d0c84e109 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.d.ts @@ -43,5 +43,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.d.ts index 70f23c11a..81fd7f109 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.d.ts @@ -114,5 +114,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js index 62c2de8c6..bebe9179d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js @@ -61,6 +61,227 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + function __bjs_arrayCodec(elementCodec) { + return { + lower(value) { + for (let i = 0; i < value.length; i++) { + elementCodec.lower(value[i]); + } + i32Stack.push(value.length); + }, + lift() { + const count = i32Stack.pop(); + if (count === -1) { + return taStack.pop(); + } + const result = new Array(count); + for (let i = count - 1; i >= 0; i--) { + result[i] = elementCodec.lift(); + } + return result; + }, + }; + } + function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { + return { + lower(value) { + const isSome = isUndefinedOr ? value !== undefined : value != null; + if (isSome) { + elementCodec.lower(value); + i32Stack.push(1); + } else { + i32Stack.push(0); + } + }, + lift() { + if (i32Stack.pop() === 0) { + return isUndefinedOr ? undefined : null; + } + return elementCodec.lift(); + }, + }; + } + function __bjs_dictCodec(valueCodec) { + return { + lower(value) { + const keys = Object.keys(value); + for (let i = 0; i < keys.length; i++) { + __bjs_stringCodec.lower(keys[i]); + valueCodec.lower(value[keys[i]]); + } + i32Stack.push(keys.length); + }, + lift() { + const count = i32Stack.pop(); + const result = {}; + for (let i = 0; i < count; i++) { + const value = valueCodec.lift(); + const key = __bjs_stringCodec.lift(); + result[key] = value; + } + return result; + }, + }; + } + function __bjs_enumCodec(helper) { + return { + lower(value) { + i32Stack.push(helper.lower(value)); + }, + lift() { + return helper.lift(i32Stack.pop()); + }, + }; + } + + const __bjs_stringCodec = { + lower: (v) => { + const bytes = textEncoder.encode(v); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + }, + lift: () => { + const string = strStack.pop(); + return string; + }, + }; + const __bjs_primitiveCodecs = { + Bool: { + lower: (v) => { + i32Stack.push(v ? 1 : 0); + }, + lift: () => { + const bool = i32Stack.pop() !== 0; + return bool; + }, + }, + Int: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + Int8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + UInt: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + UInt64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + Float: { + lower: (v) => { + f32Stack.push(Math.fround(v)); + }, + lift: () => { + const f32 = f32Stack.pop(); + return f32; + }, + }, + Double: { + lower: (v) => { + f64Stack.push(v); + }, + lift: () => { + const f64 = f64Stack.pop(); + return f64; + }, + }, + String: __bjs_stringCodec, + JSValue: { + lower: (v) => { + const [vKind, vPayload1, vPayload2] = __bjs_jsValueLower(v); + i32Stack.push(vKind); + i32Stack.push(vPayload1); + f64Stack.push(vPayload2); + }, + lift: () => { + const jsValuePayload2 = f64Stack.pop(); + const jsValuePayload1 = i32Stack.pop(); + const jsValueKind = i32Stack.pop(); + const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + return jsValue; + }, + }, + }; + function __bjs_jsValueLower(value) { let kind; let payload1; @@ -330,6 +551,7 @@ export async function createInstantiator(options, swift) { const value = structHelpers.Animal.lift(); return swift.memory.retain(value); } + bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; @@ -863,32 +1085,23 @@ export async function createInstantiator(options, swift) { optResult = null; } let ret = callback(optResult); - const isSome = ret != null; - if (isSome) { - structHelpers.Animal.lower(ret); - } - i32Stack.push(isSome ? 1 : 0); + __bjs_optionalCodec(structHelpers.Animal).lower(ret); } catch (error) { setException(error); } } bjs["make_swift_closure_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV"] = function(boxPtr, file, line) { const lower_closure_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV = function(param0) { - const isSome = param0 != null; - if (isSome) { - structHelpers.Animal.lower(param0); - } - i32Stack.push(+isSome); + __bjs_optionalCodec(structHelpers.Animal).lower(param0); instance.exports.invoke_swift_closure_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV(boxPtr); - const isSome1 = i32Stack.pop(); - const optResult = isSome1 ? structHelpers.Animal.lift() : null; + const optValue = __bjs_optionalCodec(structHelpers.Animal).lift(); if (tmpRetException) { const error = swift.memory.getObject(tmpRetException); swift.memory.release(tmpRetException); tmpRetException = undefined; throw error; } - return optResult; + return optValue; }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV); } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.d.ts index b66f960f8..47f1b89f9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.d.ts @@ -17,5 +17,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts index 3b394fb06..3503e138e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts @@ -90,5 +90,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js index 92a99becb..c16b674ae 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js @@ -36,6 +36,316 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + function __bjs_arrayCodec(elementCodec) { + return { + lower(value) { + for (let i = 0; i < value.length; i++) { + elementCodec.lower(value[i]); + } + i32Stack.push(value.length); + }, + lift() { + const count = i32Stack.pop(); + if (count === -1) { + return taStack.pop(); + } + const result = new Array(count); + for (let i = count - 1; i >= 0; i--) { + result[i] = elementCodec.lift(); + } + return result; + }, + }; + } + function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { + return { + lower(value) { + const isSome = isUndefinedOr ? value !== undefined : value != null; + if (isSome) { + elementCodec.lower(value); + i32Stack.push(1); + } else { + i32Stack.push(0); + } + }, + lift() { + if (i32Stack.pop() === 0) { + return isUndefinedOr ? undefined : null; + } + return elementCodec.lift(); + }, + }; + } + function __bjs_dictCodec(valueCodec) { + return { + lower(value) { + const keys = Object.keys(value); + for (let i = 0; i < keys.length; i++) { + __bjs_stringCodec.lower(keys[i]); + valueCodec.lower(value[keys[i]]); + } + i32Stack.push(keys.length); + }, + lift() { + const count = i32Stack.pop(); + const result = {}; + for (let i = 0; i < count; i++) { + const value = valueCodec.lift(); + const key = __bjs_stringCodec.lift(); + result[key] = value; + } + return result; + }, + }; + } + function __bjs_enumCodec(helper) { + return { + lower(value) { + i32Stack.push(helper.lower(value)); + }, + lift() { + return helper.lift(i32Stack.pop()); + }, + }; + } + + const __bjs_stringCodec = { + lower: (v) => { + const bytes = textEncoder.encode(v); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + }, + lift: () => { + const string = strStack.pop(); + return string; + }, + }; + const __bjs_primitiveCodecs = { + Bool: { + lower: (v) => { + i32Stack.push(v ? 1 : 0); + }, + lift: () => { + const bool = i32Stack.pop() !== 0; + return bool; + }, + }, + Int: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + Int8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + UInt: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + UInt64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + Float: { + lower: (v) => { + f32Stack.push(Math.fround(v)); + }, + lift: () => { + const f32 = f32Stack.pop(); + return f32; + }, + }, + Double: { + lower: (v) => { + f64Stack.push(v); + }, + lift: () => { + const f64 = f64Stack.pop(); + return f64; + }, + }, + String: __bjs_stringCodec, + JSValue: { + lower: (v) => { + const [vKind, vPayload1, vPayload2] = __bjs_jsValueLower(v); + i32Stack.push(vKind); + i32Stack.push(vPayload1); + f64Stack.push(vPayload2); + }, + lift: () => { + const jsValuePayload2 = f64Stack.pop(); + const jsValuePayload1 = i32Stack.pop(); + const jsValueKind = i32Stack.pop(); + const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + return jsValue; + }, + }, + }; + + function __bjs_jsValueLower(value) { + let kind; + let payload1; + let payload2; + if (value === null) { + kind = 4; + payload1 = 0; + payload2 = 0; + } else { + switch (typeof value) { + case "boolean": + kind = 0; + payload1 = value ? 1 : 0; + payload2 = 0; + break; + case "number": + kind = 2; + payload1 = 0; + payload2 = value; + break; + case "string": + kind = 1; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "undefined": + kind = 5; + payload1 = 0; + payload2 = 0; + break; + case "object": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "function": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "symbol": + kind = 7; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "bigint": + kind = 8; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + default: + throw new TypeError("Unsupported JSValue type"); + } + } + return [kind, payload1, payload2]; + } + function __bjs_jsValueLift(kind, payload1, payload2) { + let jsValue; + switch (kind) { + case 0: + jsValue = payload1 !== 0; + break; + case 1: + jsValue = swift.memory.getObject(payload1); + break; + case 2: + jsValue = payload2; + break; + case 3: + jsValue = swift.memory.getObject(payload1); + break; + case 4: + jsValue = null; + break; + case 5: + jsValue = undefined; + break; + case 7: + jsValue = swift.memory.getObject(payload1); + break; + case 8: + jsValue = swift.memory.getObject(payload1); + break; + default: + throw new TypeError("Unsupported JSValue kind " + kind); + } + return jsValue; + } + const __bjs_createDataPointHelpers = () => ({ lower: (value) => { f64Stack.push(value.x); @@ -44,34 +354,12 @@ export async function createInstantiator(options, swift) { const id = swift.memory.retain(bytes); i32Stack.push(bytes.length); i32Stack.push(id); - const isSome = value.optCount != null ? 1 : 0; - if (isSome) { - i32Stack.push((value.optCount | 0)); - } - i32Stack.push(isSome); - const isSome1 = value.optFlag != null ? 1 : 0; - if (isSome1) { - i32Stack.push(value.optFlag ? 1 : 0); - } - i32Stack.push(isSome1); + __bjs_optionalCodec(__bjs_primitiveCodecs.Int).lower(value.optCount); + __bjs_optionalCodec(__bjs_primitiveCodecs.Bool).lower(value.optFlag); }, lift: () => { - const isSome = i32Stack.pop(); - let optValue; - if (isSome === 0) { - optValue = null; - } else { - const bool = i32Stack.pop() !== 0; - optValue = bool; - } - const isSome1 = i32Stack.pop(); - let optValue1; - if (isSome1 === 0) { - optValue1 = null; - } else { - const int = i32Stack.pop(); - optValue1 = int; - } + const optValue = __bjs_optionalCodec(__bjs_primitiveCodecs.Bool).lift(); + const optValue1 = __bjs_optionalCodec(__bjs_primitiveCodecs.Int).lift(); const string = strStack.pop(); const f64 = f64Stack.pop(); const f641 = f64Stack.pop(); @@ -88,21 +376,10 @@ export async function createInstantiator(options, swift) { const id1 = swift.memory.retain(bytes1); i32Stack.push(bytes1.length); i32Stack.push(id1); - const isSome = value.zipCode != null ? 1 : 0; - if (isSome) { - i32Stack.push((value.zipCode | 0)); - } - i32Stack.push(isSome); + __bjs_optionalCodec(__bjs_primitiveCodecs.Int).lower(value.zipCode); }, lift: () => { - const isSome = i32Stack.pop(); - let optValue; - if (isSome === 0) { - optValue = null; - } else { - const int = i32Stack.pop(); - optValue = int; - } + const optValue = __bjs_optionalCodec(__bjs_primitiveCodecs.Int).lift(); const string = strStack.pop(); const string1 = strStack.pop(); return { street: string1, city: string, zipCode: optValue }; @@ -116,28 +393,14 @@ export async function createInstantiator(options, swift) { i32Stack.push(id); i32Stack.push((value.age | 0)); structHelpers.Address.lower(value.address); - const isSome = value.email != null ? 1 : 0; - if (isSome) { - const bytes1 = textEncoder.encode(value.email); - const id1 = swift.memory.retain(bytes1); - i32Stack.push(bytes1.length); - i32Stack.push(id1); - } - i32Stack.push(isSome); + __bjs_optionalCodec(__bjs_stringCodec).lower(value.email); }, lift: () => { - const isSome = i32Stack.pop(); - let optValue; - if (isSome === 0) { - optValue = null; - } else { - const string = strStack.pop(); - optValue = string; - } + const optValue = __bjs_optionalCodec(__bjs_stringCodec).lift(); const struct = structHelpers.Address.lift(); const int = i32Stack.pop(); - const string1 = strStack.pop(); - return { name: string1, age: int, address: struct, email: optValue }; + const string = strStack.pop(); + return { name: string, age: int, address: struct, email: optValue }; } }); const __bjs_createSessionHelpers = () => ({ @@ -156,24 +419,31 @@ export async function createInstantiator(options, swift) { lower: (value) => { f64Stack.push(value.value); f32Stack.push(Math.fround(value.precision)); - const isSome = value.optionalPrecision != null ? 1 : 0; - if (isSome) { - f32Stack.push(Math.fround(value.optionalPrecision)); - } - i32Stack.push(isSome); + const elemCodec = { + lower: (v) => { + f32Stack.push(Math.fround(v)); + }, + lift: () => { + const rawValue = f32Stack.pop(); + return rawValue; + }, + }; + __bjs_optionalCodec(elemCodec).lower(value.optionalPrecision); }, lift: () => { - const isSome = i32Stack.pop(); - let optValue; - if (isSome === 0) { - optValue = null; - } else { - const rawValue = f32Stack.pop(); - optValue = rawValue; - } - const rawValue1 = f32Stack.pop(); + const elemCodec = { + lower: (v) => { + f32Stack.push(Math.fround(v)); + }, + lift: () => { + const rawValue = f32Stack.pop(); + return rawValue; + }, + }; + const optValue = __bjs_optionalCodec(elemCodec).lift(); + const rawValue = f32Stack.pop(); const f64 = f64Stack.pop(); - return { value: f64, precision: rawValue1, optionalPrecision: optValue }; + return { value: f64, precision: rawValue, optionalPrecision: optValue }; } }); const __bjs_createConfigStructHelpers = () => ({ @@ -192,24 +462,34 @@ export async function createInstantiator(options, swift) { id = undefined; } i32Stack.push(id !== undefined ? id : 0); - const isSome = value.optionalObject != null ? 1 : 0; - if (isSome) { - const objId = swift.memory.retain(value.optionalObject); - i32Stack.push(objId); - } - i32Stack.push(isSome); + const elemCodec = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + __bjs_optionalCodec(elemCodec).lower(value.optionalObject); }, lift: () => { - const isSome = i32Stack.pop(); - let optValue; - if (isSome === 0) { - optValue = null; - } else { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - optValue = obj; - } + const elemCodec = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + const optValue = __bjs_optionalCodec(elemCodec).lift(); const objectId = i32Stack.pop(); let value; if (objectId !== 0) { @@ -382,6 +662,7 @@ export async function createInstantiator(options, swift) { const value = structHelpers.Vector2D.lift(); return swift.memory.retain(value); } + bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.d.ts index e97b50fda..e95b78349 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.d.ts @@ -19,5 +19,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js index 4a2e18d6b..9d613c8a9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js @@ -31,6 +31,316 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + function __bjs_arrayCodec(elementCodec) { + return { + lower(value) { + for (let i = 0; i < value.length; i++) { + elementCodec.lower(value[i]); + } + i32Stack.push(value.length); + }, + lift() { + const count = i32Stack.pop(); + if (count === -1) { + return taStack.pop(); + } + const result = new Array(count); + for (let i = count - 1; i >= 0; i--) { + result[i] = elementCodec.lift(); + } + return result; + }, + }; + } + function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { + return { + lower(value) { + const isSome = isUndefinedOr ? value !== undefined : value != null; + if (isSome) { + elementCodec.lower(value); + i32Stack.push(1); + } else { + i32Stack.push(0); + } + }, + lift() { + if (i32Stack.pop() === 0) { + return isUndefinedOr ? undefined : null; + } + return elementCodec.lift(); + }, + }; + } + function __bjs_dictCodec(valueCodec) { + return { + lower(value) { + const keys = Object.keys(value); + for (let i = 0; i < keys.length; i++) { + __bjs_stringCodec.lower(keys[i]); + valueCodec.lower(value[keys[i]]); + } + i32Stack.push(keys.length); + }, + lift() { + const count = i32Stack.pop(); + const result = {}; + for (let i = 0; i < count; i++) { + const value = valueCodec.lift(); + const key = __bjs_stringCodec.lift(); + result[key] = value; + } + return result; + }, + }; + } + function __bjs_enumCodec(helper) { + return { + lower(value) { + i32Stack.push(helper.lower(value)); + }, + lift() { + return helper.lift(i32Stack.pop()); + }, + }; + } + + const __bjs_stringCodec = { + lower: (v) => { + const bytes = textEncoder.encode(v); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + }, + lift: () => { + const string = strStack.pop(); + return string; + }, + }; + const __bjs_primitiveCodecs = { + Bool: { + lower: (v) => { + i32Stack.push(v ? 1 : 0); + }, + lift: () => { + const bool = i32Stack.pop() !== 0; + return bool; + }, + }, + Int: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + Int8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + UInt: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + UInt64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + Float: { + lower: (v) => { + f32Stack.push(Math.fround(v)); + }, + lift: () => { + const f32 = f32Stack.pop(); + return f32; + }, + }, + Double: { + lower: (v) => { + f64Stack.push(v); + }, + lift: () => { + const f64 = f64Stack.pop(); + return f64; + }, + }, + String: __bjs_stringCodec, + JSValue: { + lower: (v) => { + const [vKind, vPayload1, vPayload2] = __bjs_jsValueLower(v); + i32Stack.push(vKind); + i32Stack.push(vPayload1); + f64Stack.push(vPayload2); + }, + lift: () => { + const jsValuePayload2 = f64Stack.pop(); + const jsValuePayload1 = i32Stack.pop(); + const jsValueKind = i32Stack.pop(); + const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + return jsValue; + }, + }, + }; + + function __bjs_jsValueLower(value) { + let kind; + let payload1; + let payload2; + if (value === null) { + kind = 4; + payload1 = 0; + payload2 = 0; + } else { + switch (typeof value) { + case "boolean": + kind = 0; + payload1 = value ? 1 : 0; + payload2 = 0; + break; + case "number": + kind = 2; + payload1 = 0; + payload2 = value; + break; + case "string": + kind = 1; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "undefined": + kind = 5; + payload1 = 0; + payload2 = 0; + break; + case "object": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "function": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "symbol": + kind = 7; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "bigint": + kind = 8; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + default: + throw new TypeError("Unsupported JSValue type"); + } + } + return [kind, payload1, payload2]; + } + function __bjs_jsValueLift(kind, payload1, payload2) { + let jsValue; + switch (kind) { + case 0: + jsValue = payload1 !== 0; + break; + case 1: + jsValue = swift.memory.getObject(payload1); + break; + case 2: + jsValue = payload2; + break; + case 3: + jsValue = swift.memory.getObject(payload1); + break; + case 4: + jsValue = null; + break; + case 5: + jsValue = undefined; + break; + case 7: + jsValue = swift.memory.getObject(payload1); + break; + case 8: + jsValue = swift.memory.getObject(payload1); + break; + default: + throw new TypeError("Unsupported JSValue kind " + kind); + } + return jsValue; + } + const __bjs_createPointHelpers = () => ({ lower: (value) => { i32Stack.push((value.x | 0)); @@ -125,6 +435,7 @@ export async function createInstantiator(options, swift) { const value = structHelpers.Point.lift(); return swift.memory.retain(value); } + bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; @@ -242,11 +553,7 @@ export async function createInstantiator(options, swift) { optResult = null; } let ret = imports.roundTripOptional(optResult); - const isSome = ret != null; - if (isSome) { - structHelpers.Point.lower(ret); - } - i32Stack.push(isSome ? 1 : 0); + __bjs_optionalCodec(structHelpers.Point).lower(ret); } catch (error) { setException(error); } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.d.ts index 99adf95b6..606de53ad 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.d.ts @@ -29,5 +29,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.d.ts index 9199ad1ae..13dccd568 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.d.ts @@ -14,5 +14,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.d.ts index 5a4ee78ce..b1ecc2000 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.d.ts @@ -34,5 +34,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js index 457bfa973..704dbb021 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js @@ -130,6 +130,7 @@ export async function createInstantiator(options, swift) { const value = structHelpers.PointerFields.lift(); return swift.memory.retain(value); } + bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.d.ts index 7acba67a0..d15ce0a8a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.d.ts @@ -15,5 +15,6 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; + afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/PackageToJS/Templates/instantiate.js b/Plugins/PackageToJS/Templates/instantiate.js index 36d840099..71aea21ee 100644 --- a/Plugins/PackageToJS/Templates/instantiate.js +++ b/Plugins/PackageToJS/Templates/instantiate.js @@ -84,7 +84,7 @@ async function createInstantiator(options, swift) { /** @type {import('./instantiate.d').instantiate} */ export async function instantiate(options) { - const result = await _instantiate(options); + const { instantiator, ...result } = await _instantiate(options); /* #if IS_WASI */ options.wasi.initialize(result.instance); /* #endif */ @@ -94,7 +94,7 @@ export async function instantiate(options) { /** @type {import('./instantiate.d').instantiateForThread} */ export async function instantiateForThread(tid, startArg, options) { - const result = await _instantiate(options); + const { instantiator, ...result } = await _instantiate(options); /* #if IS_WASI */ options.wasi.setInstance(result.instance); /* #endif */ @@ -102,7 +102,7 @@ export async function instantiateForThread(tid, startArg, options) { return result; } -/** @type {import('./instantiate.d').instantiate} */ +/** @param {import('./instantiate.d').InstantiateOptions} options */ async function _instantiate(options) { const _WebAssembly = options.WebAssembly || WebAssembly; const moduleSource = options.module; @@ -184,5 +184,6 @@ async function _instantiate(options) { instance, swift, exports, + instantiator, }; } diff --git a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift index 4eeae4dac..b15e07b5d 100644 --- a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift +++ b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift @@ -204,6 +204,58 @@ extension _BridgedSwiftStackType { } } +/// Types usable as the generic argument of a generic imported `@JSFunction`. +/// Each conforming type owns a ``BridgeJSTypeHandle`` whose pointer is the +/// runtime type ID that selects the matching JS codec. Do not conform types by +/// hand; marking them `@JS` emits the conformance together with the JS codec. +public protocol BridgedSwiftGenericBridgeable: _BridgedSwiftStackType +where StackLiftResult == Self { + @_spi(BridgeJS) static var bridgeJSTypeHandle: BridgeJSTypeHandle { get } +} + +extension BridgedSwiftGenericBridgeable { + /// The runtime type ID passed across the bridge for this type. + @_spi(BridgeJS) public static var bridgeJSTypeID: Int32 { bridgeJSTypeHandle.typeID } + + /// Creates the type's unique handle. A generic static function so + /// conformances compile under Embedded Swift. + @_spi(BridgeJS) public static func bridgeJSMakeTypeHandle() -> BridgeJSTypeHandle { + #if hasFeature(Embedded) + return BridgeJSTypeHandle() + #else + return BridgeJSTypeHandle(Self.self) + #endif + } +} + +/// A per-type identity token for generic bridging: each conforming type stores +/// exactly one handle in a `static let`, so the handle's pointer identifies the +/// type at runtime without relying on type names, which could collide across +/// modules. +public final class BridgeJSTypeHandle: Sendable { + #if hasFeature(Embedded) + public init() {} + #else + /// The conforming type, for exported generics (planned follow-up) to map a + /// type ID back to. `nonisolated(unsafe)`: an immutable metatype is safe to + /// share, but the compiler cannot infer that. + public nonisolated(unsafe) let type: any BridgedSwiftGenericBridgeable.Type + + public init(_ type: any BridgedSwiftGenericBridgeable.Type) { + self.type = type + } + #endif + + /// The handle object's own address; pointers are 32-bit on wasm32. + @_spi(BridgeJS) public var typeID: Int32 { + #if arch(wasm32) + return Int32(bitPattern: UInt32(UInt(bitPattern: Unmanaged.passUnretained(self).toOpaque()))) + #else + _onlyAvailableOnWasm() + #endif + } +} + /// Types that bridge with the same (isSome, value) ABI as Optional. /// Used by JSUndefinedOr so all bridge methods delegate to Optional. public protocol _BridgedAsOptional { @@ -808,6 +860,49 @@ extension String: _BridgedSwiftStackType { } } +extension Bool: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Bool.bridgeJSMakeTypeHandle() +} +extension Int: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Int.bridgeJSMakeTypeHandle() +} +extension Float: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Float.bridgeJSMakeTypeHandle() +} +extension Double: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Double.bridgeJSMakeTypeHandle() +} +extension String: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = String.bridgeJSMakeTypeHandle() +} +extension UInt: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = UInt.bridgeJSMakeTypeHandle() +} +extension Int8: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Int8.bridgeJSMakeTypeHandle() +} +extension UInt8: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = UInt8.bridgeJSMakeTypeHandle() +} +extension Int16: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Int16.bridgeJSMakeTypeHandle() +} +extension UInt16: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = UInt16.bridgeJSMakeTypeHandle() +} +extension Int32: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Int32.bridgeJSMakeTypeHandle() +} +extension UInt32: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = UInt32.bridgeJSMakeTypeHandle() +} +extension Int64: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Int64.bridgeJSMakeTypeHandle() +} +extension UInt64: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = UInt64.bridgeJSMakeTypeHandle() +} + extension JSObject: _BridgedSwiftStackType { // JSObject is a non-final class, so we must explicitly specify the associated type // rather than relying on the default `Self` (which Swift requires for covariant returns). @@ -914,6 +1009,10 @@ extension JSValue: _BridgedSwiftStackType { } } +extension JSValue: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = JSValue.bridgeJSMakeTypeHandle() +} + /// A protocol that Swift heap objects exposed to JavaScript via `@JS class` must conform to. /// /// The conformance is automatically synthesized by the BridgeJS code generator. diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Generating-from-TypeScript.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Generating-from-TypeScript.md index 9c0a80dc1..5a47746d6 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Generating-from-TypeScript.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Generating-from-TypeScript.md @@ -416,4 +416,4 @@ When a TypeScript name is not a valid Swift identifier (e.g. contains dashes, sp ## Limitations - No first-class support for async/Promise-returning functions;. -- No generic type parameter can appear on a bridged function signature. \ No newline at end of file +- No generic type parameter can appear on a bridged function signature generated from TypeScript; a type parameter is lowered to `JSObject`. Generic imports are available only through `@JSFunction` declarations written in Swift — see . \ No newline at end of file diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Function.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Function.md index 1b2be6cb0..ebc9ac857 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Function.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Importing-JavaScript/Importing-JS-Function.md @@ -77,11 +77,23 @@ If you used `from: .global` or `.module`, do not pass the function in `getImport Bound functions are `throws(JSException)`. Call them with `try` or `try?`; they throw when the JavaScript implementation throws. +## Generic functions + +A `@JSFunction` can be generic over a type parameter constrained to `BridgedSwiftGenericBridgeable`, so one declaration serves every bridged type: + +```swift +@JSFunction func parse(_ json: String) throws(JSException) -> T + +let user: User = try parse(jsonString) // T inferred from the call site +``` + +`T` can be any supported primitive, `String`, `JSValue`, or a `@JS` struct, `@JS` enum, or `final @JS class` (see ), used bare or wrapped as `[T]`, `T?`, or `[String: T]`. A function may declare multiple type parameters, and a return-only generic (`func make() -> T`) works too. Generic initializers, methods, and static methods on `@JSClass` types are supported the same way. `async` generic functions and `where` clauses are not supported. + ## Supported features | Feature | Status | |:--|:--| | Primitive parameter/result types (e.g. `Double`, `Bool`) | ✅ | | `String` parameter/result type | ✅ | +| Generic parameter/result types (constrained to `BridgedSwiftGenericBridgeable`) | ✅ | | Async function | ❌ | -| Generics | ❌ | diff --git a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Supported-Types.md b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Supported-Types.md index 5c609ab72..539f7ce15 100644 --- a/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Supported-Types.md +++ b/Sources/JavaScriptKit/Documentation.docc/Articles/BridgeJS/Supported-Types.md @@ -31,6 +31,10 @@ When using `JSTypedArray` (or convenience typealiases) in `@JS` signatures, t See for usage details. +## Generic type parameters + +An imported `@JSFunction` can be generic over a type parameter constrained to `BridgedSwiftGenericBridgeable` (see ); exported `@JS` functions cannot yet. The constraint is satisfied by all supported primitives, `String`, `JSValue`, and any `@JS` struct, `@JS` enum, or `final @JS class`, including ones from another linked module. Do not write the conformance by hand; marking the type `@JS` is what provides it, together with the JavaScript side of the bridge. + ## See Also - diff --git a/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift b/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift index 4e35a1c9f..deedc1ccf 100644 --- a/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift @@ -353,4 +353,53 @@ fileprivate func _bjs_GlobalUtils_PublicConverter_wrap_extern(_ pointer: UnsafeM #endif @inline(never) fileprivate func _bjs_GlobalUtils_PublicConverter_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { return _bjs_GlobalUtils_PublicConverter_wrap_extern(pointer) -} \ No newline at end of file +} + +extension GlobalNetworking.API.CallMethod: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = GlobalNetworking.API.CallMethod.bridgeJSMakeTypeHandle() +} + +extension GlobalConfiguration.PublicLogLevel: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = GlobalConfiguration.PublicLogLevel.bridgeJSMakeTypeHandle() +} + +extension GlobalConfiguration.AvailablePort: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = GlobalConfiguration.AvailablePort.bridgeJSMakeTypeHandle() +} + +extension Internal.SupportedServerMethod: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Internal.SupportedServerMethod.bridgeJSMakeTypeHandle() +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_BridgeJSGlobalTests_register_type_handles") +fileprivate func _bjs_BridgeJSGlobalTests_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_BridgeJSGlobalTests_register_type_handles") +public func _bjs_BridgeJSGlobalTests_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + GlobalNetworking.API.CallMethod.bridgeJSTypeID, + GlobalConfiguration.PublicLogLevel.bridgeJSTypeID, + GlobalConfiguration.AvailablePort.bridgeJSTypeID, + Internal.SupportedServerMethod.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_BridgeJSGlobalTests_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 6c5fe3b05..156f044d2 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -13608,6 +13608,246 @@ fileprivate func _bjs_LeakCheck_wrap_extern(_ pointer: UnsafeMutableRawPointer) return _bjs_LeakCheck_wrap_extern(pointer) } +extension JSCoordinate: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = JSCoordinate.bridgeJSMakeTypeHandle() +} + +extension NestedStructGroupA.Metadata: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = NestedStructGroupA.Metadata.bridgeJSMakeTypeHandle() +} + +extension NestedStructGroupB.Metadata: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = NestedStructGroupB.Metadata.bridgeJSMakeTypeHandle() +} + +extension NestedTypeHost.Label: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = NestedTypeHost.Label.bridgeJSMakeTypeHandle() +} + +extension Point: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Point.bridgeJSMakeTypeHandle() +} + +extension PointerFields: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = PointerFields.bridgeJSMakeTypeHandle() +} + +extension DataPoint: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = DataPoint.bridgeJSMakeTypeHandle() +} + +extension PublicPoint: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = PublicPoint.bridgeJSMakeTypeHandle() +} + +extension Address: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Address.bridgeJSMakeTypeHandle() +} + +extension Contact: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Contact.bridgeJSMakeTypeHandle() +} + +extension Config: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Config.bridgeJSMakeTypeHandle() +} + +extension SessionData: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = SessionData.bridgeJSMakeTypeHandle() +} + +extension ValidationReport: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = ValidationReport.bridgeJSMakeTypeHandle() +} + +extension AdvancedConfig: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = AdvancedConfig.bridgeJSMakeTypeHandle() +} + +extension MeasurementConfig: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = MeasurementConfig.bridgeJSMakeTypeHandle() +} + +extension MathOperations: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = MathOperations.bridgeJSMakeTypeHandle() +} + +extension CopyableCart: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = CopyableCart.bridgeJSMakeTypeHandle() +} + +extension CopyableCartItem: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = CopyableCartItem.bridgeJSMakeTypeHandle() +} + +extension CopyableNestedCart: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = CopyableNestedCart.bridgeJSMakeTypeHandle() +} + +extension ConfigStruct: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = ConfigStruct.bridgeJSMakeTypeHandle() +} + +extension Vector2D: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Vector2D.bridgeJSMakeTypeHandle() +} + +extension JSObjectContainer: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = JSObjectContainer.bridgeJSMakeTypeHandle() +} + +extension FooContainer: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = FooContainer.bridgeJSMakeTypeHandle() +} + +extension ArrayMembers: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = ArrayMembers.bridgeJSMakeTypeHandle() +} + +extension PolygonReference: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = PolygonReference.bridgeJSMakeTypeHandle() +} + +extension TagReference: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = TagReference.bridgeJSMakeTypeHandle() +} + +extension TagHolderReference: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = TagHolderReference.bridgeJSMakeTypeHandle() +} + +extension PriorityReference: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = PriorityReference.bridgeJSMakeTypeHandle() +} + +extension Severity: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Severity.bridgeJSMakeTypeHandle() +} + +extension Shape: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Shape.bridgeJSMakeTypeHandle() +} + +extension InnerTag: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = InnerTag.bridgeJSMakeTypeHandle() +} + +extension AsyncImportedPayloadResult: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = AsyncImportedPayloadResult.bridgeJSMakeTypeHandle() +} + +extension Direction: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Direction.bridgeJSMakeTypeHandle() +} + +extension Status: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Status.bridgeJSMakeTypeHandle() +} + +extension Theme: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Theme.bridgeJSMakeTypeHandle() +} + +extension HttpStatus: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = HttpStatus.bridgeJSMakeTypeHandle() +} + +extension FileSize: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = FileSize.bridgeJSMakeTypeHandle() +} + +extension SessionId: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = SessionId.bridgeJSMakeTypeHandle() +} + +extension Precision: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Precision.bridgeJSMakeTypeHandle() +} + +extension Ratio: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Ratio.bridgeJSMakeTypeHandle() +} + +extension TSDirection: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = TSDirection.bridgeJSMakeTypeHandle() +} + +extension TSTheme: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = TSTheme.bridgeJSMakeTypeHandle() +} + +extension AsyncPayloadResult: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = AsyncPayloadResult.bridgeJSMakeTypeHandle() +} + +extension Networking.API.Method: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Networking.API.Method.bridgeJSMakeTypeHandle() +} + +extension Configuration.LogLevel: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Configuration.LogLevel.bridgeJSMakeTypeHandle() +} + +extension Configuration.Port: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Configuration.Port.bridgeJSMakeTypeHandle() +} + +extension Internal.SupportedMethod: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Internal.SupportedMethod.bridgeJSMakeTypeHandle() +} + +extension APIResult: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = APIResult.bridgeJSMakeTypeHandle() +} + +extension ComplexResult: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = ComplexResult.bridgeJSMakeTypeHandle() +} + +extension Utilities.Result: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Utilities.Result.bridgeJSMakeTypeHandle() +} + +extension API.NetworkingResult: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = API.NetworkingResult.bridgeJSMakeTypeHandle() +} + +extension AllTypesResult: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = AllTypesResult.bridgeJSMakeTypeHandle() +} + +extension TypedPayloadResult: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = TypedPayloadResult.bridgeJSMakeTypeHandle() +} + +extension StaticCalculator: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = StaticCalculator.bridgeJSMakeTypeHandle() +} + +extension StaticPropertyEnum: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = StaticPropertyEnum.bridgeJSMakeTypeHandle() +} + +extension NestedTypeHost.Variant: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = NestedTypeHost.Variant.bridgeJSMakeTypeHandle() +} + +extension LightColor: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = LightColor.bridgeJSMakeTypeHandle() +} + +extension ImportedPayloadSignal: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = ImportedPayloadSignal.bridgeJSMakeTypeHandle() +} + +extension OptionalAllTypesResult: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = OptionalAllTypesResult.bridgeJSMakeTypeHandle() +} + +extension APIOptionalResult: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = APIOptionalResult.bridgeJSMakeTypeHandle() +} + @JSFunction func Promise_reject(_ promise: JSObject, _ value: JSValue) throws(JSException) #if arch(wasm32) @@ -18191,4 +18431,93 @@ func _$SwiftClassSupportImports_jsConsumeOptionalLeakCheck(_ value: Optional?, _ count: Int32) + +@_expose(wasm, "bjs_BridgeJSRuntimeTests_register_type_handles") +public func _bjs_BridgeJSRuntimeTests_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + JSCoordinate.bridgeJSTypeID, + NestedStructGroupA.Metadata.bridgeJSTypeID, + NestedStructGroupB.Metadata.bridgeJSTypeID, + NestedTypeHost.Label.bridgeJSTypeID, + Point.bridgeJSTypeID, + PointerFields.bridgeJSTypeID, + DataPoint.bridgeJSTypeID, + PublicPoint.bridgeJSTypeID, + Address.bridgeJSTypeID, + Contact.bridgeJSTypeID, + Config.bridgeJSTypeID, + SessionData.bridgeJSTypeID, + ValidationReport.bridgeJSTypeID, + AdvancedConfig.bridgeJSTypeID, + MeasurementConfig.bridgeJSTypeID, + MathOperations.bridgeJSTypeID, + CopyableCart.bridgeJSTypeID, + CopyableCartItem.bridgeJSTypeID, + CopyableNestedCart.bridgeJSTypeID, + ConfigStruct.bridgeJSTypeID, + Vector2D.bridgeJSTypeID, + JSObjectContainer.bridgeJSTypeID, + FooContainer.bridgeJSTypeID, + ArrayMembers.bridgeJSTypeID, + PolygonReference.bridgeJSTypeID, + TagReference.bridgeJSTypeID, + TagHolderReference.bridgeJSTypeID, + PriorityReference.bridgeJSTypeID, + Severity.bridgeJSTypeID, + Shape.bridgeJSTypeID, + InnerTag.bridgeJSTypeID, + AsyncImportedPayloadResult.bridgeJSTypeID, + Direction.bridgeJSTypeID, + Status.bridgeJSTypeID, + Theme.bridgeJSTypeID, + HttpStatus.bridgeJSTypeID, + FileSize.bridgeJSTypeID, + SessionId.bridgeJSTypeID, + Precision.bridgeJSTypeID, + Ratio.bridgeJSTypeID, + TSDirection.bridgeJSTypeID, + TSTheme.bridgeJSTypeID, + AsyncPayloadResult.bridgeJSTypeID, + Networking.API.Method.bridgeJSTypeID, + Configuration.LogLevel.bridgeJSTypeID, + Configuration.Port.bridgeJSTypeID, + Internal.SupportedMethod.bridgeJSTypeID, + APIResult.bridgeJSTypeID, + ComplexResult.bridgeJSTypeID, + Utilities.Result.bridgeJSTypeID, + API.NetworkingResult.bridgeJSTypeID, + AllTypesResult.bridgeJSTypeID, + TypedPayloadResult.bridgeJSTypeID, + StaticCalculator.bridgeJSTypeID, + StaticPropertyEnum.bridgeJSTypeID, + NestedTypeHost.Variant.bridgeJSTypeID, + LightColor.bridgeJSTypeID, + ImportedPayloadSignal.bridgeJSTypeID, + OptionalAllTypesResult.bridgeJSTypeID, + APIOptionalResult.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_BridgeJSRuntimeTests_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index d4e1878e1..6748d7c16 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -127,6 +127,7 @@ } ] }, + "isFinal" : true, "methods" : [ { "abiName" : "bjs_PolygonReference_vertexCount", @@ -265,6 +266,7 @@ "swiftCallName" : "PolygonReference" }, { + "isFinal" : true, "methods" : [ { "abiName" : "bjs_TagReference_describe", @@ -327,6 +329,7 @@ } ] }, + "isFinal" : true, "methods" : [ { "abiName" : "bjs_TagHolderReference_describe", @@ -380,6 +383,7 @@ "swiftCallName" : "TagHolderReference" }, { + "isFinal" : true, "methods" : [ { "abiName" : "bjs_PriorityReference_describe", From c58ffa4007fe2c7f139e3895b3fc0e221f2cc9a9 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Mon, 10 Aug 2026 15:32:57 +0200 Subject: [PATCH 38/50] BridgeJS: Add tests and fixtures for generic imports --- .../BridgeJSCodegenTests.swift | 3 + .../BridgeJSToolTests/BridgeJSLinkTests.swift | 20 + .../CodegenTestSupport.swift | 40 + .../GenericExportDiagnosticsTests.swift | 63 ++ .../GenericImportDiagnosticsTests.swift | 210 ++++ .../Inputs/MacroSwift/GenericImports.swift | 74 ++ .../BridgeJSCodegenTests/Alias.swift | 34 +- .../BridgeJSCodegenTests/AliasInClosure.swift | 32 +- .../BridgeJSCodegenTests/ArrayTypes.swift | 34 +- .../BridgeJSCodegenTests/Async.swift | 34 +- .../AsyncAssociatedValueEnum.swift | 32 +- .../ClassWithNestedTypes.swift | 33 +- .../DefaultParameters.swift | 34 +- .../DictionaryTypes.swift | 32 +- .../BridgeJSCodegenTests/DocComments.swift | 33 +- .../BridgeJSCodegenTests/EnumAlias.swift | 32 +- .../EnumAssociatedValue.swift | 42 +- .../EnumAssociatedValueImport.swift | 32 +- .../BridgeJSCodegenTests/EnumCase.swift | 35 +- .../BridgeJSCodegenTests/EnumCaseImport.swift | 32 +- .../EnumNamespace.Global.swift | 35 +- .../BridgeJSCodegenTests/EnumNamespace.swift | 35 +- .../BridgeJSCodegenTests/EnumRawType.swift | 43 +- .../BridgeJSCodegenTests/GenericImports.json | 669 +++++++++++++ .../BridgeJSCodegenTests/GenericImports.swift | 520 ++++++++++ .../ImportedTypeInExportedInterface.swift | 32 +- .../BridgeJSCodegenTests/JSNameOverride.swift | 33 +- .../BridgeJSCodegenTests/NestedType.swift | 33 +- .../BridgeJSCodegenTests/Protocol.swift | 35 +- .../StaticFunctions.Global.swift | 33 +- .../StaticFunctions.swift | 33 +- .../StaticProperties.Global.swift | 32 +- .../StaticProperties.swift | 32 +- .../StructWithNestedTypes.swift | 38 +- .../BridgeJSCodegenTests/SwiftClosure.swift | 36 +- .../BridgeJSCodegenTests/SwiftStruct.swift | 40 +- .../SwiftStructImports.swift | 32 +- .../BridgeJSCodegenTests/UnsafePointer.swift | 32 +- .../BridgeJSLinkTests/Alias.d.ts | 1 - .../BridgeJSLinkTests/AliasInClosure.d.ts | 1 - .../BridgeJSLinkTests/ArrayTypes.d.ts | 1 - .../BridgeJSLinkTests/Async.d.ts | 1 - .../AsyncAssociatedValueEnum.d.ts | 1 - .../BridgeJSLinkTests/AsyncImport.d.ts | 1 - .../BridgeJSLinkTests/AsyncStaticImport.d.ts | 1 - .../ClassWithNestedTypes.d.ts | 1 - .../BridgeJSLinkTests/DefaultParameters.d.ts | 1 - .../BridgeJSLinkTests/DictionaryTypes.d.ts | 1 - .../BridgeJSLinkTests/DocComments.d.ts | 1 - .../BridgeJSLinkTests/EnumAlias.d.ts | 1 - .../EnumAssociatedValue.d.ts | 1 - .../EnumAssociatedValueImport.d.ts | 1 - .../BridgeJSLinkTests/EnumCase.d.ts | 1 - .../BridgeJSLinkTests/EnumCaseImport.d.ts | 1 - .../EnumNamespace.Global.d.ts | 1 - .../BridgeJSLinkTests/EnumNamespace.d.ts | 1 - .../BridgeJSLinkTests/EnumRawType.d.ts | 1 - .../BridgeJSLinkTests/FixedWidthIntegers.d.ts | 1 - .../BridgeJSLinkTests/GenericImports.d.ts | 87 ++ .../BridgeJSLinkTests/GenericImports.js | 930 ++++++++++++++++++ .../BridgeJSLinkTests/GlobalGetter.d.ts | 1 - .../BridgeJSLinkTests/GlobalThisImports.d.ts | 1 - .../IdentityModeClass.ConfigPointer.d.ts | 1 - .../IdentityModeClass.PerClass.d.ts | 1 - .../BridgeJSLinkTests/IdentityModeClass.d.ts | 1 - .../BridgeJSLinkTests/ImportArray.d.ts | 1 - .../ImportedTypeInExportedInterface.d.ts | 1 - .../InvalidPropertyNames.d.ts | 1 - .../BridgeJSLinkTests/JSClass.d.ts | 1 - .../JSClassStaticFunctions.d.ts | 1 - .../BridgeJSLinkTests/JSImportBareModule.d.ts | 1 - .../JSImportBareModuleFallback.d.ts | 1 - .../BridgeJSLinkTests/JSImportModule.d.ts | 1 - .../BridgeJSLinkTests/JSNameOverride.d.ts | 1 - .../BridgeJSLinkTests/JSTypedArrayTypes.d.ts | 1 - .../BridgeJSLinkTests/JSValue.d.ts | 1 - .../BridgeJSLinkTests/MixedGlobal.d.ts | 1 - .../BridgeJSLinkTests/MixedModules.d.ts | 1 - .../BridgeJSLinkTests/MixedPrivate.d.ts | 1 - .../BridgeJSLinkTests/Namespaces.Global.d.ts | 1 - .../BridgeJSLinkTests/Namespaces.d.ts | 1 - .../BridgeJSLinkTests/NestedType.d.ts | 1 - .../BridgeJSLinkTests/Optionals.d.ts | 1 - .../PrimitiveParameters.d.ts | 1 - .../BridgeJSLinkTests/PrimitiveReturn.d.ts | 1 - .../BridgeJSLinkTests/PropertyTypes.d.ts | 1 - .../BridgeJSLinkTests/Protocol.d.ts | 1 - .../BridgeJSLinkTests/ProtocolInClosure.d.ts | 1 - .../StaticFunctions.Global.d.ts | 1 - .../BridgeJSLinkTests/StaticFunctions.d.ts | 1 - .../StaticProperties.Global.d.ts | 1 - .../BridgeJSLinkTests/StaticProperties.d.ts | 1 - .../BridgeJSLinkTests/StringParameter.d.ts | 1 - .../BridgeJSLinkTests/StringReturn.d.ts | 1 - .../StructWithNestedTypes.d.ts | 1 - .../BridgeJSLinkTests/SwiftClass.d.ts | 1 - .../BridgeJSLinkTests/SwiftClosure.d.ts | 1 - .../SwiftClosureImports.d.ts | 1 - .../BridgeJSLinkTests/SwiftStruct.d.ts | 1 - .../BridgeJSLinkTests/SwiftStructImports.d.ts | 1 - .../SwiftTypedClosureAccess.d.ts | 1 - .../BridgeJSLinkTests/Throws.d.ts | 1 - .../BridgeJSLinkTests/UnsafePointer.d.ts | 1 - .../VoidParameterVoidReturn.d.ts | 1 - .../Generated/BridgeJS.swift | 614 ++++++++++++ .../Generated/JavaScript/BridgeJS.json | 778 +++++++++++++++ .../ImportGenericAPIs.swift | 280 ++++++ Tests/prelude.mjs | 32 + 108 files changed, 5315 insertions(+), 94 deletions(-) create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/CodegenTestSupport.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/GenericExportDiagnosticsTests.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/GenericImportDiagnosticsTests.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/GenericImports.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericImports.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericImports.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.d.ts create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js create mode 100644 Tests/BridgeJSRuntimeTests/ImportGenericAPIs.swift diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift index 60b2fd485..6d2f3d453 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift @@ -141,6 +141,9 @@ import Testing swiftParts.append(s) } } + if let typeRegistration = GenericTypeRegistrationCodegen().render(for: skeleton) { + swiftParts.append(typeRegistration) + } let combinedSwift = swiftParts .map { $0.trimmingCharacters(in: .newlines) } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSLinkTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSLinkTests.swift index 642debedc..cab2aca6f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSLinkTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSLinkTests.swift @@ -139,6 +139,26 @@ import Testing try snapshot(bridgeJSLink: bridgeJSLink, name: "MixedModules") } + private func linkedJS(forFixture input: String) throws -> String { + let url = Self.inputsDirectory.appendingPathComponent(input) + let name = url.deletingPathExtension().lastPathComponent + let sourceFile = Parser.parse(source: try String(contentsOf: url, encoding: .utf8)) + let importSwift = SwiftToSkeleton( + progress: .silent, + moduleName: "TestModule", + exposeToGlobal: false, + externalModuleIndex: .empty + ) + importSwift.addSourceFile(sourceFile, inputFilePath: "\(name).swift") + let importResult = try importSwift.finalize() + var bridgeJSLink = BridgeJSLink(sharedMemory: false) + let encoder = JSONEncoder() + encoder.outputFormatting = [.prettyPrinted, .sortedKeys] + let unifiedData = try encoder.encode(importResult) + try bridgeJSLink.addSkeletonFile(data: unifiedData) + return try bridgeJSLink.link().0 + } + @Test func perClassIdentityModeFromAnnotation() throws { let url = Self.inputsDirectory.appendingPathComponent("IdentityModeClass.swift") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/CodegenTestSupport.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/CodegenTestSupport.swift new file mode 100644 index 000000000..b66a5ba6f --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/CodegenTestSupport.swift @@ -0,0 +1,40 @@ +import Foundation +import SwiftParser +import SwiftSyntax +import Testing + +@testable import BridgeJSLink +@testable import BridgeJSCore +@testable import BridgeJSSkeleton + +func makeSkeleton( + _ source: String, + moduleName: String = "TestModule", + dependencies: [(moduleName: String, skeleton: BridgeJSSkeleton)] = [] +) throws -> BridgeJSSkeleton { + let swiftAPI = SwiftToSkeleton( + progress: .silent, + moduleName: moduleName, + exposeToGlobal: false, + externalModuleIndex: ExternalModuleIndex(dependencies: dependencies) + ) + swiftAPI.addSourceFile(Parser.parse(source: source), inputFilePath: "\(moduleName).swift") + return try swiftAPI.finalize() +} + +func expectDiagnostic( + source: String, + moduleName: String = "App", + contains message: String, + sourceLocation: Testing.SourceLocation = #_sourceLocation +) { + do { + _ = try makeSkeleton(source, moduleName: moduleName) + Issue.record("Expected diagnostic but resolution succeeded", sourceLocation: sourceLocation) + } catch let error as BridgeJSCoreDiagnosticError { + let combined = error.diagnostics.map(\.diagnostic.message).joined(separator: "\n") + #expect(combined.contains(message), sourceLocation: sourceLocation) + } catch { + Issue.record("Unexpected error: \(error)", sourceLocation: sourceLocation) + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/GenericExportDiagnosticsTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/GenericExportDiagnosticsTests.swift new file mode 100644 index 000000000..37f2a0318 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/GenericExportDiagnosticsTests.swift @@ -0,0 +1,63 @@ +import Testing + +@Suite struct GenericExportDiagnosticsTests { + + @Test + func genericExportedFunctionRejected() { + expectDiagnostic( + source: """ + @JS public func identity(_ value: T) -> T { value } + """, + contains: "Generic parameters on exported @JS functions are not supported yet" + ) + } + + @Test + func genericMethodOnExportedClassRejected() { + expectDiagnostic( + source: """ + @JS final class Box { + @JS init() {} + @JS func wrap(_ value: T) -> T { value } + } + """, + contains: "Generic parameters on exported @JS functions are not supported yet" + ) + } + + @Test + func genericMethodOnExportedStructRejected() { + expectDiagnostic( + source: """ + @JS struct Pair { + @JS init() {} + @JS func first(_ value: T) -> T { value } + } + """, + contains: "Generic parameters on exported @JS functions are not supported yet" + ) + } + + @Test + func genericStaticMethodOnExportedEnumRejected() { + expectDiagnostic( + source: """ + @JS enum Factory { + case primary + @JS static func one(_ value: T) -> T { value } + } + """, + contains: "Generic parameters on exported @JS functions are not supported yet" + ) + } + + @Test + func unconstrainedGenericExportedFunctionRejected() { + expectDiagnostic( + source: """ + @JS public func identity(_ value: T) -> T { value } + """, + contains: "Generic parameters on exported @JS functions are not supported yet" + ) + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/GenericImportDiagnosticsTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/GenericImportDiagnosticsTests.swift new file mode 100644 index 000000000..4a421b73b --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/GenericImportDiagnosticsTests.swift @@ -0,0 +1,210 @@ +import Testing + +@testable import BridgeJSSkeleton + +@Suite struct GenericImportDiagnosticsTests { + + @Test + func genericParameterRequiresBridgeableConstraint() { + expectDiagnostic( + source: """ + @JSFunction func identity(_ value: T) throws(JSException) -> T + """, + contains: "Generic parameter 'T' must be constrained to 'BridgedSwiftGenericBridgeable'" + ) + } + + @Test + func genericWhereClauseUnsupported() { + expectDiagnostic( + source: """ + @JSFunction func identity(_ value: T) throws(JSException) -> T where T: Sendable + """, + contains: "'where' clauses are not supported on @JSFunction" + ) + } + + @Test + func asyncGenericImportUnsupported() { + expectDiagnostic( + source: """ + @JSFunction func identityAsync(_ value: T) async throws(JSException) -> T + """, + contains: "Generic @JSFunction declarations cannot be 'async' yet." + ) + } + + @Test + func genericImportedMethodIsParsed() throws { + let skeleton = try makeSkeleton( + """ + @JSClass struct Box { + @JSFunction func member(_ value: T) throws(JSException) -> T + } + """, + moduleName: "App" + ) + let imported = try #require(skeleton.imported) + let types = imported.children.flatMap { $0.types } + let box = try #require(types.first { $0.name == "Box" }) + let method = try #require(box.methods.first { $0.name == "member" }) + #expect(method.genericParameters == ["T"]) + } + + @Test + func genericImportedConstructorIsParsed() throws { + let skeleton = try makeSkeleton( + """ + @JSClass struct Box { + @JSFunction init(_ value: T) throws(JSException) + } + """, + moduleName: "App" + ) + let imported = try #require(skeleton.imported) + let types = imported.children.flatMap { $0.types } + let box = try #require(types.first { $0.name == "Box" }) + let constructor = try #require(box.constructor) + #expect(constructor.genericParameters == ["T"]) + #expect(constructor.parameters.map(\.type) == [.generic("T")]) + } + + @Test + func genericImportedConstructorUnconstrainedParamIsRejected() { + expectDiagnostic( + source: """ + @JSClass struct Box { + @JSFunction init(_ value: T) throws(JSException) + } + """, + contains: + "Generic parameter 'T' must be constrained to 'BridgedSwiftGenericBridgeable' to be used with @JSFunction." + ) + } + + @Test + func genericImportedConstructorUnusedTypeParamIsRejected() { + expectDiagnostic( + source: """ + @JSClass struct Box { + @JSFunction init(_ value: Int) throws(JSException) + } + """, + contains: + "The generic parameter 'T' must be used in a parameter of a generic @JSFunction initializer." + ) + } + + @Test + func genericImportedConstructorAsyncIsRejected() { + expectDiagnostic( + source: """ + @JSClass struct Box { + @JSFunction init(_ value: T) async throws(JSException) + } + """, + contains: "Generic @JSFunction declarations cannot be 'async' yet." + ) + } + + @Test + func genericImportedConstructorUnsupportedWrapperFormIsRejected() { + expectDiagnostic( + source: """ + @JSClass struct Box { + @JSFunction init(_ value: [[T]]) throws(JSException) + } + """, + contains: "may only be used as a bare type" + ) + } + + @Test(arguments: [ + ("[[T]]", "@JSFunction func f(_ v: [[T]]) throws(JSException)"), + ("[T?]", "@JSFunction func f(_ v: [T?]) throws(JSException)"), + ("T??", "@JSFunction func f(_ v: T??) throws(JSException)"), + ("[Int: T]", "@JSFunction func f(_ v: [Int: T]) throws(JSException)"), + ]) + func unsupportedGenericWrapperFormsInParameter(label: String, source: String) { + expectDiagnostic( + source: source, + contains: "may only be used as a bare type" + ) + } + + @Test(arguments: [ + ("[[T]]", "@JSFunction func f(_ v: T) throws(JSException) -> [[T]]"), + ("[T?]", "@JSFunction func f(_ v: T) throws(JSException) -> [T?]"), + ("T??", "@JSFunction func f(_ v: T) throws(JSException) -> T??"), + ("[Int: T]", "@JSFunction func f(_ v: T) throws(JSException) -> [Int: T]"), + ]) + func unsupportedGenericWrapperFormsInReturn(label: String, source: String) { + expectDiagnostic( + source: source, + contains: "may only be used as a bare type" + ) + } + + @Test + func genericImportedMethodAsyncIsRejected() { + expectDiagnostic( + source: """ + @JSClass struct Box { + @JSFunction func member(_ value: T) async throws(JSException) -> T + } + """, + contains: "Generic @JSFunction declarations cannot be 'async' yet." + ) + } + + @Test + func genericImportedMethodUnconstrainedParamIsRejected() { + expectDiagnostic( + source: """ + @JSClass struct Box { + @JSFunction func member(_ value: T) throws(JSException) -> T + } + """, + contains: + "Generic parameter 'T' must be constrained to 'BridgedSwiftGenericBridgeable' to be used with @JSFunction." + ) + } + + @Test + func genericImportedFunctionUnusedTypeParamIsRejected() { + expectDiagnostic( + source: """ + @JSFunction func unused() throws(JSException) -> Int + """, + contains: + "The generic parameter 'T' must be used in a parameter or return type of a generic @JSFunction declaration." + ) + } + + @Test + func genericImportedMethodUnusedTypeParamIsRejected() { + expectDiagnostic( + source: """ + @JSClass struct Box { + @JSFunction func member() throws(JSException) -> Int + } + """, + contains: + "The generic parameter 'T' must be used in a parameter or return type of a generic @JSFunction declaration." + ) + } + + @Test + func genericImportedReturnOnlyTypeParamIsAllowed() throws { + let skeleton = try makeSkeleton( + """ + @JSFunction func make() throws(JSException) -> T + """, + moduleName: "App" + ) + let imported = try #require(skeleton.imported) + let functions = imported.children.flatMap { $0.functions } + let function = try #require(functions.first { $0.name == "make" }) + #expect(function.genericParameters == ["T"]) + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/GenericImports.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/GenericImports.swift new file mode 100644 index 000000000..5fd3d0226 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/GenericImports.swift @@ -0,0 +1,74 @@ +@JS +struct GenericPoint { + var x: Int + var y: Int +} + +@JS enum GenericColor { + case red + case green +} + +@JS enum GenericMode: String { + case light + case dark +} + +@JS enum GenericTagged { + case number(value: Int) + case text(value: String) +} + +@JS final class GenericImportBox { + @JS var value: Int + @JS init(value: Int) { + self.value = value + } + @JS func get() -> Int { + value + } +} + +@JSFunction func genericRoundTrip(_ value: T) throws(JSException) -> T + +@JSFunction func genericParse(_ json: String) throws(JSException) -> T + +@JSFunction func importGenericCombine( + _ a: T, + _ b: U +) throws(JSException) -> U + +@JSFunction func importGenericCaseDistinct( + _ a: T, + _ b: t +) throws(JSException) -> T + +@JSFunction func importGenericArray(_ values: [T]) throws(JSException) -> [T] + +@JSFunction func importGenericOptional(_ value: T?) throws(JSException) -> T? + +@JSFunction func importGenericDictionary( + _ values: [String: T] +) throws(JSException) -> [String: T] + +// A generic parameter alongside another parameter that pushes onto the shared +// stacks: both are lowered in reverse declaration order. +@JSFunction func importGenericAfterOptionalArray( + _ values: [Int]?, + _ value: T +) throws(JSException) -> T + +@JSClass struct GenericPairFactory { + @JSFunction init( + _ tag: String, + _ first: T, + _ second: U + ) throws(JSException) +} + +@JSClass struct GenericConsumer { + @JSFunction init(_ value: T) throws(JSException) + @JSFunction func accept(_ value: T) throws(JSException) + @JSFunction func identity(_ value: T) throws(JSException) -> T + @JSFunction static func box(_ value: T) throws(JSException) -> T +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.swift index 42b97761c..7fc853579 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.swift @@ -406,4 +406,36 @@ func _$Surface_label_get(_ self: JSObject) throws(JSException) -> String { throw error } return String.bridgeJSLiftReturn(ret) -} \ No newline at end of file +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + PolygonReference.bridgeJSTypeID, + TagReference.bridgeJSTypeID, + InnerTag.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.swift index b91db4857..9d9c40502 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.swift @@ -191,4 +191,34 @@ extension PolygonReference: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = PolygonReference.bridgeJSMakeTypeHandle() } -extension Polygon: _BridgedSwiftAlias, _BridgedSwiftStackType {} \ No newline at end of file +extension Polygon: _BridgedSwiftAlias, _BridgedSwiftStackType {} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + PolygonReference.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift index cf5208f5d..af2ddb544 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift @@ -655,4 +655,36 @@ func _$importProcessBooleans(_ values: [Bool]) throws(JSException) -> [Bool] { throw error } return [Bool].bridgeJSLiftReturn() -} \ No newline at end of file +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + Point.bridgeJSTypeID, + Direction.bridgeJSTypeID, + Status.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift index e4efe4596..bb51829d7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift @@ -725,4 +725,36 @@ func _$Promise_resolve_SD14AsyncDirectionO(_ promise: JSObject, _ value: [String let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_TestModule_SD14AsyncDirectionO(promiseValue) if let error = _swift_js_take_exception() { throw error } -} \ No newline at end of file +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + AsyncPoint.bridgeJSTypeID, + AsyncDirection.bridgeJSTypeID, + AsyncTheme.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncAssociatedValueEnum.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncAssociatedValueEnum.swift index 5e56f12ad..8ea2e5449 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncAssociatedValueEnum.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncAssociatedValueEnum.swift @@ -117,4 +117,34 @@ func _$Promise_resolve_Sq18AsyncPayloadResultO(_ promise: JSObject, _ value: Opt let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_TestModule_Sq18AsyncPayloadResultO(promiseValue, valueIsSome, valueCaseId) if let error = _swift_js_take_exception() { throw error } -} \ No newline at end of file +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + AsyncPayloadResult.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ClassWithNestedTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ClassWithNestedTypes.swift index 62511b41c..b8736635d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ClassWithNestedTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ClassWithNestedTypes.swift @@ -182,4 +182,35 @@ extension Account.Credentials: BridgedSwiftGenericBridgeable { extension Account.Role: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = Account.Role.bridgeJSMakeTypeHandle() -} \ No newline at end of file +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + Account.Credentials.bridgeJSTypeID, + Account.Role.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.swift index cca403b68..4f343476a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.swift @@ -648,4 +648,36 @@ extension MathOperations: BridgedSwiftGenericBridgeable { extension Status: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = Status.bridgeJSMakeTypeHandle() -} \ No newline at end of file +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + Config.bridgeJSTypeID, + MathOperations.bridgeJSTypeID, + Status.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.swift index d57ec170c..090e93eb0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.swift @@ -172,4 +172,34 @@ func _$importMirrorDictionary(_ values: [String: Double]) throws(JSException) -> throw error } return [String: Double].bridgeJSLiftReturn() -} \ No newline at end of file +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + Counters.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DocComments.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DocComments.swift index 042771659..03dfba96a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DocComments.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DocComments.swift @@ -322,4 +322,35 @@ extension Point: BridgedSwiftGenericBridgeable { extension Color: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = Color.bridgeJSMakeTypeHandle() -} \ No newline at end of file +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + Point.bridgeJSTypeID, + Color.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAlias.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAlias.swift index 6db98303e..812ece23e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAlias.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAlias.swift @@ -55,4 +55,34 @@ extension ColorBox: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = ColorBox.bridgeJSMakeTypeHandle() } -extension Color: _BridgedSwiftAlias, _BridgedSwiftStackType {} \ No newline at end of file +extension Color: _BridgedSwiftAlias, _BridgedSwiftStackType {} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + ColorBox.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.swift index 0fa414bfe..875d6f601 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.swift @@ -675,4 +675,44 @@ extension AllTypesResult: BridgedSwiftGenericBridgeable { extension OptionalAllTypesResult: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = OptionalAllTypesResult.bridgeJSMakeTypeHandle() -} \ No newline at end of file +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + Point.bridgeJSTypeID, + APIResult.bridgeJSTypeID, + ComplexResult.bridgeJSTypeID, + Utilities.Result.bridgeJSTypeID, + NetworkingResult.bridgeJSTypeID, + APIOptionalResult.bridgeJSTypeID, + Precision.bridgeJSTypeID, + CardinalDirection.bridgeJSTypeID, + TypedPayloadResult.bridgeJSTypeID, + AllTypesResult.bridgeJSTypeID, + OptionalAllTypesResult.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValueImport.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValueImport.swift index fcf201eb8..5e597d6ae 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValueImport.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValueImport.swift @@ -113,4 +113,34 @@ func _$PayloadSignalControls_roundTripOptional(_ self: JSObject, _ signal: Optio throw error } return Optional.bridgeJSLiftReturn(ret) -} \ No newline at end of file +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + PayloadSignal.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCase.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCase.swift index a3f1f62dd..c8ea2699f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCase.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCase.swift @@ -243,4 +243,37 @@ extension TSDirection: BridgedSwiftGenericBridgeable { extension PublicStatus: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = PublicStatus.bridgeJSMakeTypeHandle() -} \ No newline at end of file +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + Direction.bridgeJSTypeID, + Status.bridgeJSTypeID, + TSDirection.bridgeJSTypeID, + PublicStatus.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCaseImport.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCaseImport.swift index adef86c78..9bab304a9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCaseImport.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCaseImport.swift @@ -98,4 +98,34 @@ func _$SignalControls_current(_ self: JSObject) throws(JSException) -> Signal { throw error } return Signal.bridgeJSLiftReturn(ret) -} \ No newline at end of file +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + Signal.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift index 9b2fda572..2801e1788 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift @@ -374,4 +374,37 @@ extension Configuration.Port: BridgedSwiftGenericBridgeable { extension Internal.SupportedMethod: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = Internal.SupportedMethod.bridgeJSMakeTypeHandle() -} \ No newline at end of file +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + Networking.API.Method.bridgeJSTypeID, + Configuration.LogLevel.bridgeJSTypeID, + Configuration.Port.bridgeJSTypeID, + Internal.SupportedMethod.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift index 9b2fda572..2801e1788 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift @@ -374,4 +374,37 @@ extension Configuration.Port: BridgedSwiftGenericBridgeable { extension Internal.SupportedMethod: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = Internal.SupportedMethod.bridgeJSMakeTypeHandle() -} \ No newline at end of file +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + Networking.API.Method.bridgeJSTypeID, + Configuration.LogLevel.bridgeJSTypeID, + Configuration.Port.bridgeJSTypeID, + Internal.SupportedMethod.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.swift index 72f481c2d..e91f1b231 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.swift @@ -538,4 +538,45 @@ func _$returnsFeatureFlag() throws(JSException) -> FeatureFlag { throw error } return FeatureFlag.bridgeJSLiftReturn(ret) -} \ No newline at end of file +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + Theme.bridgeJSTypeID, + TSTheme.bridgeJSTypeID, + FeatureFlag.bridgeJSTypeID, + HttpStatus.bridgeJSTypeID, + TSHttpStatus.bridgeJSTypeID, + Priority.bridgeJSTypeID, + FileSize.bridgeJSTypeID, + UserId.bridgeJSTypeID, + TokenId.bridgeJSTypeID, + SessionId.bridgeJSTypeID, + Precision.bridgeJSTypeID, + Ratio.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericImports.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericImports.json new file mode 100644 index 000000000..c7f3e98ae --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericImports.json @@ -0,0 +1,669 @@ +{ + "exported" : { + "aliases" : [ + + ], + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_GenericImportBox_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ] + }, + "isFinal" : true, + "methods" : [ + { + "abiName" : "bjs_GenericImportBox_get", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "get", + "parameters" : [ + + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "name" : "GenericImportBox", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "swiftCallName" : "GenericImportBox" + } + ], + "enums" : [ + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "red" + }, + { + "associatedValues" : [ + + ], + "name" : "green" + } + ], + "emitStyle" : "const", + "name" : "GenericColor", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "GenericColor", + "tsFullPath" : "GenericColor" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "light" + }, + { + "associatedValues" : [ + + ], + "name" : "dark" + } + ], + "emitStyle" : "const", + "name" : "GenericMode", + "rawType" : "String", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "GenericMode", + "tsFullPath" : "GenericMode" + }, + { + "cases" : [ + { + "associatedValues" : [ + { + "label" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "name" : "number" + }, + { + "associatedValues" : [ + { + "label" : "value", + "type" : { + "string" : { + + } + } + } + ], + "name" : "text" + } + ], + "emitStyle" : "const", + "name" : "GenericTagged", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "GenericTagged", + "tsFullPath" : "GenericTagged" + } + ], + "exposeToGlobal" : false, + "functions" : [ + + ], + "protocols" : [ + + ], + "structs" : [ + { + "methods" : [ + + ], + "name" : "GenericPoint", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "x", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "y", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "swiftCallName" : "GenericPoint" + } + ] + }, + "imported" : { + "children" : [ + { + "functions" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + "T" + ], + "name" : "genericRoundTrip", + "parameters" : [ + { + "name" : "value", + "type" : { + "generic" : { + "_0" : "T" + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "T" + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + "T" + ], + "name" : "genericParse", + "parameters" : [ + { + "name" : "json", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "T" + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + "T", + "U" + ], + "name" : "importGenericCombine", + "parameters" : [ + { + "name" : "a", + "type" : { + "generic" : { + "_0" : "T" + } + } + }, + { + "name" : "b", + "type" : { + "generic" : { + "_0" : "U" + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "U" + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + "T", + "t" + ], + "name" : "importGenericCaseDistinct", + "parameters" : [ + { + "name" : "a", + "type" : { + "generic" : { + "_0" : "T" + } + } + }, + { + "name" : "b", + "type" : { + "generic" : { + "_0" : "t" + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "T" + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + "T" + ], + "name" : "importGenericArray", + "parameters" : [ + { + "name" : "values", + "type" : { + "array" : { + "_0" : { + "generic" : { + "_0" : "T" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "generic" : { + "_0" : "T" + } + } + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + "T" + ], + "name" : "importGenericOptional", + "parameters" : [ + { + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "generic" : { + "_0" : "T" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "generic" : { + "_0" : "T" + } + }, + "_1" : "null" + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + "T" + ], + "name" : "importGenericDictionary", + "parameters" : [ + { + "name" : "values", + "type" : { + "dictionary" : { + "_0" : { + "generic" : { + "_0" : "T" + } + } + } + } + } + ], + "returnType" : { + "dictionary" : { + "_0" : { + "generic" : { + "_0" : "T" + } + } + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + "T" + ], + "name" : "importGenericAfterOptionalArray", + "parameters" : [ + { + "name" : "values", + "type" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + }, + "_1" : "null" + } + } + }, + { + "name" : "value", + "type" : { + "generic" : { + "_0" : "T" + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "T" + } + } + } + ], + "types" : [ + { + "accessLevel" : "internal", + "constructor" : { + "accessLevel" : "internal", + "genericParameters" : [ + "T", + "U" + ], + "parameters" : [ + { + "name" : "tag", + "type" : { + "string" : { + + } + } + }, + { + "name" : "first", + "type" : { + "generic" : { + "_0" : "T" + } + } + }, + { + "name" : "second", + "type" : { + "generic" : { + "_0" : "U" + } + } + } + ] + }, + "getters" : [ + + ], + "methods" : [ + + ], + "name" : "GenericPairFactory", + "setters" : [ + + ], + "staticMethods" : [ + + ] + }, + { + "accessLevel" : "internal", + "constructor" : { + "accessLevel" : "internal", + "genericParameters" : [ + "T" + ], + "parameters" : [ + { + "name" : "value", + "type" : { + "generic" : { + "_0" : "T" + } + } + } + ] + }, + "getters" : [ + + ], + "methods" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + "T" + ], + "name" : "accept", + "parameters" : [ + { + "name" : "value", + "type" : { + "generic" : { + "_0" : "T" + } + } + } + ], + "returnType" : { + "void" : { + + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + "T" + ], + "name" : "identity", + "parameters" : [ + { + "name" : "value", + "type" : { + "generic" : { + "_0" : "T" + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "T" + } + } + } + ], + "name" : "GenericConsumer", + "setters" : [ + + ], + "staticMethods" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + "T" + ], + "name" : "box", + "parameters" : [ + { + "name" : "value", + "type" : { + "generic" : { + "_0" : "T" + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "T" + } + } + } + ] + } + ] + } + ] + }, + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericImports.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericImports.swift new file mode 100644 index 000000000..044fd0e57 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericImports.swift @@ -0,0 +1,520 @@ +extension GenericColor: _BridgedSwiftCaseEnum { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + return bridgeJSRawValue + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> GenericColor { + return bridgeJSLiftParameter(value) + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> GenericColor { + return GenericColor(bridgeJSRawValue: value)! + } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { + return bridgeJSLowerParameter() + } + + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { + switch bridgeJSRawValue { + case 0: + self = .red + case 1: + self = .green + default: + return nil + } + } + + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { + switch self { + case .red: + return 0 + case .green: + return 1 + } + } +} + +extension GenericMode: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +} + +extension GenericTagged: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> GenericTagged { + switch caseId { + case 0: + return .number(value: Int.bridgeJSStackPop()) + case 1: + return .text(value: String.bridgeJSStackPop()) + default: + fatalError("Unknown GenericTagged case ID: \(caseId)") + } + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { + switch self { + case .number(let value): + value.bridgeJSStackPush() + return Int32(0) + case .text(let value): + value.bridgeJSStackPush() + return Int32(1) + } + } +} + +extension GenericPoint: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> GenericPoint { + let y = Int.bridgeJSStackPop() + let x = Int.bridgeJSStackPop() + return GenericPoint(x: x, y: y) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.x.bridgeJSStackPush() + self.y.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_GenericPoint(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_GenericPoint())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_GenericPoint") +fileprivate func _bjs_struct_lower_GenericPoint_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_GenericPoint_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_GenericPoint(_ objectId: Int32) -> Void { + return _bjs_struct_lower_GenericPoint_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_GenericPoint") +fileprivate func _bjs_struct_lift_GenericPoint_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_GenericPoint_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_GenericPoint() -> Int32 { + return _bjs_struct_lift_GenericPoint_extern() +} + +@_expose(wasm, "bjs_GenericImportBox_init") +@_cdecl("bjs_GenericImportBox_init") +public func _bjs_GenericImportBox_init(_ value: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = GenericImportBox(value: Int.bridgeJSLiftParameter(value)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_GenericImportBox_get") +@_cdecl("bjs_GenericImportBox_get") +public func _bjs_GenericImportBox_get(_ _self: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let ret = GenericImportBox.bridgeJSLiftParameter(_self).get() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_GenericImportBox_value_get") +@_cdecl("bjs_GenericImportBox_value_get") +public func _bjs_GenericImportBox_value_get(_ _self: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let ret = GenericImportBox.bridgeJSLiftParameter(_self).value + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_GenericImportBox_value_set") +@_cdecl("bjs_GenericImportBox_value_set") +public func _bjs_GenericImportBox_value_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { + #if arch(wasm32) + GenericImportBox.bridgeJSLiftParameter(_self).value = Int.bridgeJSLiftParameter(value) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_GenericImportBox_deinit") +@_cdecl("bjs_GenericImportBox_deinit") +public func _bjs_GenericImportBox_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension GenericImportBox: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_GenericImportBox_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_GenericImportBox_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_GenericImportBox_wrap") +fileprivate func _bjs_GenericImportBox_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_GenericImportBox_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_GenericImportBox_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_GenericImportBox_wrap_extern(pointer) +} + +extension GenericPoint: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = GenericPoint.bridgeJSMakeTypeHandle() +} + +extension GenericImportBox: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = GenericImportBox.bridgeJSMakeTypeHandle() +} + +extension GenericColor: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = GenericColor.bridgeJSMakeTypeHandle() +} + +extension GenericMode: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = GenericMode.bridgeJSMakeTypeHandle() +} + +extension GenericTagged: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = GenericTagged.bridgeJSMakeTypeHandle() +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_genericRoundTrip") +fileprivate func bjs_genericRoundTrip_extern(_ _generic0TypeId: Int32) -> Void +#else +fileprivate func bjs_genericRoundTrip_extern(_ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_genericRoundTrip(_ _generic0TypeId: Int32) -> Void { + return bjs_genericRoundTrip_extern(_generic0TypeId) +} + +func _$genericRoundTrip(_ value: T) throws(JSException) -> T { + value.bridgeJSStackPush() + bjs_genericRoundTrip(T.bridgeJSTypeID) + if let error = _swift_js_take_exception() { + throw error + } + return T.bridgeJSStackPop() +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_genericParse") +fileprivate func bjs_genericParse_extern(_ jsonBytes: Int32, _ jsonLength: Int32, _ _generic0TypeId: Int32) -> Void +#else +fileprivate func bjs_genericParse_extern(_ jsonBytes: Int32, _ jsonLength: Int32, _ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_genericParse(_ jsonBytes: Int32, _ jsonLength: Int32, _ _generic0TypeId: Int32) -> Void { + return bjs_genericParse_extern(jsonBytes, jsonLength, _generic0TypeId) +} + +func _$genericParse(_ json: String) throws(JSException) -> T { + json.bridgeJSWithLoweredParameter { (jsonBytes, jsonLength) in + bjs_genericParse(jsonBytes, jsonLength, T.bridgeJSTypeID) + } + if let error = _swift_js_take_exception() { + throw error + } + return T.bridgeJSStackPop() +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_importGenericCombine") +fileprivate func bjs_importGenericCombine_extern(_ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void +#else +fileprivate func bjs_importGenericCombine_extern(_ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_importGenericCombine(_ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void { + return bjs_importGenericCombine_extern(_generic0TypeId, _generic1TypeId) +} + +func _$importGenericCombine(_ a: T, _ b: U) throws(JSException) -> U { + b.bridgeJSStackPush() + a.bridgeJSStackPush() + bjs_importGenericCombine(T.bridgeJSTypeID, U.bridgeJSTypeID) + if let error = _swift_js_take_exception() { + throw error + } + return U.bridgeJSStackPop() +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_importGenericCaseDistinct") +fileprivate func bjs_importGenericCaseDistinct_extern(_ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void +#else +fileprivate func bjs_importGenericCaseDistinct_extern(_ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_importGenericCaseDistinct(_ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void { + return bjs_importGenericCaseDistinct_extern(_generic0TypeId, _generic1TypeId) +} + +func _$importGenericCaseDistinct(_ a: T, _ b: t) throws(JSException) -> T { + b.bridgeJSStackPush() + a.bridgeJSStackPush() + bjs_importGenericCaseDistinct(T.bridgeJSTypeID, t.bridgeJSTypeID) + if let error = _swift_js_take_exception() { + throw error + } + return T.bridgeJSStackPop() +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_importGenericArray") +fileprivate func bjs_importGenericArray_extern(_ _generic0TypeId: Int32) -> Void +#else +fileprivate func bjs_importGenericArray_extern(_ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_importGenericArray(_ _generic0TypeId: Int32) -> Void { + return bjs_importGenericArray_extern(_generic0TypeId) +} + +func _$importGenericArray(_ values: [T]) throws(JSException) -> [T] { + let _ = values.bridgeJSLowerParameter() + bjs_importGenericArray(T.bridgeJSTypeID) + if let error = _swift_js_take_exception() { + throw error + } + return [T].bridgeJSLiftReturn() +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_importGenericOptional") +fileprivate func bjs_importGenericOptional_extern(_ _generic0TypeId: Int32) -> Void +#else +fileprivate func bjs_importGenericOptional_extern(_ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_importGenericOptional(_ _generic0TypeId: Int32) -> Void { + return bjs_importGenericOptional_extern(_generic0TypeId) +} + +func _$importGenericOptional(_ value: Optional) throws(JSException) -> Optional { + value.bridgeJSStackPush() + bjs_importGenericOptional(T.bridgeJSTypeID) + if let error = _swift_js_take_exception() { + throw error + } + return Optional.bridgeJSStackPop() +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_importGenericDictionary") +fileprivate func bjs_importGenericDictionary_extern(_ _generic0TypeId: Int32) -> Void +#else +fileprivate func bjs_importGenericDictionary_extern(_ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_importGenericDictionary(_ _generic0TypeId: Int32) -> Void { + return bjs_importGenericDictionary_extern(_generic0TypeId) +} + +func _$importGenericDictionary(_ values: [String: T]) throws(JSException) -> [String: T] { + let _ = values.bridgeJSLowerParameter() + bjs_importGenericDictionary(T.bridgeJSTypeID) + if let error = _swift_js_take_exception() { + throw error + } + return [String: T].bridgeJSLiftReturn() +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_importGenericAfterOptionalArray") +fileprivate func bjs_importGenericAfterOptionalArray_extern(_ values: Int32, _ _generic0TypeId: Int32) -> Void +#else +fileprivate func bjs_importGenericAfterOptionalArray_extern(_ values: Int32, _ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_importGenericAfterOptionalArray(_ values: Int32, _ _generic0TypeId: Int32) -> Void { + return bjs_importGenericAfterOptionalArray_extern(values, _generic0TypeId) +} + +func _$importGenericAfterOptionalArray(_ values: Optional<[Int]>, _ value: T) throws(JSException) -> T { + value.bridgeJSStackPush() + let valuesIsSome = values.bridgeJSLowerParameter() + bjs_importGenericAfterOptionalArray(valuesIsSome, T.bridgeJSTypeID) + if let error = _swift_js_take_exception() { + throw error + } + return T.bridgeJSStackPop() +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_GenericPairFactory_init") +fileprivate func bjs_GenericPairFactory_init_extern(_ tagBytes: Int32, _ tagLength: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Int32 +#else +fileprivate func bjs_GenericPairFactory_init_extern(_ tagBytes: Int32, _ tagLength: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_GenericPairFactory_init(_ tagBytes: Int32, _ tagLength: Int32, _ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Int32 { + return bjs_GenericPairFactory_init_extern(tagBytes, tagLength, _generic0TypeId, _generic1TypeId) +} + +func _$GenericPairFactory_init(_ tag: String, _ first: T, _ second: U) throws(JSException) -> JSObject { + let ret0 = tag.bridgeJSWithLoweredParameter { (tagBytes, tagLength) in + second.bridgeJSStackPush() + first.bridgeJSStackPush() + let ret = bjs_GenericPairFactory_init(tagBytes, tagLength, T.bridgeJSTypeID, U.bridgeJSTypeID) + return ret + } + let ret = ret0 + if let error = _swift_js_take_exception() { + throw error + } + return JSObject.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_GenericConsumer_init") +fileprivate func bjs_GenericConsumer_init_extern(_ _generic0TypeId: Int32) -> Int32 +#else +fileprivate func bjs_GenericConsumer_init_extern(_ _generic0TypeId: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_GenericConsumer_init(_ _generic0TypeId: Int32) -> Int32 { + return bjs_GenericConsumer_init_extern(_generic0TypeId) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_GenericConsumer_box_static") +fileprivate func bjs_GenericConsumer_box_static_extern(_ _generic0TypeId: Int32) -> Void +#else +fileprivate func bjs_GenericConsumer_box_static_extern(_ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_GenericConsumer_box_static(_ _generic0TypeId: Int32) -> Void { + return bjs_GenericConsumer_box_static_extern(_generic0TypeId) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_GenericConsumer_accept") +fileprivate func bjs_GenericConsumer_accept_extern(_ self: Int32, _ _generic0TypeId: Int32) -> Void +#else +fileprivate func bjs_GenericConsumer_accept_extern(_ self: Int32, _ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_GenericConsumer_accept(_ self: Int32, _ _generic0TypeId: Int32) -> Void { + return bjs_GenericConsumer_accept_extern(self, _generic0TypeId) +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_GenericConsumer_identity") +fileprivate func bjs_GenericConsumer_identity_extern(_ self: Int32, _ _generic0TypeId: Int32) -> Void +#else +fileprivate func bjs_GenericConsumer_identity_extern(_ self: Int32, _ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_GenericConsumer_identity(_ self: Int32, _ _generic0TypeId: Int32) -> Void { + return bjs_GenericConsumer_identity_extern(self, _generic0TypeId) +} + +func _$GenericConsumer_init(_ value: T) throws(JSException) -> JSObject { + value.bridgeJSStackPush() + let ret = bjs_GenericConsumer_init(T.bridgeJSTypeID) + if let error = _swift_js_take_exception() { + throw error + } + return JSObject.bridgeJSLiftReturn(ret) +} + +func _$GenericConsumer_box(_ value: T) throws(JSException) -> T { + value.bridgeJSStackPush() + bjs_GenericConsumer_box_static(T.bridgeJSTypeID) + if let error = _swift_js_take_exception() { + throw error + } + return T.bridgeJSStackPop() +} + +func _$GenericConsumer_accept(_ self: JSObject, _ value: T) throws(JSException) -> Void { + value.bridgeJSStackPush() + let selfValue = self.bridgeJSLowerParameter() + bjs_GenericConsumer_accept(selfValue, T.bridgeJSTypeID) + if let error = _swift_js_take_exception() { + throw error + } +} + +func _$GenericConsumer_identity(_ self: JSObject, _ value: T) throws(JSException) -> T { + value.bridgeJSStackPush() + let selfValue = self.bridgeJSLowerParameter() + bjs_GenericConsumer_identity(selfValue, T.bridgeJSTypeID) + if let error = _swift_js_take_exception() { + throw error + } + return T.bridgeJSStackPop() +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + GenericPoint.bridgeJSTypeID, + GenericImportBox.bridgeJSTypeID, + GenericColor.bridgeJSTypeID, + GenericMode.bridgeJSTypeID, + GenericTagged.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.swift index 0e36253b7..dfec6b6a0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.swift @@ -126,4 +126,34 @@ func _$Foo_init() throws(JSException) -> JSObject { throw error } return JSObject.bridgeJSLiftReturn(ret) -} \ No newline at end of file +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + FooContainer.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSNameOverride.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSNameOverride.swift index 745843e34..5f767abdb 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSNameOverride.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSNameOverride.swift @@ -356,4 +356,35 @@ extension RenamedVector: BridgedSwiftGenericBridgeable { extension RenamedEnumMembers: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = RenamedEnumMembers.bridgeJSMakeTypeHandle() -} \ No newline at end of file +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + RenamedVector.bridgeJSTypeID, + RenamedEnumMembers.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedType.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedType.swift index bc910951f..ca1c98a75 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedType.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedType.swift @@ -184,4 +184,35 @@ extension User.Stats: BridgedSwiftGenericBridgeable { extension Player.Stats: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = Player.Stats.bridgeJSMakeTypeHandle() -} \ No newline at end of file +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + User.Stats.bridgeJSTypeID, + Player.Stats.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift index a92716d44..2ef680b8a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift @@ -1059,4 +1059,37 @@ extension Result: BridgedSwiftGenericBridgeable { extension Priority: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = Priority.bridgeJSMakeTypeHandle() -} \ No newline at end of file +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + Direction.bridgeJSTypeID, + ExampleEnum.bridgeJSTypeID, + Result.bridgeJSTypeID, + Priority.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift index 1f33a0b1d..18e91616c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift @@ -215,4 +215,35 @@ extension Calculator: BridgedSwiftGenericBridgeable { extension APIResult: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = APIResult.bridgeJSMakeTypeHandle() -} \ No newline at end of file +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + Calculator.bridgeJSTypeID, + APIResult.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift index 1f33a0b1d..18e91616c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift @@ -215,4 +215,35 @@ extension Calculator: BridgedSwiftGenericBridgeable { extension APIResult: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = APIResult.bridgeJSMakeTypeHandle() -} \ No newline at end of file +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + Calculator.bridgeJSTypeID, + APIResult.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.swift index 2c6aa9add..75c4382dd 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.swift @@ -342,4 +342,34 @@ fileprivate func _bjs_PropertyClass_wrap_extern(_ pointer: UnsafeMutableRawPoint extension PropertyEnum: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = PropertyEnum.bridgeJSMakeTypeHandle() -} \ No newline at end of file +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + PropertyEnum.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.swift index 2c6aa9add..75c4382dd 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.swift @@ -342,4 +342,34 @@ fileprivate func _bjs_PropertyClass_wrap_extern(_ pointer: UnsafeMutableRawPoint extension PropertyEnum: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = PropertyEnum.bridgeJSMakeTypeHandle() -} \ No newline at end of file +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + PropertyEnum.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StructWithNestedTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StructWithNestedTypes.swift index b557b423f..1b8a69739 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StructWithNestedTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StructWithNestedTypes.swift @@ -274,4 +274,40 @@ extension Widget.Variant: BridgedSwiftGenericBridgeable { extension Widget.Layout.Alignment: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = Widget.Layout.Alignment.bridgeJSMakeTypeHandle() -} \ No newline at end of file +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + Shape.bridgeJSTypeID, + Widget.bridgeJSTypeID, + Widget.Layout.bridgeJSTypeID, + Widget.Bounds.bridgeJSTypeID, + Shape.Kind.bridgeJSTypeID, + Widget.Variant.bridgeJSTypeID, + Widget.Layout.Alignment.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift index cde864d3c..bad3ba0e1 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift @@ -2740,4 +2740,38 @@ func _$Promise_resolve_9APIResultO(_ promise: JSObject, _ value: APIResult) thro let promiseValue = promise.bridgeJSLowerParameter() promise_resolve_TestModule_9APIResultO(promiseValue, valueCaseId) if let error = _swift_js_take_exception() { throw error } -} \ No newline at end of file +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + Animal.bridgeJSTypeID, + Direction.bridgeJSTypeID, + Theme.bridgeJSTypeID, + HttpStatus.bridgeJSTypeID, + APIResult.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift index 3414b158d..7aca6afd5 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift @@ -666,4 +666,42 @@ extension Vector2D: BridgedSwiftGenericBridgeable { extension Precision: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = Precision.bridgeJSMakeTypeHandle() -} \ No newline at end of file +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + DataPoint.bridgeJSTypeID, + Address.bridgeJSTypeID, + Person.bridgeJSTypeID, + Session.bridgeJSTypeID, + Measurement.bridgeJSTypeID, + ConfigStruct.bridgeJSTypeID, + Container.bridgeJSTypeID, + Vector2D.bridgeJSTypeID, + Precision.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.swift index 2eb0e70b7..a5c5d9fd8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.swift @@ -92,4 +92,34 @@ func _$roundTripOptional(_ point: Optional) throws(JSException) -> Option throw error } return Optional.bridgeJSLiftReturn() -} \ No newline at end of file +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + Point.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/UnsafePointer.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/UnsafePointer.swift index 93abd19e8..615608687 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/UnsafePointer.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/UnsafePointer.swift @@ -181,4 +181,34 @@ public func _bjs_roundTripPointerFields() -> Void { extension PointerFields: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = PointerFields.bridgeJSMakeTypeHandle() -} \ No newline at end of file +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + PointerFields.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.d.ts index 9815b6514..e3092afb3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.d.ts @@ -67,6 +67,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.d.ts index 4d2bab311..73ea3b570 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.d.ts @@ -27,6 +27,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.d.ts index 529b16095..f48189956 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.d.ts @@ -91,6 +91,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.d.ts index fefbf0039..507a96d4a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.d.ts @@ -55,6 +55,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.d.ts index c0c8900d7..d25336ef7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.d.ts @@ -29,6 +29,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.d.ts index f1bf7e0c6..e612ae1e1 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.d.ts @@ -19,6 +19,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.d.ts index 97a9c23ad..491a66795 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.d.ts @@ -19,6 +19,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.d.ts index a2bd7b41b..5537696c4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.d.ts @@ -47,6 +47,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.d.ts index 7cec6e66b..961b9fa5b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.d.ts @@ -161,6 +161,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.d.ts index 2479e3f25..652177cd8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.d.ts @@ -35,6 +35,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.d.ts index f37d8945d..196ef73fe 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.d.ts @@ -136,6 +136,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.d.ts index 4921cd937..d2772fa8b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.d.ts @@ -26,6 +26,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.d.ts index 9e6d967ff..36fc92474 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.d.ts @@ -195,6 +195,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.d.ts index c980b7dbf..d29256af4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.d.ts @@ -35,6 +35,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.d.ts index 8ea0aa79b..5581df31e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.d.ts @@ -56,6 +56,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.d.ts index 03e210f3c..fe48c9174 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.d.ts @@ -29,6 +29,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.d.ts index 403ef2149..0ca8b16b9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.d.ts @@ -154,6 +154,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.d.ts index f5d357a64..b5a85a082 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.d.ts @@ -115,6 +115,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.d.ts index e43673e7a..fbd5ad637 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.d.ts @@ -169,6 +169,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.d.ts index 3eea52594..d6ab5aa8f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.d.ts @@ -29,6 +29,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.d.ts new file mode 100644 index 000000000..026713ce3 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.d.ts @@ -0,0 +1,87 @@ +// 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`. + +export const GenericColorValues: { + readonly Red: 0; + readonly Green: 1; +}; +export type GenericColorTag = typeof GenericColorValues[keyof typeof GenericColorValues]; + +export const GenericModeValues: { + readonly Light: "light"; + readonly Dark: "dark"; +}; +export type GenericModeTag = typeof GenericModeValues[keyof typeof GenericModeValues]; + +export const GenericTaggedValues: { + readonly Tag: { + readonly Number: 0; + readonly Text: 1; + }; +}; + +export type GenericTaggedTag = + { tag: typeof GenericTaggedValues.Tag.Number; value: number } | { tag: typeof GenericTaggedValues.Tag.Text; value: string } + +export interface GenericPoint { + x: number; + y: number; +} +export type GenericColorObject = typeof GenericColorValues; + +export type GenericModeObject = typeof GenericModeValues; + +export type GenericTaggedObject = typeof GenericTaggedValues; + +/// Represents a Swift heap object like a class instance or an actor instance. +export interface SwiftHeapObject { + /// Release the heap object. + /// + /// Note: Calling this method will release the heap object and it will no longer be accessible. + release(): void; +} +export interface GenericImportBox extends SwiftHeapObject { + get(): number; + value: number; +} +export interface GenericPairFactory { +} +export interface GenericConsumer { + accept(value: T): void; + identity(value: T): T; +} +export type Exports = { + GenericColor: GenericColorObject + GenericMode: GenericModeObject + GenericTagged: GenericTaggedObject + GenericImportBox: { + new(value: number): GenericImportBox; + }, +} +export type Imports = { + genericRoundTrip(value: T): T; + genericParse(json: string): T; + importGenericCombine(a: T, b: U): U; + importGenericCaseDistinct(a: T, b: t): T; + importGenericArray(values: T[]): T[]; + importGenericOptional(value: T | null): T | null; + importGenericDictionary(values: Record): Record; + importGenericAfterOptionalArray(values: number[] | null, value: T): T; + GenericPairFactory: { + new(tag: string, first: T, second: U): GenericPairFactory; + } + GenericConsumer: { + new(value: T): GenericConsumer; + box(value: T): T; + } +} +export function createInstantiator(options: { + imports: Imports; +}, swift: any): Promise<{ + addImports: (importObject: WebAssembly.Imports) => void; + setInstance: (instance: WebAssembly.Instance) => void; + createExports: (instance: WebAssembly.Instance) => Exports; +}>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js new file mode 100644 index 000000000..e01f6fffc --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js @@ -0,0 +1,930 @@ +// 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`. + +export const GenericColorValues = { + Red: 0, + Green: 1, +}; + +export const GenericModeValues = { + Light: "light", + Dark: "dark", +}; + +export const GenericTaggedValues = { + Tag: { + Number: 0, + Text: 1, + }, +}; +export async function createInstantiator(options, swift) { + let instance; + let memory; + let setException; + let decodeString; + const textDecoder = new TextDecoder("utf-8"); + const textEncoder = new TextEncoder("utf-8"); + let tmpRetString; + let tmpRetBytes; + let tmpRetException; + let tmpRetOptionalBool; + let tmpRetOptionalInt; + let tmpRetOptionalFloat; + let tmpRetOptionalDouble; + let tmpRetOptionalHeapObject; + let strStack = []; + let i32Stack = []; + let i64Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; + let taStack = []; + const enumHelpers = {}; + const structHelpers = {}; + const __bjs_codecByTypeId = new Map(); + let __bjs_typeHandlesRegistered = false; + function __bjs_registerTypeHandles() { + if (__bjs_typeHandlesRegistered) { + return; + } + __bjs_typeHandlesRegistered = true; + instance.exports["bjs_TestModule_register_type_handles"](); + } + function __bjs_codecForTypeId(typeId) { + __bjs_registerTypeHandles(); + const codec = __bjs_codecByTypeId.get(typeId); + if (!codec) { + throw new Error("BridgeJS: no codec registered for type ID " + typeId); + } + return codec; + } + + let _exports = null; + let bjs = null; + function __bjs_arrayCodec(elementCodec) { + return { + lower(value) { + for (let i = 0; i < value.length; i++) { + elementCodec.lower(value[i]); + } + i32Stack.push(value.length); + }, + lift() { + const count = i32Stack.pop(); + if (count === -1) { + return taStack.pop(); + } + const result = new Array(count); + for (let i = count - 1; i >= 0; i--) { + result[i] = elementCodec.lift(); + } + return result; + }, + }; + } + function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { + return { + lower(value) { + const isSome = isUndefinedOr ? value !== undefined : value != null; + if (isSome) { + elementCodec.lower(value); + i32Stack.push(1); + } else { + i32Stack.push(0); + } + }, + lift() { + if (i32Stack.pop() === 0) { + return isUndefinedOr ? undefined : null; + } + return elementCodec.lift(); + }, + }; + } + function __bjs_dictCodec(valueCodec) { + return { + lower(value) { + const keys = Object.keys(value); + for (let i = 0; i < keys.length; i++) { + __bjs_stringCodec.lower(keys[i]); + valueCodec.lower(value[keys[i]]); + } + i32Stack.push(keys.length); + }, + lift() { + const count = i32Stack.pop(); + const result = {}; + for (let i = 0; i < count; i++) { + const value = valueCodec.lift(); + const key = __bjs_stringCodec.lift(); + result[key] = value; + } + return result; + }, + }; + } + function __bjs_enumCodec(helper) { + return { + lower(value) { + i32Stack.push(helper.lower(value)); + }, + lift() { + return helper.lift(i32Stack.pop()); + }, + }; + } + + const __bjs_stringCodec = { + lower: (v) => { + const bytes = textEncoder.encode(v); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + }, + lift: () => { + const string = strStack.pop(); + return string; + }, + }; + const __bjs_primitiveCodecs = { + Bool: { + lower: (v) => { + i32Stack.push(v ? 1 : 0); + }, + lift: () => { + const bool = i32Stack.pop() !== 0; + return bool; + }, + }, + Int: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + Int8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt8: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt16: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return int; + }, + }, + UInt32: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + UInt: { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const int = i32Stack.pop() >>> 0; + return int; + }, + }, + Int64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + UInt64: { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const int = i64Stack.pop(); + return int; + }, + }, + Float: { + lower: (v) => { + f32Stack.push(Math.fround(v)); + }, + lift: () => { + const f32 = f32Stack.pop(); + return f32; + }, + }, + Double: { + lower: (v) => { + f64Stack.push(v); + }, + lift: () => { + const f64 = f64Stack.pop(); + return f64; + }, + }, + String: __bjs_stringCodec, + JSValue: { + lower: (v) => { + const [vKind, vPayload1, vPayload2] = __bjs_jsValueLower(v); + i32Stack.push(vKind); + i32Stack.push(vPayload1); + f64Stack.push(vPayload2); + }, + lift: () => { + const jsValuePayload2 = f64Stack.pop(); + const jsValuePayload1 = i32Stack.pop(); + const jsValueKind = i32Stack.pop(); + const jsValue = __bjs_jsValueLift(jsValueKind, jsValuePayload1, jsValuePayload2); + return jsValue; + }, + }, + }; + + function __bjs_jsValueLower(value) { + let kind; + let payload1; + let payload2; + if (value === null) { + kind = 4; + payload1 = 0; + payload2 = 0; + } else { + switch (typeof value) { + case "boolean": + kind = 0; + payload1 = value ? 1 : 0; + payload2 = 0; + break; + case "number": + kind = 2; + payload1 = 0; + payload2 = value; + break; + case "string": + kind = 1; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "undefined": + kind = 5; + payload1 = 0; + payload2 = 0; + break; + case "object": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "function": + kind = 3; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "symbol": + kind = 7; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + case "bigint": + kind = 8; + payload1 = swift.memory.retain(value); + payload2 = 0; + break; + default: + throw new TypeError("Unsupported JSValue type"); + } + } + return [kind, payload1, payload2]; + } + function __bjs_jsValueLift(kind, payload1, payload2) { + let jsValue; + switch (kind) { + case 0: + jsValue = payload1 !== 0; + break; + case 1: + jsValue = swift.memory.getObject(payload1); + break; + case 2: + jsValue = payload2; + break; + case 3: + jsValue = swift.memory.getObject(payload1); + break; + case 4: + jsValue = null; + break; + case 5: + jsValue = undefined; + break; + case 7: + jsValue = swift.memory.getObject(payload1); + break; + case 8: + jsValue = swift.memory.getObject(payload1); + break; + default: + throw new TypeError("Unsupported JSValue kind " + kind); + } + return jsValue; + } + + const __bjs_createGenericPointHelpers = () => ({ + lower: (value) => { + i32Stack.push((value.x | 0)); + i32Stack.push((value.y | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + const int1 = i32Stack.pop(); + return { x: int1, y: int }; + } + }); + const __bjs_createGenericTaggedValuesHelpers = () => ({ + lower: (value) => { + const enumTag = value.tag; + switch (enumTag) { + case GenericTaggedValues.Tag.Number: { + i32Stack.push((value.value | 0)); + return GenericTaggedValues.Tag.Number; + } + case GenericTaggedValues.Tag.Text: { + const bytes = textEncoder.encode(value.value); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + return GenericTaggedValues.Tag.Text; + } + default: throw new Error("Unknown GenericTaggedValues tag: " + String(enumTag)); + } + }, + lift: (tag) => { + tag = tag | 0; + switch (tag) { + case GenericTaggedValues.Tag.Number: { + const int = i32Stack.pop(); + return { tag: GenericTaggedValues.Tag.Number, value: int }; + } + case GenericTaggedValues.Tag.Text: { + const string = strStack.pop(); + return { tag: GenericTaggedValues.Tag.Text, value: string }; + } + default: throw new Error("Unknown GenericTaggedValues tag returned from Swift: " + String(tag)); + } + } + }); + + return { + /** + * @param {WebAssembly.Imports} importObject + */ + addImports: (importObject, importsContext) => { + bjs = {}; + importObject["bjs"] = bjs; + const imports = options.getImports(importsContext); + bjs["swift_js_return_string"] = function(ptr, len) { + tmpRetString = decodeString(ptr, len); + } + bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { + const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); + bytes.set(source); + } + bjs["swift_js_make_js_string"] = function(ptr, len) { + return swift.memory.retain(decodeString(ptr, len)); + } + bjs["swift_js_init_memory_with_result"] = function(ptr, len) { + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); + target.set(tmpRetBytes); + tmpRetBytes = undefined; + } + bjs["swift_js_throw"] = function(id) { + tmpRetException = swift.memory.retainByRef(id); + } + bjs["swift_js_retain"] = function(id) { + return swift.memory.retainByRef(id); + } + bjs["swift_js_release"] = function(id) { + swift.memory.release(id); + } + bjs["swift_js_push_i32"] = function(v) { + i32Stack.push(v | 0); + } + bjs["swift_js_push_f32"] = function(v) { + f32Stack.push(Math.fround(v)); + } + bjs["swift_js_push_f64"] = function(v) { + f64Stack.push(v); + } + bjs["swift_js_push_string"] = function(ptr, len) { + const value = decodeString(ptr, len); + strStack.push(value); + } + bjs["swift_js_pop_i32"] = function() { + return i32Stack.pop(); + } + bjs["swift_js_pop_f32"] = function() { + return f32Stack.pop(); + } + bjs["swift_js_pop_f64"] = function() { + return f64Stack.pop(); + } + bjs["swift_js_push_pointer"] = function(pointer) { + ptrStack.push(pointer); + } + bjs["swift_js_pop_pointer"] = function() { + return ptrStack.pop(); + } + bjs["swift_js_push_i64"] = function(v) { + i64Stack.push(v); + } + bjs["swift_js_pop_i64"] = function() { + return i64Stack.pop(); + } + const taCtors = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array]; + bjs["swift_js_push_typed_array"] = function(kind, ptr, count) { + const Ctor = taCtors[kind]; + const byteLen = count * Ctor.BYTES_PER_ELEMENT; + const copy = memory.buffer.slice(ptr, ptr + byteLen); + taStack.push(Array.from(new Ctor(copy))); + } + bjs["swift_js_struct_lower_GenericPoint"] = function(objectId) { + structHelpers.GenericPoint.lower(swift.memory.getObject(objectId)); + } + bjs["swift_js_struct_lift_GenericPoint"] = function() { + const value = structHelpers.GenericPoint.lift(); + return swift.memory.retain(value); + } + bjs["bjs_TestModule_register_type_handles"] = function(base, count) { + const codecs = [ + __bjs_primitiveCodecs.Bool, + __bjs_primitiveCodecs.Int, + __bjs_primitiveCodecs.Int8, + __bjs_primitiveCodecs.UInt8, + __bjs_primitiveCodecs.Int16, + __bjs_primitiveCodecs.UInt16, + __bjs_primitiveCodecs.Int32, + __bjs_primitiveCodecs.UInt32, + __bjs_primitiveCodecs.UInt, + __bjs_primitiveCodecs.Int64, + __bjs_primitiveCodecs.UInt64, + __bjs_primitiveCodecs.Float, + __bjs_primitiveCodecs.Double, + __bjs_primitiveCodecs.String, + __bjs_primitiveCodecs.JSValue, + ].concat([ + { + lower: (v) => { + structHelpers.GenericPoint.lower(v); + }, + lift: () => { + const struct = structHelpers.GenericPoint.lift(); + return struct; + }, + }, + { + lower: (v) => { + ptrStack.push(v.pointer); + }, + lift: () => { + const ptr = ptrStack.pop(); + const obj = _exports['GenericImportBox'].__construct(ptr); + return obj; + }, + }, + { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const caseId = i32Stack.pop(); + return caseId; + }, + }, + { + lower: (v) => { + const bytes = textEncoder.encode(v); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + }, + lift: () => { + const rawValue = strStack.pop(); + return rawValue; + }, + }, + { + lower: (v) => { + const caseId = enumHelpers.GenericTagged.lower(v); + i32Stack.push(caseId); + }, + lift: () => { + const enumValue = enumHelpers.GenericTagged.lift(i32Stack.pop()); + return enumValue; + }, + }, + ]); + const typeIds = new Int32Array(memory.buffer, base >>> 0, count >>> 0); + for (let i = 0; i < count; i++) { + __bjs_codecByTypeId.set(typeIds[i], codecs[i]); + } + } + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } + bjs["swift_js_return_optional_bool"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalBool = null; + } else { + tmpRetOptionalBool = value !== 0; + } + } + bjs["swift_js_return_optional_int"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalInt = null; + } else { + tmpRetOptionalInt = value | 0; + } + } + bjs["swift_js_return_optional_float"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalFloat = null; + } else { + tmpRetOptionalFloat = Math.fround(value); + } + } + bjs["swift_js_return_optional_double"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalDouble = null; + } else { + tmpRetOptionalDouble = value; + } + } + bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = decodeString(ptr, len); + } + } + bjs["swift_js_return_optional_object"] = function(isSome, objectId) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = swift.memory.getObject(objectId); + } + } + bjs["swift_js_return_optional_heap_object"] = function(isSome, pointer) { + if (isSome === 0) { + tmpRetOptionalHeapObject = null; + } else { + tmpRetOptionalHeapObject = pointer; + } + } + bjs["swift_js_get_optional_int_presence"] = function() { + return tmpRetOptionalInt != null ? 1 : 0; + } + bjs["swift_js_get_optional_int_value"] = function() { + const value = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; + return value; + } + bjs["swift_js_get_optional_string"] = function() { + const str = tmpRetString; + tmpRetString = undefined; + if (str == null) { + return -1; + } else { + const bytes = textEncoder.encode(str); + tmpRetBytes = bytes; + return bytes.length; + } + } + bjs["swift_js_get_optional_float_presence"] = function() { + return tmpRetOptionalFloat != null ? 1 : 0; + } + bjs["swift_js_get_optional_float_value"] = function() { + const value = tmpRetOptionalFloat; + tmpRetOptionalFloat = undefined; + return value; + } + bjs["swift_js_get_optional_double_presence"] = function() { + return tmpRetOptionalDouble != null ? 1 : 0; + } + bjs["swift_js_get_optional_double_value"] = function() { + const value = tmpRetOptionalDouble; + tmpRetOptionalDouble = undefined; + return value; + } + bjs["swift_js_get_optional_heap_object_pointer"] = function() { + const pointer = tmpRetOptionalHeapObject; + tmpRetOptionalHeapObject = undefined; + return pointer || 0; + } + bjs["swift_js_closure_unregister"] = function(funcRef) {} + // Wrapper functions for module: TestModule + if (!importObject["TestModule"]) { + importObject["TestModule"] = {}; + } + importObject["TestModule"]["bjs_GenericImportBox_wrap"] = function(pointer) { + const obj = _exports['GenericImportBox'].__construct(pointer); + return swift.memory.retain(obj); + }; + const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; + TestModule["bjs_genericRoundTrip"] = function bjs_genericRoundTrip(tTypeId) { + try { + const codecT = __bjs_codecForTypeId(tTypeId); + const value = codecT.lift(); + let ret = imports.genericRoundTrip(value); + codecT.lower(ret); + } catch (error) { + setException(error); + } + } + TestModule["bjs_genericParse"] = function bjs_genericParse(jsonBytes, jsonCount, tTypeId) { + try { + const codecT = __bjs_codecForTypeId(tTypeId); + const string = decodeString(jsonBytes, jsonCount); + let ret = imports.genericParse(string); + codecT.lower(ret); + } catch (error) { + setException(error); + } + } + TestModule["bjs_importGenericCombine"] = function bjs_importGenericCombine(tTypeId, uTypeId) { + try { + const codecT = __bjs_codecForTypeId(tTypeId); + const codecU = __bjs_codecForTypeId(uTypeId); + const a = codecT.lift(); + const b = codecU.lift(); + let ret = imports.importGenericCombine(a, b); + codecU.lower(ret); + } catch (error) { + setException(error); + } + } + TestModule["bjs_importGenericCaseDistinct"] = function bjs_importGenericCaseDistinct(tTypeId, tTypeId1) { + try { + const codecT = __bjs_codecForTypeId(tTypeId); + const codect = __bjs_codecForTypeId(tTypeId1); + const a = codecT.lift(); + const b = codect.lift(); + let ret = imports.importGenericCaseDistinct(a, b); + codecT.lower(ret); + } catch (error) { + setException(error); + } + } + TestModule["bjs_importGenericArray"] = function bjs_importGenericArray(tTypeId) { + try { + const codecT = __bjs_codecForTypeId(tTypeId); + const values = __bjs_arrayCodec(codecT).lift(); + let ret = imports.importGenericArray(values); + __bjs_arrayCodec(codecT).lower(ret); + } catch (error) { + setException(error); + } + } + TestModule["bjs_importGenericOptional"] = function bjs_importGenericOptional(tTypeId) { + try { + const codecT = __bjs_codecForTypeId(tTypeId); + const value = __bjs_optionalCodec(codecT).lift(); + let ret = imports.importGenericOptional(value); + __bjs_optionalCodec(codecT).lower(ret); + } catch (error) { + setException(error); + } + } + TestModule["bjs_importGenericDictionary"] = function bjs_importGenericDictionary(tTypeId) { + try { + const codecT = __bjs_codecForTypeId(tTypeId); + const values = __bjs_dictCodec(codecT).lift(); + let ret = imports.importGenericDictionary(values); + __bjs_dictCodec(codecT).lower(ret); + } catch (error) { + setException(error); + } + } + TestModule["bjs_importGenericAfterOptionalArray"] = function bjs_importGenericAfterOptionalArray(values, tTypeId) { + try { + const codecT = __bjs_codecForTypeId(tTypeId); + let optResult; + if (values) { + const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lift(); + optResult = arrayResult; + } else { + optResult = null; + } + const value = codecT.lift(); + let ret = imports.importGenericAfterOptionalArray(optResult, value); + codecT.lower(ret); + } catch (error) { + setException(error); + } + } + TestModule["bjs_GenericPairFactory_init"] = function bjs_GenericPairFactory_init(tagBytes, tagCount, tTypeId, uTypeId) { + try { + const codecT = __bjs_codecForTypeId(tTypeId); + const codecU = __bjs_codecForTypeId(uTypeId); + const string = decodeString(tagBytes, tagCount); + const first = codecT.lift(); + const second = codecU.lift(); + return swift.memory.retain(new imports.GenericPairFactory(string, first, second)); + } catch (error) { + setException(error); + return 0 + } + } + TestModule["bjs_GenericConsumer_init"] = function bjs_GenericConsumer_init(tTypeId) { + try { + const codecT = __bjs_codecForTypeId(tTypeId); + const value = codecT.lift(); + return swift.memory.retain(new imports.GenericConsumer(value)); + } catch (error) { + setException(error); + return 0 + } + } + TestModule["bjs_GenericConsumer_box_static"] = function bjs_GenericConsumer_box_static(tTypeId) { + try { + const codecT = __bjs_codecForTypeId(tTypeId); + const value = codecT.lift(); + let ret = imports.GenericConsumer.box(value); + codecT.lower(ret); + } catch (error) { + setException(error); + } + } + TestModule["bjs_GenericConsumer_accept"] = function bjs_GenericConsumer_accept(self, tTypeId) { + try { + const codecT = __bjs_codecForTypeId(tTypeId); + const value = codecT.lift(); + swift.memory.getObject(self).accept(value); + } catch (error) { + setException(error); + } + } + TestModule["bjs_GenericConsumer_identity"] = function bjs_GenericConsumer_identity(self, tTypeId) { + try { + const codecT = __bjs_codecForTypeId(tTypeId); + const value = codecT.lift(); + let ret = swift.memory.getObject(self).identity(value); + codecT.lower(ret); + } catch (error) { + setException(error); + } + } + }, + setInstance: (i) => { + instance = i; + memory = instance.exports.memory; + + decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + + setException = (error) => { + instance.exports._swift_js_exception.value = swift.memory.retain(error) + } + }, + /** @param {WebAssembly.Instance} instance */ + createExports: (instance) => { + const js = swift.memory.heap; + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.identityMap?.delete(state.pointer); + state.deinit(state.pointer); + }); + + /// Represents a Swift heap object like a class instance or an actor instance. + class SwiftHeapObject { + static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; + const makeFresh = (identityMap) => { + const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false, identityMap }; + obj.pointer = pointer; + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); + if (identityMap) { + identityMap.set(pointer, new WeakRef(obj)); + } + return obj; + }; + + if (!identityCache) { + return makeFresh(null); + } + + const cached = identityCache.get(pointer)?.deref(); + if (cached && !cached.__swiftHeapObjectState.hasReleased) { + deinit(pointer); + return cached; + } + if (identityCache.has(pointer)) { + identityCache.delete(pointer); + } + + return makeFresh(identityCache); + } + + release() { + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.identityMap?.delete(state.pointer); + state.deinit(state.pointer); + } + } + class GenericImportBox extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_GenericImportBox_deinit, GenericImportBox.prototype, null); + } + + constructor(value) { + const ret = instance.exports.bjs_GenericImportBox_init(value); + return GenericImportBox.__construct(ret); + } + get() { + const ret = instance.exports.bjs_GenericImportBox_get(this.pointer); + return ret; + } + get value() { + const ret = instance.exports.bjs_GenericImportBox_value_get(this.pointer); + return ret; + } + set value(value) { + instance.exports.bjs_GenericImportBox_value_set(this.pointer, value); + } + } + const GenericPointHelpers = __bjs_createGenericPointHelpers(); + structHelpers.GenericPoint = GenericPointHelpers; + + const GenericTaggedHelpers = __bjs_createGenericTaggedValuesHelpers(); + enumHelpers.GenericTagged = GenericTaggedHelpers; + + const exports = { + GenericColor: GenericColorValues, + GenericMode: GenericModeValues, + GenericTagged: GenericTaggedValues, + GenericImportBox, + }; + _exports = exports; + return exports; + }, + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.d.ts index e4754d8e0..312f56786 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.d.ts @@ -17,6 +17,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.d.ts index 0dbdafe7b..ae1152016 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.d.ts @@ -19,6 +19,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.d.ts index 64acfac35..02d17c011 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.d.ts @@ -38,6 +38,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.d.ts index 64acfac35..02d17c011 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.d.ts @@ -38,6 +38,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.d.ts index 64acfac35..02d17c011 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.d.ts @@ -38,6 +38,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.d.ts index e0da68c50..cd4f822e2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.d.ts @@ -17,6 +17,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.d.ts index 1d5f31efd..22b4e6a1c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.d.ts @@ -26,6 +26,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.d.ts index edc243baa..ac0e05a91 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.d.ts @@ -33,6 +33,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.d.ts index e6dfad7fa..aaf227cf7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.d.ts @@ -27,6 +27,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.d.ts index 3cb232260..3b2b5de99 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.d.ts @@ -28,6 +28,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModule.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModule.d.ts index b0c2eff74..a6267bd31 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModule.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModule.d.ts @@ -17,6 +17,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModuleFallback.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModuleFallback.d.ts index e9f73cfae..818d57a9d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModuleFallback.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModuleFallback.d.ts @@ -13,6 +13,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.d.ts index 9afd16f74..624691d83 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.d.ts @@ -17,6 +17,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.d.ts index d6cbf725c..d31aeebe3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.d.ts @@ -64,6 +64,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.d.ts index c77ca0828..b842e7d7d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.d.ts @@ -17,6 +17,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.d.ts index 951f1e7aa..85109479e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.d.ts @@ -36,6 +36,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.d.ts index 737e94bce..c7ff9a39c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.d.ts @@ -29,6 +29,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.d.ts index 88d337296..01a392e91 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.d.ts @@ -51,6 +51,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.d.ts index 634065017..89aad5c32 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.d.ts @@ -29,6 +29,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.d.ts index 76daa290c..ac9ea13c4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.d.ts @@ -126,6 +126,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.d.ts index 59961720b..debd3ffcf 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.d.ts @@ -73,6 +73,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.d.ts index 5dfb48fcf..c418ed8a5 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.d.ts @@ -42,6 +42,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.d.ts index 324947e18..0f64324cd 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.d.ts @@ -82,6 +82,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.d.ts index 19680ec06..961f97635 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.d.ts @@ -15,6 +15,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.d.ts index a28a7b4bb..77e269d16 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.d.ts @@ -20,6 +20,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.d.ts index d7cd0e2e6..5872a3020 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.d.ts @@ -44,6 +44,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.d.ts index f55109d2b..a413fa500 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.d.ts @@ -119,6 +119,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.d.ts index ce87ccd29..7d5a3c9aa 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.d.ts @@ -34,6 +34,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.d.ts index b97a1bd8e..e5602e42d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.d.ts @@ -73,6 +73,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.d.ts index 6176abb6f..a168f3ad1 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.d.ts @@ -63,6 +63,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.d.ts index 42cfe5870..b54e14def 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.d.ts @@ -68,6 +68,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.d.ts index 42ff8507c..aea927c79 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.d.ts @@ -54,6 +54,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.d.ts index 8d562d13a..5e45162a1 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.d.ts @@ -17,6 +17,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.d.ts index 667db342e..b43ff062c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.d.ts @@ -15,6 +15,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.d.ts index cf231e076..fe4708fd8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.d.ts @@ -69,6 +69,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.d.ts index d0c84e109..2f56a1cb8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.d.ts @@ -43,6 +43,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.d.ts index 81fd7f109..70f23c11a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.d.ts @@ -114,6 +114,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.d.ts index 47f1b89f9..b66f960f8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.d.ts @@ -17,6 +17,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts index 3503e138e..3b394fb06 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.d.ts @@ -90,6 +90,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.d.ts index e95b78349..e97b50fda 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.d.ts @@ -19,6 +19,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.d.ts index 606de53ad..99adf95b6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.d.ts @@ -29,6 +29,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.d.ts index 13dccd568..9199ad1ae 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.d.ts @@ -14,6 +14,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.d.ts index b1ecc2000..5a4ee78ce 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.d.ts @@ -34,6 +34,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.d.ts index d15ce0a8a..7acba67a0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.d.ts @@ -15,6 +15,5 @@ export function createInstantiator(options: { }, swift: any): Promise<{ addImports: (importObject: WebAssembly.Imports) => void; setInstance: (instance: WebAssembly.Instance) => void; - afterInitialize?: () => void; createExports: (instance: WebAssembly.Instance) => Exports; }>; \ No newline at end of file diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 156f044d2..9c7cc6d2a 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -5991,6 +5991,75 @@ extension ImportedPayloadSignal: _BridgedSwiftAssociatedValueEnum { } } +extension GenericRTColor: _BridgedSwiftCaseEnum { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + return bridgeJSRawValue + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> GenericRTColor { + return bridgeJSLiftParameter(value) + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> GenericRTColor { + return GenericRTColor(bridgeJSRawValue: value)! + } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { + return bridgeJSLowerParameter() + } + + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { + switch bridgeJSRawValue { + case 0: + self = .red + case 1: + self = .green + case 2: + self = .blue + default: + return nil + } + } + + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { + switch self { + case .red: + return 0 + case .green: + return 1 + case .blue: + return 2 + } + } +} + +extension GenericRTMode: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +} + +extension GenericRTLevel: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +} + +extension GenericRTOutcome: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> GenericRTOutcome { + switch caseId { + case 0: + return .ok(code: Int.bridgeJSStackPop()) + case 1: + return .fail(message: String.bridgeJSStackPop()) + default: + fatalError("Unknown GenericRTOutcome case ID: \(caseId)") + } + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { + switch self { + case .ok(let code): + code.bridgeJSStackPush() + return Int32(0) + case .fail(let message): + message.bridgeJSStackPush() + return Int32(1) + } + } +} + @_expose(wasm, "bjs_IntegerTypesSupportExports_static_roundTripInt") @_cdecl("bjs_IntegerTypesSupportExports_static_roundTripInt") public func _bjs_IntegerTypesSupportExports_static_roundTripInt(_ v: Int32) -> Int32 { @@ -6779,6 +6848,102 @@ public func _bjs_NestedTypeHost_Label_static_untitled() -> Void { #endif } +extension GenericRTPoint: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> GenericRTPoint { + let y = Int.bridgeJSStackPop() + let x = Int.bridgeJSStackPop() + return GenericRTPoint(x: x, y: y) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.x.bridgeJSStackPush() + self.y.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_GenericRTPoint(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_GenericRTPoint())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_GenericRTPoint") +fileprivate func _bjs_struct_lower_GenericRTPoint_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_GenericRTPoint_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_GenericRTPoint(_ objectId: Int32) -> Void { + return _bjs_struct_lower_GenericRTPoint_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_GenericRTPoint") +fileprivate func _bjs_struct_lift_GenericRTPoint_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_GenericRTPoint_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_GenericRTPoint() -> Int32 { + return _bjs_struct_lift_GenericRTPoint_extern() +} + +extension GenericRTNamespace.Metadata: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> GenericRTNamespace.Metadata { + let count = Int.bridgeJSStackPop() + let label = String.bridgeJSStackPop() + return GenericRTNamespace.Metadata(label: label, count: count) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.label.bridgeJSStackPush() + self.count.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_GenericRTNamespace_Metadata(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_GenericRTNamespace_Metadata())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_GenericRTNamespace_Metadata") +fileprivate func _bjs_struct_lower_GenericRTNamespace_Metadata_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_GenericRTNamespace_Metadata_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_GenericRTNamespace_Metadata(_ objectId: Int32) -> Void { + return _bjs_struct_lower_GenericRTNamespace_Metadata_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_GenericRTNamespace_Metadata") +fileprivate func _bjs_struct_lift_GenericRTNamespace_Metadata_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_GenericRTNamespace_Metadata_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_GenericRTNamespace_Metadata() -> Int32 { + return _bjs_struct_lift_GenericRTNamespace_Metadata_extern() +} + extension Point: _BridgedSwiftStruct { @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Point { let y = Int.bridgeJSStackPop() @@ -13206,6 +13371,80 @@ fileprivate func _bjs_NestedTypeHost_wrap_extern(_ pointer: UnsafeMutableRawPoin return _bjs_NestedTypeHost_wrap_extern(pointer) } +@_expose(wasm, "bjs_ImportGenericBox_init") +@_cdecl("bjs_ImportGenericBox_init") +public func _bjs_ImportGenericBox_init(_ value: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = ImportGenericBox(value: Int.bridgeJSLiftParameter(value)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ImportGenericBox_get") +@_cdecl("bjs_ImportGenericBox_get") +public func _bjs_ImportGenericBox_get(_ _self: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let ret = ImportGenericBox.bridgeJSLiftParameter(_self).get() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ImportGenericBox_value_get") +@_cdecl("bjs_ImportGenericBox_value_get") +public func _bjs_ImportGenericBox_value_get(_ _self: UnsafeMutableRawPointer) -> Int32 { + #if arch(wasm32) + let ret = ImportGenericBox.bridgeJSLiftParameter(_self).value + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ImportGenericBox_value_set") +@_cdecl("bjs_ImportGenericBox_value_set") +public func _bjs_ImportGenericBox_value_set(_ _self: UnsafeMutableRawPointer, _ value: Int32) -> Void { + #if arch(wasm32) + ImportGenericBox.bridgeJSLiftParameter(_self).value = Int.bridgeJSLiftParameter(value) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_ImportGenericBox_deinit") +@_cdecl("bjs_ImportGenericBox_deinit") +public func _bjs_ImportGenericBox_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension ImportGenericBox: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_ImportGenericBox_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_ImportGenericBox_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ImportGenericBox_wrap") +fileprivate func _bjs_ImportGenericBox_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_ImportGenericBox_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_ImportGenericBox_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_ImportGenericBox_wrap_extern(pointer) +} + @_expose(wasm, "bjs_JSNameRenamedClass_init") @_cdecl("bjs_JSNameRenamedClass_init") public func _bjs_JSNameRenamedClass_init(_ value: Int32) -> UnsafeMutableRawPointer { @@ -13624,6 +13863,14 @@ extension NestedTypeHost.Label: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = NestedTypeHost.Label.bridgeJSMakeTypeHandle() } +extension GenericRTPoint: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = GenericRTPoint.bridgeJSMakeTypeHandle() +} + +extension GenericRTNamespace.Metadata: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = GenericRTNamespace.Metadata.bridgeJSMakeTypeHandle() +} + extension Point: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = Point.bridgeJSMakeTypeHandle() } @@ -13720,6 +13967,10 @@ extension PriorityReference: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = PriorityReference.bridgeJSMakeTypeHandle() } +extension ImportGenericBox: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = ImportGenericBox.bridgeJSMakeTypeHandle() +} + extension Severity: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = Severity.bridgeJSMakeTypeHandle() } @@ -13840,6 +14091,22 @@ extension ImportedPayloadSignal: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = ImportedPayloadSignal.bridgeJSMakeTypeHandle() } +extension GenericRTColor: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = GenericRTColor.bridgeJSMakeTypeHandle() +} + +extension GenericRTMode: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = GenericRTMode.bridgeJSMakeTypeHandle() +} + +extension GenericRTLevel: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = GenericRTLevel.bridgeJSMakeTypeHandle() +} + +extension GenericRTOutcome: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = GenericRTOutcome.bridgeJSMakeTypeHandle() +} + extension OptionalAllTypesResult: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = OptionalAllTypesResult.bridgeJSMakeTypeHandle() } @@ -17057,6 +17324,346 @@ func _$jsJoinStringThenStackParams(_ s: String, _ a: Optional<[Int]>, _ b: [Int] return String.bridgeJSLiftReturn(ret) } +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsGenericRoundTrip") +fileprivate func bjs_jsGenericRoundTrip_extern(_ _generic0TypeId: Int32) -> Void +#else +fileprivate func bjs_jsGenericRoundTrip_extern(_ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsGenericRoundTrip(_ _generic0TypeId: Int32) -> Void { + return bjs_jsGenericRoundTrip_extern(_generic0TypeId) +} + +func _$jsGenericRoundTrip(_ value: T) throws(JSException) -> T { + value.bridgeJSStackPush() + bjs_jsGenericRoundTrip(T.bridgeJSTypeID) + if let error = _swift_js_take_exception() { + throw error + } + return T.bridgeJSStackPop() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsGenericRoundTripClass") +fileprivate func bjs_jsGenericRoundTripClass_extern(_ _generic0TypeId: Int32) -> Void +#else +fileprivate func bjs_jsGenericRoundTripClass_extern(_ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsGenericRoundTripClass(_ _generic0TypeId: Int32) -> Void { + return bjs_jsGenericRoundTripClass_extern(_generic0TypeId) +} + +func _$jsGenericRoundTripClass(_ value: T) throws(JSException) -> T { + value.bridgeJSStackPush() + bjs_jsGenericRoundTripClass(T.bridgeJSTypeID) + if let error = _swift_js_take_exception() { + throw error + } + return T.bridgeJSStackPop() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsGenericParsePoint") +fileprivate func bjs_jsGenericParsePoint_extern(_ jsonBytes: Int32, _ jsonLength: Int32, _ _generic0TypeId: Int32) -> Void +#else +fileprivate func bjs_jsGenericParsePoint_extern(_ jsonBytes: Int32, _ jsonLength: Int32, _ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsGenericParsePoint(_ jsonBytes: Int32, _ jsonLength: Int32, _ _generic0TypeId: Int32) -> Void { + return bjs_jsGenericParsePoint_extern(jsonBytes, jsonLength, _generic0TypeId) +} + +func _$jsGenericParsePoint(_ json: String) throws(JSException) -> T { + json.bridgeJSWithLoweredParameter { (jsonBytes, jsonLength) in + bjs_jsGenericParsePoint(jsonBytes, jsonLength, T.bridgeJSTypeID) + } + if let error = _swift_js_take_exception() { + throw error + } + return T.bridgeJSStackPop() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsImportPickFirst") +fileprivate func bjs_jsImportPickFirst_extern(_ _generic0TypeId: Int32) -> Void +#else +fileprivate func bjs_jsImportPickFirst_extern(_ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsImportPickFirst(_ _generic0TypeId: Int32) -> Void { + return bjs_jsImportPickFirst_extern(_generic0TypeId) +} + +func _$jsImportPickFirst(_ a: T, _ b: T) throws(JSException) -> T { + b.bridgeJSStackPush() + a.bridgeJSStackPush() + bjs_jsImportPickFirst(T.bridgeJSTypeID) + if let error = _swift_js_take_exception() { + throw error + } + return T.bridgeJSStackPop() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsImportMakeInt") +fileprivate func bjs_jsImportMakeInt_extern(_ _generic0TypeId: Int32) -> Void +#else +fileprivate func bjs_jsImportMakeInt_extern(_ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsImportMakeInt(_ _generic0TypeId: Int32) -> Void { + return bjs_jsImportMakeInt_extern(_generic0TypeId) +} + +func _$jsImportMakeInt() throws(JSException) -> T { + bjs_jsImportMakeInt(T.bridgeJSTypeID) + if let error = _swift_js_take_exception() { + throw error + } + return T.bridgeJSStackPop() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsImportCombineSecond") +fileprivate func bjs_jsImportCombineSecond_extern(_ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void +#else +fileprivate func bjs_jsImportCombineSecond_extern(_ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsImportCombineSecond(_ _generic0TypeId: Int32, _ _generic1TypeId: Int32) -> Void { + return bjs_jsImportCombineSecond_extern(_generic0TypeId, _generic1TypeId) +} + +func _$jsImportCombineSecond(_ a: T, _ b: U) throws(JSException) -> U { + b.bridgeJSStackPush() + a.bridgeJSStackPush() + bjs_jsImportCombineSecond(T.bridgeJSTypeID, U.bridgeJSTypeID) + if let error = _swift_js_take_exception() { + throw error + } + return U.bridgeJSStackPop() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsGenericArrayRoundTrip") +fileprivate func bjs_jsGenericArrayRoundTrip_extern(_ _generic0TypeId: Int32) -> Void +#else +fileprivate func bjs_jsGenericArrayRoundTrip_extern(_ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsGenericArrayRoundTrip(_ _generic0TypeId: Int32) -> Void { + return bjs_jsGenericArrayRoundTrip_extern(_generic0TypeId) +} + +func _$jsGenericArrayRoundTrip(_ values: [T]) throws(JSException) -> [T] { + let _ = values.bridgeJSLowerParameter() + bjs_jsGenericArrayRoundTrip(T.bridgeJSTypeID) + if let error = _swift_js_take_exception() { + throw error + } + return [T].bridgeJSLiftReturn() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsGenericOptionalRoundTrip") +fileprivate func bjs_jsGenericOptionalRoundTrip_extern(_ _generic0TypeId: Int32) -> Void +#else +fileprivate func bjs_jsGenericOptionalRoundTrip_extern(_ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsGenericOptionalRoundTrip(_ _generic0TypeId: Int32) -> Void { + return bjs_jsGenericOptionalRoundTrip_extern(_generic0TypeId) +} + +func _$jsGenericOptionalRoundTrip(_ value: Optional) throws(JSException) -> Optional { + value.bridgeJSStackPush() + bjs_jsGenericOptionalRoundTrip(T.bridgeJSTypeID) + if let error = _swift_js_take_exception() { + throw error + } + return Optional.bridgeJSStackPop() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsGenericDictRoundTrip") +fileprivate func bjs_jsGenericDictRoundTrip_extern(_ _generic0TypeId: Int32) -> Void +#else +fileprivate func bjs_jsGenericDictRoundTrip_extern(_ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsGenericDictRoundTrip(_ _generic0TypeId: Int32) -> Void { + return bjs_jsGenericDictRoundTrip_extern(_generic0TypeId) +} + +func _$jsGenericDictRoundTrip(_ values: [String: T]) throws(JSException) -> [String: T] { + let _ = values.bridgeJSLowerParameter() + bjs_jsGenericDictRoundTrip(T.bridgeJSTypeID) + if let error = _swift_js_take_exception() { + throw error + } + return [String: T].bridgeJSLiftReturn() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsGenericAfterOptionalArray") +fileprivate func bjs_jsGenericAfterOptionalArray_extern(_ values: Int32, _ _generic0TypeId: Int32) -> Int32 +#else +fileprivate func bjs_jsGenericAfterOptionalArray_extern(_ values: Int32, _ _generic0TypeId: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsGenericAfterOptionalArray(_ values: Int32, _ _generic0TypeId: Int32) -> Int32 { + return bjs_jsGenericAfterOptionalArray_extern(values, _generic0TypeId) +} + +func _$jsGenericAfterOptionalArray(_ values: Optional<[Int]>, _ value: T) throws(JSException) -> String { + value.bridgeJSStackPush() + let valuesIsSome = values.bridgeJSLowerParameter() + let ret = bjs_jsGenericAfterOptionalArray(valuesIsSome, T.bridgeJSTypeID) + if let error = _swift_js_take_exception() { + throw error + } + return String.bridgeJSLiftReturn(ret) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsGenericThrowOrRoundTrip") +fileprivate func bjs_jsGenericThrowOrRoundTrip_extern(_ shouldThrow: Int32, _ _generic0TypeId: Int32) -> Void +#else +fileprivate func bjs_jsGenericThrowOrRoundTrip_extern(_ shouldThrow: Int32, _ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_jsGenericThrowOrRoundTrip(_ shouldThrow: Int32, _ _generic0TypeId: Int32) -> Void { + return bjs_jsGenericThrowOrRoundTrip_extern(shouldThrow, _generic0TypeId) +} + +func _$jsGenericThrowOrRoundTrip(_ shouldThrow: Bool, _ value: T) throws(JSException) -> T { + value.bridgeJSStackPush() + let shouldThrowValue = shouldThrow.bridgeJSLowerParameter() + bjs_jsGenericThrowOrRoundTrip(shouldThrowValue, T.bridgeJSTypeID) + if let error = _swift_js_take_exception() { + throw error + } + return T.bridgeJSStackPop() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ImportGenericConsumer_init") +fileprivate func bjs_ImportGenericConsumer_init_extern() -> Int32 +#else +fileprivate func bjs_ImportGenericConsumer_init_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ImportGenericConsumer_init() -> Int32 { + return bjs_ImportGenericConsumer_init_extern() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ImportGenericConsumer_box_static") +fileprivate func bjs_ImportGenericConsumer_box_static_extern(_ _generic0TypeId: Int32) -> Void +#else +fileprivate func bjs_ImportGenericConsumer_box_static_extern(_ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ImportGenericConsumer_box_static(_ _generic0TypeId: Int32) -> Void { + return bjs_ImportGenericConsumer_box_static_extern(_generic0TypeId) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ImportGenericConsumer_identity") +fileprivate func bjs_ImportGenericConsumer_identity_extern(_ self: Int32, _ _generic0TypeId: Int32) -> Void +#else +fileprivate func bjs_ImportGenericConsumer_identity_extern(_ self: Int32, _ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ImportGenericConsumer_identity(_ self: Int32, _ _generic0TypeId: Int32) -> Void { + return bjs_ImportGenericConsumer_identity_extern(self, _generic0TypeId) +} + +func _$ImportGenericConsumer_init() throws(JSException) -> JSObject { + let ret = bjs_ImportGenericConsumer_init() + if let error = _swift_js_take_exception() { + throw error + } + return JSObject.bridgeJSLiftReturn(ret) +} + +func _$ImportGenericConsumer_box(_ value: T) throws(JSException) -> T { + value.bridgeJSStackPush() + bjs_ImportGenericConsumer_box_static(T.bridgeJSTypeID) + if let error = _swift_js_take_exception() { + throw error + } + return T.bridgeJSStackPop() +} + +func _$ImportGenericConsumer_identity(_ self: JSObject, _ value: T) throws(JSException) -> T { + value.bridgeJSStackPush() + let selfValue = self.bridgeJSLowerParameter() + bjs_ImportGenericConsumer_identity(selfValue, T.bridgeJSTypeID) + if let error = _swift_js_take_exception() { + throw error + } + return T.bridgeJSStackPop() +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ImportGenericBoxed_init") +fileprivate func bjs_ImportGenericBoxed_init_extern(_ _generic0TypeId: Int32) -> Int32 +#else +fileprivate func bjs_ImportGenericBoxed_init_extern(_ _generic0TypeId: Int32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ImportGenericBoxed_init(_ _generic0TypeId: Int32) -> Int32 { + return bjs_ImportGenericBoxed_init_extern(_generic0TypeId) +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_ImportGenericBoxed_unwrap") +fileprivate func bjs_ImportGenericBoxed_unwrap_extern(_ self: Int32, _ _generic0TypeId: Int32) -> Void +#else +fileprivate func bjs_ImportGenericBoxed_unwrap_extern(_ self: Int32, _ _generic0TypeId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func bjs_ImportGenericBoxed_unwrap(_ self: Int32, _ _generic0TypeId: Int32) -> Void { + return bjs_ImportGenericBoxed_unwrap_extern(self, _generic0TypeId) +} + +func _$ImportGenericBoxed_init(_ value: T) throws(JSException) -> JSObject { + value.bridgeJSStackPush() + let ret = bjs_ImportGenericBoxed_init(T.bridgeJSTypeID) + if let error = _swift_js_take_exception() { + throw error + } + return JSObject.bridgeJSLiftReturn(ret) +} + +func _$ImportGenericBoxed_unwrap(_ self: JSObject) throws(JSException) -> T { + let selfValue = self.bridgeJSLowerParameter() + bjs_ImportGenericBoxed_unwrap(selfValue, T.bridgeJSTypeID) + if let error = _swift_js_take_exception() { + throw error + } + return T.bridgeJSStackPop() +} + #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsTranslatePoint") fileprivate func bjs_jsTranslatePoint_extern(_ dx: Int32, _ dy: Int32) -> Void @@ -18459,6 +19066,8 @@ public func _bjs_BridgeJSRuntimeTests_register_type_handles() { NestedStructGroupA.Metadata.bridgeJSTypeID, NestedStructGroupB.Metadata.bridgeJSTypeID, NestedTypeHost.Label.bridgeJSTypeID, + GenericRTPoint.bridgeJSTypeID, + GenericRTNamespace.Metadata.bridgeJSTypeID, Point.bridgeJSTypeID, PointerFields.bridgeJSTypeID, DataPoint.bridgeJSTypeID, @@ -18483,6 +19092,7 @@ public func _bjs_BridgeJSRuntimeTests_register_type_handles() { TagReference.bridgeJSTypeID, TagHolderReference.bridgeJSTypeID, PriorityReference.bridgeJSTypeID, + ImportGenericBox.bridgeJSTypeID, Severity.bridgeJSTypeID, Shape.bridgeJSTypeID, InnerTag.bridgeJSTypeID, @@ -18513,6 +19123,10 @@ public func _bjs_BridgeJSRuntimeTests_register_type_handles() { NestedTypeHost.Variant.bridgeJSTypeID, LightColor.bridgeJSTypeID, ImportedPayloadSignal.bridgeJSTypeID, + GenericRTColor.bridgeJSTypeID, + GenericRTMode.bridgeJSTypeID, + GenericRTLevel.bridgeJSTypeID, + GenericRTOutcome.bridgeJSTypeID, OptionalAllTypesResult.bridgeJSTypeID, APIOptionalResult.bridgeJSTypeID, ] diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index 6748d7c16..8622b1cc9 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -4844,6 +4844,70 @@ ], "swiftCallName" : "NestedTypeHost" }, + { + "constructor" : { + "abiName" : "bjs_ImportGenericBox_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "value", + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ] + }, + "isFinal" : true, + "methods" : [ + { + "abiName" : "bjs_ImportGenericBox_get", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "get", + "parameters" : [ + + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "name" : "ImportGenericBox", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "value", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "swiftCallName" : "ImportGenericBox" + }, { "constructor" : { "abiName" : "bjs_JSNameRenamedClass_init", @@ -10347,6 +10411,152 @@ { "cases" : [ + ], + "emitStyle" : "const", + "name" : "GenericRTNamespace", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "GenericRTNamespace", + "tsFullPath" : "GenericRTNamespace" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "red" + }, + { + "associatedValues" : [ + + ], + "name" : "green" + }, + { + "associatedValues" : [ + + ], + "name" : "blue" + } + ], + "emitStyle" : "const", + "name" : "GenericRTColor", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "GenericRTColor", + "tsFullPath" : "GenericRTColor" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "light" + }, + { + "associatedValues" : [ + + ], + "name" : "dark" + } + ], + "emitStyle" : "const", + "name" : "GenericRTMode", + "rawType" : "String", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "GenericRTMode", + "tsFullPath" : "GenericRTMode" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "low", + "rawValue" : "1" + }, + { + "associatedValues" : [ + + ], + "name" : "high", + "rawValue" : "9" + } + ], + "emitStyle" : "const", + "name" : "GenericRTLevel", + "rawType" : "Int", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "GenericRTLevel", + "tsFullPath" : "GenericRTLevel" + }, + { + "cases" : [ + { + "associatedValues" : [ + { + "label" : "code", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "name" : "ok" + }, + { + "associatedValues" : [ + { + "label" : "message", + "type" : { + "string" : { + + } + } + } + ], + "name" : "fail" + } + ], + "emitStyle" : "const", + "name" : "GenericRTOutcome", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "GenericRTOutcome", + "tsFullPath" : "GenericRTOutcome" + }, + { + "cases" : [ + ], "emitStyle" : "const", "name" : "IntegerTypesSupportExports", @@ -18472,6 +18682,82 @@ { "methods" : [ + ], + "name" : "GenericRTPoint", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "x", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "y", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "swiftCallName" : "GenericRTPoint" + }, + { + "methods" : [ + + ], + "name" : "Metadata", + "namespace" : [ + "GenericRTNamespace" + ], + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "label", + "namespace" : [ + "GenericRTNamespace" + ], + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : false, + "name" : "count", + "namespace" : [ + "GenericRTNamespace" + ], + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "swiftCallName" : "GenericRTNamespace.Metadata" + }, + { + "methods" : [ + ], "name" : "Point", "properties" : [ @@ -23779,6 +24065,498 @@ ] }, + { + "functions" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + "T" + ], + "name" : "jsGenericRoundTrip", + "parameters" : [ + { + "name" : "value", + "type" : { + "generic" : { + "_0" : "T" + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "T" + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + "T" + ], + "name" : "jsGenericRoundTripClass", + "parameters" : [ + { + "name" : "value", + "type" : { + "generic" : { + "_0" : "T" + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "T" + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + "T" + ], + "name" : "jsGenericParsePoint", + "parameters" : [ + { + "name" : "json", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "T" + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + "T" + ], + "name" : "jsImportPickFirst", + "parameters" : [ + { + "name" : "a", + "type" : { + "generic" : { + "_0" : "T" + } + } + }, + { + "name" : "b", + "type" : { + "generic" : { + "_0" : "T" + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "T" + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + "T" + ], + "name" : "jsImportMakeInt", + "parameters" : [ + + ], + "returnType" : { + "generic" : { + "_0" : "T" + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + "T", + "U" + ], + "name" : "jsImportCombineSecond", + "parameters" : [ + { + "name" : "a", + "type" : { + "generic" : { + "_0" : "T" + } + } + }, + { + "name" : "b", + "type" : { + "generic" : { + "_0" : "U" + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "U" + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + "T" + ], + "name" : "jsGenericArrayRoundTrip", + "parameters" : [ + { + "name" : "values", + "type" : { + "array" : { + "_0" : { + "generic" : { + "_0" : "T" + } + } + } + } + } + ], + "returnType" : { + "array" : { + "_0" : { + "generic" : { + "_0" : "T" + } + } + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + "T" + ], + "name" : "jsGenericOptionalRoundTrip", + "parameters" : [ + { + "name" : "value", + "type" : { + "nullable" : { + "_0" : { + "generic" : { + "_0" : "T" + } + }, + "_1" : "null" + } + } + } + ], + "returnType" : { + "nullable" : { + "_0" : { + "generic" : { + "_0" : "T" + } + }, + "_1" : "null" + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + "T" + ], + "name" : "jsGenericDictRoundTrip", + "parameters" : [ + { + "name" : "values", + "type" : { + "dictionary" : { + "_0" : { + "generic" : { + "_0" : "T" + } + } + } + } + } + ], + "returnType" : { + "dictionary" : { + "_0" : { + "generic" : { + "_0" : "T" + } + } + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + "T" + ], + "name" : "jsGenericAfterOptionalArray", + "parameters" : [ + { + "name" : "values", + "type" : { + "nullable" : { + "_0" : { + "array" : { + "_0" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + }, + "_1" : "null" + } + } + }, + { + "name" : "value", + "type" : { + "generic" : { + "_0" : "T" + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + "T" + ], + "name" : "jsGenericThrowOrRoundTrip", + "parameters" : [ + { + "name" : "shouldThrow", + "type" : { + "bool" : { + + } + } + }, + { + "name" : "value", + "type" : { + "generic" : { + "_0" : "T" + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "T" + } + } + } + ], + "types" : [ + { + "accessLevel" : "internal", + "constructor" : { + "accessLevel" : "internal", + "parameters" : [ + + ] + }, + "getters" : [ + + ], + "methods" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + "T" + ], + "name" : "identity", + "parameters" : [ + { + "name" : "value", + "type" : { + "generic" : { + "_0" : "T" + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "T" + } + } + } + ], + "name" : "ImportGenericConsumer", + "setters" : [ + + ], + "staticMethods" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + "T" + ], + "name" : "box", + "parameters" : [ + { + "name" : "value", + "type" : { + "generic" : { + "_0" : "T" + } + } + } + ], + "returnType" : { + "generic" : { + "_0" : "T" + } + } + } + ] + }, + { + "accessLevel" : "internal", + "constructor" : { + "accessLevel" : "internal", + "genericParameters" : [ + "T" + ], + "parameters" : [ + { + "name" : "value", + "type" : { + "generic" : { + "_0" : "T" + } + } + } + ] + }, + "getters" : [ + + ], + "methods" : [ + { + "accessLevel" : "internal", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : true + }, + "genericParameters" : [ + "T" + ], + "name" : "unwrap", + "parameters" : [ + + ], + "returnType" : { + "generic" : { + "_0" : "T" + } + } + } + ], + "name" : "ImportGenericBoxed", + "setters" : [ + + ], + "staticMethods" : [ + + ] + } + ] + }, { "functions" : [ { diff --git a/Tests/BridgeJSRuntimeTests/ImportGenericAPIs.swift b/Tests/BridgeJSRuntimeTests/ImportGenericAPIs.swift new file mode 100644 index 000000000..bfd63839f --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/ImportGenericAPIs.swift @@ -0,0 +1,280 @@ +import Testing +import JavaScriptKit + +@JS struct GenericRTPoint { + var x: Int + var y: Int +} + +@JS enum GenericRTNamespace { + @JS struct Metadata { + var label: String + var count: Int + } +} + +@JS enum GenericRTColor { + case red + case green + case blue +} + +@JS enum GenericRTMode: String { + case light + case dark +} + +@JS enum GenericRTLevel: Int { + case low = 1 + case high = 9 +} + +@JS enum GenericRTOutcome { + case ok(code: Int) + case fail(message: String) +} + +@JS final class ImportGenericBox { + @JS var value: Int + @JS init(value: Int) { + self.value = value + } + @JS func get() -> Int { + value + } +} + +@JSFunction func jsGenericRoundTrip(_ value: T) throws(JSException) -> T +@JSFunction func jsGenericRoundTripClass(_ value: T) throws(JSException) -> T +@JSFunction func jsGenericParsePoint(_ json: String) throws(JSException) -> T +@JSFunction func jsImportPickFirst(_ a: T, _ b: T) throws(JSException) -> T +@JSFunction func jsImportMakeInt() throws(JSException) -> T +@JSFunction func jsImportCombineSecond( + _ a: T, + _ b: U +) throws(JSException) -> U +@JSFunction func jsGenericArrayRoundTrip(_ values: [T]) throws(JSException) -> [T] +@JSFunction func jsGenericOptionalRoundTrip(_ value: T?) throws(JSException) -> T? +@JSFunction func jsGenericDictRoundTrip( + _ values: [String: T] +) throws(JSException) -> [String: T] +@JSFunction func jsGenericAfterOptionalArray( + _ values: [Int]?, + _ value: T +) throws(JSException) -> String + +@JSClass struct ImportGenericConsumer { + @JSFunction init() throws(JSException) + @JSFunction func identity(_ value: T) throws(JSException) -> T + @JSFunction static func box(_ value: T) throws(JSException) -> T +} + +@JSFunction func jsGenericThrowOrRoundTrip( + _ shouldThrow: Bool, + _ value: T +) throws(JSException) -> T + +@JSClass struct ImportGenericBoxed { + @JSFunction init(_ value: T) throws(JSException) + @JSFunction func unwrap() throws(JSException) -> T +} + +@Suite struct ImportGenericAPITests { + @Test func genericRoundTripScalars() throws { + #expect(try jsGenericRoundTrip(42) == 42) + #expect(try jsGenericRoundTrip(-7) == -7) + #expect(try jsGenericRoundTrip(3.5) == 3.5) + #expect(try jsGenericRoundTrip(Float(1.25)) == Float(1.25)) + #expect(try jsGenericRoundTrip(true) == true) + #expect(try jsGenericRoundTrip(false) == false) + #expect(try jsGenericRoundTrip("hello") == "hello") + #expect(try jsGenericRoundTrip("") == "") + } + + @Test func genericRoundTripNumerics() throws { + #expect(try jsGenericRoundTrip(Int8(-5)) == Int8(-5)) + #expect(try jsGenericRoundTrip(Int8.min) == Int8.min) + #expect(try jsGenericRoundTrip(Int8.max) == Int8.max) + #expect(try jsGenericRoundTrip(UInt8(200)) == UInt8(200)) + #expect(try jsGenericRoundTrip(UInt8.max) == UInt8.max) + #expect(try jsGenericRoundTrip(Int16(-1000)) == Int16(-1000)) + #expect(try jsGenericRoundTrip(UInt16(60000)) == UInt16(60000)) + #expect(try jsGenericRoundTrip(Int32(-123456)) == Int32(-123456)) + #expect(try jsGenericRoundTrip(UInt32(3_000_000_000)) == UInt32(3_000_000_000)) + #expect(try jsGenericRoundTrip(UInt32.max) == UInt32.max) + #expect(try jsGenericRoundTrip(UInt(42)) == UInt(42)) + #expect(try jsGenericRoundTrip(UInt(4_000_000_000)) == UInt(4_000_000_000)) + #expect(try jsGenericRoundTrip(Int64(-9_000_000_000)) == Int64(-9_000_000_000)) + #expect(try jsGenericRoundTrip(Int64.min) == Int64.min) + #expect(try jsGenericRoundTrip(Int64.max) == Int64.max) + #expect(try jsGenericRoundTrip(UInt64(18_000_000_000_000_000_000)) == UInt64(18_000_000_000_000_000_000)) + #expect(try jsGenericRoundTrip(UInt64.max) == UInt64.max) + } + + @Test func genericRoundTripJSValue() throws { + let number = try jsGenericRoundTrip(JSValue.number(3.5)) + #expect(number.number == 3.5) + let string = try jsGenericRoundTrip(JSValue.string("hi")) + #expect(string.string == "hi") + let boolean = try jsGenericRoundTrip(JSValue.boolean(true)) + #expect(boolean.boolean == true) + #expect(try jsGenericRoundTrip(JSValue.null).isNull) + #expect(try jsGenericRoundTrip(JSValue.undefined).isUndefined) + let object = JSObject.global.Object.function!.new() + object.tag = 7 + let roundTripped = try jsGenericRoundTrip(JSValue.object(object)) + #expect(roundTripped.object?.tag.number == 7) + } + + @Test func genericWrappedRoundTrip() throws { + #expect(try jsGenericArrayRoundTrip([1, 2, 3]) == [1, 2, 3]) + #expect(try jsGenericArrayRoundTrip(["a", "b"]) == ["a", "b"]) + #expect(try jsGenericArrayRoundTrip([Int]()) == []) + #expect(try jsGenericOptionalRoundTrip(Optional.some(7)) == 7) + #expect(try jsGenericOptionalRoundTrip(Optional.none) == nil) + #expect(try jsGenericOptionalRoundTrip(Optional.some("hi")) == "hi") + let outcome = try jsGenericOptionalRoundTrip(Optional.some(.ok(code: 5))) + guard case .some(.ok(let code)) = outcome else { + Issue.record("expected .ok") + return + } + #expect(code == 5) + #expect(try jsGenericOptionalRoundTrip(Optional.none) == nil) + #expect(try jsGenericDictRoundTrip(["x": 1, "y": 2]) == ["x": 1, "y": 2]) + #expect(try jsGenericDictRoundTrip([String: String]()) == [:]) + } + + @Test func genericRoundTripEnums() throws { + #expect(try jsGenericRoundTrip(GenericRTColor.red) == .red) + #expect(try jsGenericRoundTrip(GenericRTColor.blue) == .blue) + #expect(try jsGenericRoundTrip(GenericRTMode.dark) == .dark) + #expect(try jsGenericRoundTrip(GenericRTMode.light).rawValue == "light") + #expect(try jsGenericRoundTrip(GenericRTLevel.high) == .high) + let outcome = try jsGenericRoundTrip(GenericRTOutcome.ok(code: 42)) + guard case .ok(let code) = outcome else { + Issue.record("expected .ok") + return + } + #expect(code == 42) + let failure = try jsGenericRoundTrip(GenericRTOutcome.fail(message: "boom")) + guard case .fail(let message) = failure else { + Issue.record("expected .fail") + return + } + #expect(message == "boom") + } + + @Test func genericRoundTripStruct() throws { + let point = try jsGenericRoundTrip(GenericRTPoint(x: 1, y: 2)) + #expect(point.x == 1) + #expect(point.y == 2) + } + + @Test func genericRoundTripNestedStruct() throws { + let metadata = try jsGenericRoundTrip(GenericRTNamespace.Metadata(label: "alpha", count: 7)) + #expect(metadata.label == "alpha") + #expect(metadata.count == 7) + } + + @Test func genericParse() throws { + let point: GenericRTPoint = try jsGenericParsePoint("{\"x\": 10, \"y\": 20}") + #expect(point.x == 10) + #expect(point.y == 20) + let n: Int = try jsGenericParsePoint("42") + #expect(n == 42) + let string: String = try jsGenericParsePoint("\"hi\"") + #expect(string == "hi") + } + + @Test func genericPickFirstMultiUse() throws { + #expect(try jsImportPickFirst(10, 20) as Int == 10) + #expect(try jsImportPickFirst("a", "b") as String == "a") + let firstPoint = try jsImportPickFirst(GenericRTPoint(x: 1, y: 2), GenericRTPoint(x: 3, y: 4)) + #expect(firstPoint.x == 1) + #expect(firstPoint.y == 2) + } + + @Test func genericMakeReturnOnly() throws { + let made: Int = try jsImportMakeInt() + #expect(made == 123) + } + + @Test func genericCombineSecondMultiParameter() throws { + #expect(try jsImportCombineSecond(7, "hello") as String == "hello") + #expect(try jsImportCombineSecond("x", 9) as Int == 9) + let point = try jsImportCombineSecond(42, GenericRTPoint(x: 5, y: 6)) + #expect(point.x == 5) + #expect(point.y == 6) + } + + @Test func genericRoundTripHeapObjectClass() throws { + let box = ImportGenericBox(value: 314) + #expect(box.get() == 314) + let sameBox = try jsGenericRoundTripClass(box) + #expect(sameBox.get() == 314) + sameBox.value = 271 + #expect(box.get() == 271) + } + + @Test func genericMixedConsecutiveCalls() throws { + #expect(try jsGenericRoundTrip(1) == 1) + #expect(try jsGenericRoundTrip("two") == "two") + #expect(try jsGenericRoundTrip(3.0) == 3.0) + let p = try jsGenericRoundTrip(GenericRTPoint(x: 4, y: 5)) + #expect(p.x == 4) + #expect(p.y == 5) + } + + @Test func importGenericInstanceMethod() throws { + let consumer = try ImportGenericConsumer() + #expect(try consumer.identity(42) == 42) + #expect(try consumer.identity(-7) == -7) + #expect(try consumer.identity("hi") == "hi") + #expect(try consumer.identity(true) == true) + #expect(try consumer.identity(false) == false) + let point = try consumer.identity(GenericRTPoint(x: 3, y: 4)) + #expect(point.x == 3) + #expect(point.y == 4) + } + + /// A generic parameter shares the stacks with any other stack-lowered + /// parameter, so both have to arrive in declaration order. + @Test func genericAlongsideOptionalArray() throws { + #expect(try jsGenericAfterOptionalArray([1, 2], 42) == "[1,2]|42") + #expect(try jsGenericAfterOptionalArray([1, 2], GenericRTPoint(x: 3, y: 4)) == #"[1,2]|{"x":3,"y":4}"#) + #expect(try jsGenericAfterOptionalArray(nil, "x") == #"null|"x""#) + } + + @Test func genericImportPropagatesJSException() throws { + #expect(try jsGenericThrowOrRoundTrip(false, 42) == 42) + #expect(try jsGenericThrowOrRoundTrip(false, GenericRTPoint(x: 1, y: 2)).x == 1) + do { + let _: Int = try jsGenericThrowOrRoundTrip(true, 0) + Issue.record("Expected exception") + } catch { + #expect(error.description.contains("TestError")) + } + // A throwing generic call must not strand its argument on the shared + // stack: the next call has to read its own value back. + #expect(try jsGenericThrowOrRoundTrip(false, GenericRTPoint(x: 7, y: 8)).y == 8) + } + + @Test func importGenericConstructor() throws { + let boxedInt = try ImportGenericBoxed(42) + #expect(try boxedInt.unwrap() == 42) + let boxedText = try ImportGenericBoxed("boxed") + #expect(try boxedText.unwrap() == "boxed") + let boxedPoint = try ImportGenericBoxed(GenericRTPoint(x: 1, y: 2)) + let point: GenericRTPoint = try boxedPoint.unwrap() + #expect(point.x == 1) + #expect(point.y == 2) + } + + @Test func importGenericStaticMethod() throws { + #expect(try ImportGenericConsumer.box(7) == 7) + #expect(try ImportGenericConsumer.box("s") == "s") + #expect(try ImportGenericConsumer.box(true) == true) + let color = try ImportGenericConsumer.box(GenericRTColor.green) + #expect(color == .green) + } +} diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index 9ca873301..b7e21e821 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -161,6 +161,38 @@ export async function setupOptions(options, context) { jsJoinOptionalStructThenArray: joinStackParams, jsJoinEnumThenArray: joinStackParams, jsJoinStringThenStackParams: joinStackParams, + jsGenericRoundTrip: (v) => v, + jsGenericRoundTripClass: (v) => v, + jsGenericParsePoint: (json) => JSON.parse(json), + jsImportPickFirst: (a, b) => a, + jsImportMakeInt: () => 123, + jsImportCombineSecond: (a, b) => b, + jsGenericThrowOrRoundTrip: (shouldThrow, v) => { + if (shouldThrow) { + throw new Error("TestError"); + } + return v; + }, + jsGenericArrayRoundTrip: (v) => v, + jsGenericOptionalRoundTrip: (v) => v, + jsGenericDictRoundTrip: (v) => v, + jsGenericAfterOptionalArray: (a, b) => `${JSON.stringify(a)}|${JSON.stringify(b)}`, + ImportGenericConsumer: class { + identity(value) { + return value; + } + static box(value) { + return value; + } + }, + ImportGenericBoxed: class { + constructor(value) { + this.value = value; + } + unwrap() { + return this.value; + } + }, roundTripArrayMembers: (value) => { return value; }, From d13c994af4f403a267b80f1fef46e41201468890 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Tue, 11 Aug 2026 14:42:03 +0200 Subject: [PATCH 39/50] BridgeJS: Register core generic type handles in JavaScriptKit --- Benchmarks/Sources/Generated/BridgeJS.swift | 15 ---- .../PlayBridgeJS/Generated/BridgeJS.swift | 15 ---- .../Sources/BridgeJSCore/ExportSwift.swift | 4 ++ .../Sources/BridgeJSLink/BridgeJSLink.swift | 71 +++++++++++++------ .../BridgeJSSkeleton/BridgeJSSkeleton.swift | 25 ++++--- .../BridgeJSCodegenTests/Alias.swift | 15 ---- .../BridgeJSCodegenTests/AliasInClosure.swift | 15 ---- .../BridgeJSCodegenTests/ArrayTypes.swift | 15 ---- .../BridgeJSCodegenTests/Async.swift | 15 ---- .../AsyncAssociatedValueEnum.swift | 15 ---- .../ClassWithNestedTypes.swift | 15 ---- .../DefaultParameters.swift | 15 ---- .../DictionaryTypes.swift | 15 ---- .../BridgeJSCodegenTests/DocComments.swift | 15 ---- .../BridgeJSCodegenTests/EnumAlias.swift | 15 ---- .../EnumAssociatedValue.swift | 15 ---- .../EnumAssociatedValueImport.swift | 15 ---- .../BridgeJSCodegenTests/EnumCase.swift | 15 ---- .../BridgeJSCodegenTests/EnumCaseImport.swift | 15 ---- .../EnumNamespace.Global.swift | 15 ---- .../BridgeJSCodegenTests/EnumNamespace.swift | 15 ---- .../BridgeJSCodegenTests/EnumRawType.swift | 15 ---- .../BridgeJSCodegenTests/GenericImports.swift | 15 ---- .../ImportedTypeInExportedInterface.swift | 15 ---- .../BridgeJSCodegenTests/JSNameOverride.swift | 15 ---- .../BridgeJSCodegenTests/NestedType.swift | 15 ---- .../BridgeJSCodegenTests/Protocol.swift | 15 ---- .../StaticFunctions.Global.swift | 15 ---- .../StaticFunctions.swift | 15 ---- .../StaticProperties.Global.swift | 15 ---- .../StaticProperties.swift | 15 ---- .../StructWithNestedTypes.swift | 15 ---- .../BridgeJSCodegenTests/SwiftClosure.swift | 15 ---- .../BridgeJSCodegenTests/SwiftStruct.swift | 15 ---- .../SwiftStructImports.swift | 15 ---- .../BridgeJSCodegenTests/UnsafePointer.swift | 15 ---- .../__Snapshots__/BridgeJSLinkTests/Alias.js | 1 + .../BridgeJSLinkTests/AliasInClosure.js | 1 + .../BridgeJSLinkTests/ArrayTypes.js | 1 + .../__Snapshots__/BridgeJSLinkTests/Async.js | 1 + .../AsyncAssociatedValueEnum.js | 1 + .../BridgeJSLinkTests/AsyncImport.js | 1 + .../BridgeJSLinkTests/AsyncStaticImport.js | 1 + .../BridgeJSLinkTests/ClassWithNestedTypes.js | 1 + .../BridgeJSLinkTests/DefaultParameters.js | 1 + .../BridgeJSLinkTests/DictionaryTypes.js | 1 + .../BridgeJSLinkTests/DocComments.js | 1 + .../BridgeJSLinkTests/EnumAlias.js | 1 + .../BridgeJSLinkTests/EnumAssociatedValue.js | 1 + .../EnumAssociatedValueImport.js | 1 + .../BridgeJSLinkTests/EnumCase.js | 1 + .../BridgeJSLinkTests/EnumCaseImport.js | 1 + .../BridgeJSLinkTests/EnumNamespace.Global.js | 1 + .../BridgeJSLinkTests/EnumNamespace.js | 1 + .../BridgeJSLinkTests/EnumRawType.js | 1 + .../BridgeJSLinkTests/FixedWidthIntegers.js | 1 + .../BridgeJSLinkTests/GenericImports.js | 17 ++++- .../BridgeJSLinkTests/GlobalGetter.js | 1 + .../BridgeJSLinkTests/GlobalThisImports.js | 1 + .../IdentityModeClass.ConfigPointer.js | 1 + .../IdentityModeClass.PerClass.js | 1 + .../BridgeJSLinkTests/IdentityModeClass.js | 1 + .../BridgeJSLinkTests/ImportArray.js | 1 + .../ImportedTypeInExportedInterface.js | 1 + .../BridgeJSLinkTests/InvalidPropertyNames.js | 1 + .../BridgeJSLinkTests/JSClass.js | 1 + .../JSClassStaticFunctions.js | 1 + .../BridgeJSLinkTests/JSImportBareModule.js | 1 + .../JSImportBareModuleFallback.js | 1 + .../BridgeJSLinkTests/JSImportModule.js | 1 + .../BridgeJSLinkTests/JSNameOverride.js | 1 + .../BridgeJSLinkTests/JSTypedArrayTypes.js | 1 + .../BridgeJSLinkTests/JSValue.js | 1 + .../BridgeJSLinkTests/MixedGlobal.js | 1 + .../BridgeJSLinkTests/MixedModules.js | 1 + .../BridgeJSLinkTests/MixedPrivate.js | 1 + .../BridgeJSLinkTests/Namespaces.Global.js | 1 + .../BridgeJSLinkTests/Namespaces.js | 1 + .../BridgeJSLinkTests/NestedType.js | 1 + .../BridgeJSLinkTests/Optionals.js | 1 + .../BridgeJSLinkTests/PrimitiveParameters.js | 1 + .../BridgeJSLinkTests/PrimitiveReturn.js | 1 + .../BridgeJSLinkTests/PropertyTypes.js | 1 + .../BridgeJSLinkTests/Protocol.js | 1 + .../BridgeJSLinkTests/ProtocolInClosure.js | 1 + .../StaticFunctions.Global.js | 1 + .../BridgeJSLinkTests/StaticFunctions.js | 1 + .../StaticProperties.Global.js | 1 + .../BridgeJSLinkTests/StaticProperties.js | 1 + .../BridgeJSLinkTests/StringParameter.js | 1 + .../BridgeJSLinkTests/StringReturn.js | 1 + .../StructWithNestedTypes.js | 1 + .../BridgeJSLinkTests/SwiftClass.js | 1 + .../BridgeJSLinkTests/SwiftClosure.js | 1 + .../BridgeJSLinkTests/SwiftClosureImports.js | 1 + .../BridgeJSLinkTests/SwiftStruct.js | 1 + .../BridgeJSLinkTests/SwiftStructImports.js | 1 + .../SwiftTypedClosureAccess.js | 1 + .../__Snapshots__/BridgeJSLinkTests/Throws.js | 1 + .../BridgeJSLinkTests/UnsafePointer.js | 1 + .../VoidParameterVoidReturn.js | 1 + Plugins/PackageToJS/Templates/instantiate.js | 3 + .../JavaScriptKit/BridgeJSIntrinsics.swift | 50 +++++++++++++ .../Generated/BridgeJS.swift | 15 ---- .../Generated/BridgeJS.swift | 15 ---- 105 files changed, 201 insertions(+), 558 deletions(-) diff --git a/Benchmarks/Sources/Generated/BridgeJS.swift b/Benchmarks/Sources/Generated/BridgeJS.swift index 81888845b..5e3e11db8 100644 --- a/Benchmarks/Sources/Generated/BridgeJS.swift +++ b/Benchmarks/Sources/Generated/BridgeJS.swift @@ -2275,21 +2275,6 @@ fileprivate func _bjs_Benchmarks_register_type_handles_extern(_ base: UnsafePoin @_expose(wasm, "bjs_Benchmarks_register_type_handles") public func _bjs_Benchmarks_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, SimpleStruct.bridgeJSTypeID, Address.bridgeJSTypeID, Person.bridgeJSTypeID, diff --git a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift index dff715c64..328ae0610 100644 --- a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift +++ b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/Generated/BridgeJS.swift @@ -295,21 +295,6 @@ fileprivate func _bjs_PlayBridgeJS_register_type_handles_extern(_ base: UnsafePo @_expose(wasm, "bjs_PlayBridgeJS_register_type_handles") public func _bjs_PlayBridgeJS_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, PlayBridgeJSOutput.bridgeJSTypeID, PlayBridgeJSDiagnostic.bridgeJSTypeID, PlayBridgeJSResult.bridgeJSTypeID, diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift index e4d0f5b02..1508363c2 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift @@ -908,6 +908,10 @@ struct GenericConformanceCodegen { /// registered type's `bridgeJSTypeID` into a buffer, in the canonical order of /// `BridgeJSSkeleton.typeRegistrationEntries`, and passes it to the JS import /// hook of the same name, which pairs the IDs with its codec array by index. +/// +/// Only the module's own `@JS` types are listed; the core (primitive) handles are +/// registered once by the JavaScriptKit library itself +/// (`_bjs_core_register_type_handles`). public struct GenericTypeRegistrationCodegen { public init() {} diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index 7a407889f..081d1c642 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -348,6 +348,11 @@ public struct BridgeJSLink { declarations.append(" return;") declarations.append(" }") declarations.append(" __bjs_typeHandlesRegistered = true;") + // The core (primitive) handles live in the JavaScriptKit library, so + // they are registered once here rather than by every module. + declarations.append( + " \(JSGlueVariableScope.reservedInstance).exports[\"\(ABINameGenerator.coreTypeRegistrationFunctionName)\"]();" + ) for skeleton in skeletons { guard skeleton.typeRegistrationEntries != nil else { continue } let name = ABINameGenerator.typeRegistrationFunctionName(moduleName: skeleton.moduleName) @@ -426,46 +431,70 @@ public struct BridgeJSLink { ) } + /// Pairs the type IDs Swift pushed with codecs in the matching skeleton order. + private func writeTypeHandleRegistrationBody(into printer: CodeFragmentPrinter) { + printer.write( + "const typeIds = new Int32Array(\(JSGlueVariableScope.reservedMemory).buffer, base >>> 0, count >>> 0);" + ) + printer.write("for (let i = 0; i < count; i++) {") + printer.indent { + printer.write("\(JSGlueVariableScope.reservedCodecByTypeId).set(typeIds[i], codecs[i]);") + } + printer.write("}") + } + + /// Installs the `bjs_core_register_type_handles` hook. The core handles are + /// owned by the JavaScriptKit library rather than by generated code, so the + /// wasm import exists in every binary that links JavaScriptKit and the hook + /// is always installed; without generics anywhere in the build it is a no-op + /// and the registration export is never called. + private func generateCoreTypeRegistrationHook(into printer: CodeFragmentPrinter) throws { + let hookName = ABINameGenerator.coreTypeRegistrationFunctionName + guard hasGenerics else { + printer.write("bjs[\"\(hookName)\"] = function() {};") + return + } + try ContainerCodecJS.registerPrimitiveCodecs(context: makeCodecPrintContext(printer: printer)) + printer.write("bjs[\"\(hookName)\"] = function(base, count) {") + printer.indent { + // Same canonical order as `_bjs_core_register_type_handles` in the + // JavaScriptKit library. + printer.write("const codecs = [") + printer.indent { + for primitive in BridgeType.genericBridgeablePrimitives { + printer.write("\(JSGlueVariableScope.reservedPrimitiveCodecs).\(primitive.token),") + } + } + printer.write("];") + writeTypeHandleRegistrationBody(into: printer) + } + printer.write("}") + } + /// Installs the per-module `bjs__register_type_handles` import /// hooks. A module with a registration function always carries the wasm /// import, so a hook is always installed; without generics anywhere in the /// build it is a no-op and the registration export is never called. private func generateTypeRegistrationHooks(into printer: CodeFragmentPrinter) throws { + try generateCoreTypeRegistrationHook(into: printer) for skeleton in skeletons { - guard skeleton.typeRegistrationEntries != nil else { continue } + guard let moduleEntries = skeleton.typeRegistrationEntries else { continue } let hookName = ABINameGenerator.typeRegistrationFunctionName(moduleName: skeleton.moduleName) guard hasGenerics else { printer.write("bjs[\"\(hookName)\"] = function() {};") continue } - // The hooks resolve type IDs against the shared primitive codec table. - try ContainerCodecJS.registerPrimitiveCodecs(context: makeCodecPrintContext(printer: printer)) - let moduleEntries = skeleton.exported?.genericBridgeableTypeEntries ?? [] printer.write("bjs[\"\(hookName)\"] = function(base, count) {") try printer.indent { - // Same canonical order as the Swift registration function: - // primitives first, then the module's own types. + // Same order as the module's Swift registration function. printer.write("const codecs = [") - printer.indent { - for primitive in BridgeType.genericBridgeablePrimitives { - printer.write("\(JSGlueVariableScope.reservedPrimitiveCodecs).\(primitive.token),") - } - } - printer.write("].concat([") try printer.indent { for entry in moduleEntries { try appendGenericCodecLiteral(type: entry.bridgeType, into: printer) } } - printer.write("]);") - printer.write( - "const typeIds = new Int32Array(\(JSGlueVariableScope.reservedMemory).buffer, base >>> 0, count >>> 0);" - ) - printer.write("for (let i = 0; i < count; i++) {") - printer.indent { - printer.write("\(JSGlueVariableScope.reservedCodecByTypeId).set(typeIds[i], codecs[i]);") - } - printer.write("}") + printer.write("];") + writeTypeHandleRegistrationBody(into: printer) } printer.write("}") } diff --git a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift index 2cea16fb4..641105d12 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift @@ -32,6 +32,13 @@ public struct ABINameGenerator { "bjs_\(moduleName)_register_type_handles" } + /// Name of the core type-handle registration function. Unlike the per-module + /// ones, this is defined once in the JavaScriptKit library (see + /// `_bjs_core_register_type_handles` in `BridgeJSIntrinsics.swift`) so the + /// primitive handles exist exactly once in the final binary and the JS glue + /// registers their codecs once per linked bundle. + public static let coreTypeRegistrationFunctionName = "bjs_core_register_type_handles" + /// Generates ABI name using standardized namespace + context pattern public static func generateABIName( baseName: String, @@ -383,17 +390,17 @@ extension ExportedSkeleton { extension BridgeJSSkeleton { /// The ordered list of types this module registers type handles for, or - /// `nil` when it emits no registration function. Primitive handles are - /// library singletons, so every module re-registering them writes the same - /// ID-to-codec pair, and a pure-import build still gets a populated table. + /// `nil` when it emits no registration function. + /// + /// Only the module's own `@JS` types appear here: the core (primitive) + /// handles are owned by the JavaScriptKit library, which registers them once + /// for the whole binary via ``ABINameGenerator/coreTypeRegistrationFunctionName``. + /// A module that only *uses* generics therefore needs no registration + /// function of its own. public var typeRegistrationEntries: [GenericBridgeableTypeEntry]? { let exportedEntries = exported?.genericBridgeableTypeEntries ?? [] - let hasGenericImports = imported?.hasGenericDeclarations ?? false - guard !exportedEntries.isEmpty || hasGenericImports else { return nil } - let primitives = BridgeType.genericBridgeablePrimitives.map { - GenericBridgeableTypeEntry(swiftName: $0.token, bridgeType: $0.type) - } - return primitives + exportedEntries + guard !exportedEntries.isEmpty else { return nil } + return exportedEntries } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.swift index 7fc853579..4483de428 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Alias.swift @@ -415,21 +415,6 @@ fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePoin @_expose(wasm, "bjs_TestModule_register_type_handles") public func _bjs_TestModule_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, PolygonReference.bridgeJSTypeID, TagReference.bridgeJSTypeID, InnerTag.bridgeJSTypeID, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.swift index 9d9c40502..0a208bf70 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AliasInClosure.swift @@ -200,21 +200,6 @@ fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePoin @_expose(wasm, "bjs_TestModule_register_type_handles") public func _bjs_TestModule_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, PolygonReference.bridgeJSTypeID, ] typeIds.withUnsafeBufferPointer { buffer in diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift index af2ddb544..94b8eb208 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ArrayTypes.swift @@ -664,21 +664,6 @@ fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePoin @_expose(wasm, "bjs_TestModule_register_type_handles") public func _bjs_TestModule_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, Point.bridgeJSTypeID, Direction.bridgeJSTypeID, Status.bridgeJSTypeID, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift index bb51829d7..81c8c1c56 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift @@ -734,21 +734,6 @@ fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePoin @_expose(wasm, "bjs_TestModule_register_type_handles") public func _bjs_TestModule_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, AsyncPoint.bridgeJSTypeID, AsyncDirection.bridgeJSTypeID, AsyncTheme.bridgeJSTypeID, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncAssociatedValueEnum.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncAssociatedValueEnum.swift index 8ea2e5449..6776998bc 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncAssociatedValueEnum.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/AsyncAssociatedValueEnum.swift @@ -126,21 +126,6 @@ fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePoin @_expose(wasm, "bjs_TestModule_register_type_handles") public func _bjs_TestModule_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, AsyncPayloadResult.bridgeJSTypeID, ] typeIds.withUnsafeBufferPointer { buffer in diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ClassWithNestedTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ClassWithNestedTypes.swift index b8736635d..c9c291317 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ClassWithNestedTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ClassWithNestedTypes.swift @@ -191,21 +191,6 @@ fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePoin @_expose(wasm, "bjs_TestModule_register_type_handles") public func _bjs_TestModule_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, Account.Credentials.bridgeJSTypeID, Account.Role.bridgeJSTypeID, ] diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.swift index 4f343476a..e2e74e532 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DefaultParameters.swift @@ -657,21 +657,6 @@ fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePoin @_expose(wasm, "bjs_TestModule_register_type_handles") public func _bjs_TestModule_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, Config.bridgeJSTypeID, MathOperations.bridgeJSTypeID, Status.bridgeJSTypeID, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.swift index 090e93eb0..2990eeabe 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DictionaryTypes.swift @@ -181,21 +181,6 @@ fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePoin @_expose(wasm, "bjs_TestModule_register_type_handles") public func _bjs_TestModule_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, Counters.bridgeJSTypeID, ] typeIds.withUnsafeBufferPointer { buffer in diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DocComments.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DocComments.swift index 03dfba96a..fab694b18 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DocComments.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/DocComments.swift @@ -331,21 +331,6 @@ fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePoin @_expose(wasm, "bjs_TestModule_register_type_handles") public func _bjs_TestModule_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, Point.bridgeJSTypeID, Color.bridgeJSTypeID, ] diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAlias.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAlias.swift index 812ece23e..5689b143f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAlias.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAlias.swift @@ -64,21 +64,6 @@ fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePoin @_expose(wasm, "bjs_TestModule_register_type_handles") public func _bjs_TestModule_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, ColorBox.bridgeJSTypeID, ] typeIds.withUnsafeBufferPointer { buffer in diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.swift index 875d6f601..4ca3236f8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValue.swift @@ -684,21 +684,6 @@ fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePoin @_expose(wasm, "bjs_TestModule_register_type_handles") public func _bjs_TestModule_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, Point.bridgeJSTypeID, APIResult.bridgeJSTypeID, ComplexResult.bridgeJSTypeID, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValueImport.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValueImport.swift index 5e597d6ae..2c275a7a3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValueImport.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumAssociatedValueImport.swift @@ -122,21 +122,6 @@ fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePoin @_expose(wasm, "bjs_TestModule_register_type_handles") public func _bjs_TestModule_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, PayloadSignal.bridgeJSTypeID, ] typeIds.withUnsafeBufferPointer { buffer in diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCase.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCase.swift index c8ea2699f..dab981312 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCase.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCase.swift @@ -252,21 +252,6 @@ fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePoin @_expose(wasm, "bjs_TestModule_register_type_handles") public func _bjs_TestModule_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, Direction.bridgeJSTypeID, Status.bridgeJSTypeID, TSDirection.bridgeJSTypeID, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCaseImport.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCaseImport.swift index 9bab304a9..6ed293525 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCaseImport.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumCaseImport.swift @@ -107,21 +107,6 @@ fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePoin @_expose(wasm, "bjs_TestModule_register_type_handles") public func _bjs_TestModule_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, Signal.bridgeJSTypeID, ] typeIds.withUnsafeBufferPointer { buffer in diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift index 2801e1788..9d6908bcc 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.Global.swift @@ -383,21 +383,6 @@ fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePoin @_expose(wasm, "bjs_TestModule_register_type_handles") public func _bjs_TestModule_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, Networking.API.Method.bridgeJSTypeID, Configuration.LogLevel.bridgeJSTypeID, Configuration.Port.bridgeJSTypeID, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift index 2801e1788..9d6908bcc 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumNamespace.swift @@ -383,21 +383,6 @@ fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePoin @_expose(wasm, "bjs_TestModule_register_type_handles") public func _bjs_TestModule_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, Networking.API.Method.bridgeJSTypeID, Configuration.LogLevel.bridgeJSTypeID, Configuration.Port.bridgeJSTypeID, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.swift index e91f1b231..2dbb21422 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/EnumRawType.swift @@ -547,21 +547,6 @@ fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePoin @_expose(wasm, "bjs_TestModule_register_type_handles") public func _bjs_TestModule_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, Theme.bridgeJSTypeID, TSTheme.bridgeJSTypeID, FeatureFlag.bridgeJSTypeID, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericImports.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericImports.swift index 044fd0e57..7714c498e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericImports.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericImports.swift @@ -492,21 +492,6 @@ fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePoin @_expose(wasm, "bjs_TestModule_register_type_handles") public func _bjs_TestModule_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, GenericPoint.bridgeJSTypeID, GenericImportBox.bridgeJSTypeID, GenericColor.bridgeJSTypeID, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.swift index dfec6b6a0..b9fddf706 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportedTypeInExportedInterface.swift @@ -135,21 +135,6 @@ fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePoin @_expose(wasm, "bjs_TestModule_register_type_handles") public func _bjs_TestModule_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, FooContainer.bridgeJSTypeID, ] typeIds.withUnsafeBufferPointer { buffer in diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSNameOverride.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSNameOverride.swift index 5f767abdb..8e01bca22 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSNameOverride.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/JSNameOverride.swift @@ -365,21 +365,6 @@ fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePoin @_expose(wasm, "bjs_TestModule_register_type_handles") public func _bjs_TestModule_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, RenamedVector.bridgeJSTypeID, RenamedEnumMembers.bridgeJSTypeID, ] diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedType.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedType.swift index ca1c98a75..9e1b0e0f6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedType.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedType.swift @@ -193,21 +193,6 @@ fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePoin @_expose(wasm, "bjs_TestModule_register_type_handles") public func _bjs_TestModule_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, User.Stats.bridgeJSTypeID, Player.Stats.bridgeJSTypeID, ] diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift index 2ef680b8a..7c2db9a98 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Protocol.swift @@ -1068,21 +1068,6 @@ fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePoin @_expose(wasm, "bjs_TestModule_register_type_handles") public func _bjs_TestModule_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, Direction.bridgeJSTypeID, ExampleEnum.bridgeJSTypeID, Result.bridgeJSTypeID, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift index 18e91616c..2d5a93c54 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.Global.swift @@ -224,21 +224,6 @@ fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePoin @_expose(wasm, "bjs_TestModule_register_type_handles") public func _bjs_TestModule_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, Calculator.bridgeJSTypeID, APIResult.bridgeJSTypeID, ] diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift index 18e91616c..2d5a93c54 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticFunctions.swift @@ -224,21 +224,6 @@ fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePoin @_expose(wasm, "bjs_TestModule_register_type_handles") public func _bjs_TestModule_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, Calculator.bridgeJSTypeID, APIResult.bridgeJSTypeID, ] diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.swift index 75c4382dd..721c5335a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.Global.swift @@ -351,21 +351,6 @@ fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePoin @_expose(wasm, "bjs_TestModule_register_type_handles") public func _bjs_TestModule_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, PropertyEnum.bridgeJSTypeID, ] typeIds.withUnsafeBufferPointer { buffer in diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.swift index 75c4382dd..721c5335a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StaticProperties.swift @@ -351,21 +351,6 @@ fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePoin @_expose(wasm, "bjs_TestModule_register_type_handles") public func _bjs_TestModule_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, PropertyEnum.bridgeJSTypeID, ] typeIds.withUnsafeBufferPointer { buffer in diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StructWithNestedTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StructWithNestedTypes.swift index 1b8a69739..8fc6db1a7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StructWithNestedTypes.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/StructWithNestedTypes.swift @@ -283,21 +283,6 @@ fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePoin @_expose(wasm, "bjs_TestModule_register_type_handles") public func _bjs_TestModule_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, Shape.bridgeJSTypeID, Widget.bridgeJSTypeID, Widget.Layout.bridgeJSTypeID, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift index bad3ba0e1..f349f0c40 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift @@ -2749,21 +2749,6 @@ fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePoin @_expose(wasm, "bjs_TestModule_register_type_handles") public func _bjs_TestModule_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, Animal.bridgeJSTypeID, Direction.bridgeJSTypeID, Theme.bridgeJSTypeID, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift index 7aca6afd5..b4e54961c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStruct.swift @@ -675,21 +675,6 @@ fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePoin @_expose(wasm, "bjs_TestModule_register_type_handles") public func _bjs_TestModule_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, DataPoint.bridgeJSTypeID, Address.bridgeJSTypeID, Person.bridgeJSTypeID, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.swift index a5c5d9fd8..4e9899470 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.swift @@ -101,21 +101,6 @@ fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePoin @_expose(wasm, "bjs_TestModule_register_type_handles") public func _bjs_TestModule_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, Point.bridgeJSTypeID, ] typeIds.withUnsafeBufferPointer { buffer in diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/UnsafePointer.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/UnsafePointer.swift index 615608687..69011da18 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/UnsafePointer.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/UnsafePointer.swift @@ -190,21 +190,6 @@ fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePoin @_expose(wasm, "bjs_TestModule_register_type_handles") public func _bjs_TestModule_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, PointerFields.bridgeJSTypeID, ] typeIds.withUnsafeBufferPointer { buffer in diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js index d8a23090a..c9c09bd97 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js @@ -449,6 +449,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js index cb130421b..fa9095cd8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AliasInClosure.js @@ -131,6 +131,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js index 39c0507c1..86a84490e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js @@ -448,6 +448,7 @@ export async function createInstantiator(options, swift) { const value = structHelpers.Point.lift(); return swift.memory.retain(value); } + bjs["bjs_core_register_type_handles"] = function() {}; bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js index 497c71bf8..4b3e0c3ed 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js @@ -444,6 +444,7 @@ export async function createInstantiator(options, swift) { const value = structHelpers.AsyncPoint.lift(); return swift.memory.retain(value); } + bjs["bjs_core_register_type_handles"] = function() {}; bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js index 8e09e38d9..5671e4898 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js @@ -239,6 +239,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js index fa50b23f2..96c0d11e8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncImport.js @@ -221,6 +221,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js index c359886b3..47dd161a2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js @@ -220,6 +220,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.js index db3288037..30d0522c0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.js @@ -130,6 +130,7 @@ export async function createInstantiator(options, swift) { const value = structHelpers.Account_Credentials.lift(); return swift.memory.retain(value); } + bjs["bjs_core_register_type_handles"] = function() {}; bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js index 16505d112..ac3a508da 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js @@ -472,6 +472,7 @@ export async function createInstantiator(options, swift) { const value = structHelpers.MathOperations.lift(); return swift.memory.retain(value); } + bjs["bjs_core_register_type_handles"] = function() {}; bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js index 78e1d4c54..2ddf3e217 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js @@ -438,6 +438,7 @@ export async function createInstantiator(options, swift) { const value = structHelpers.Counters.lift(); return swift.memory.retain(value); } + bjs["bjs_core_register_type_handles"] = function() {}; bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.js index 53cd64917..65323aace 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.js @@ -130,6 +130,7 @@ export async function createInstantiator(options, swift) { const value = structHelpers.Point.lift(); return swift.memory.retain(value); } + bjs["bjs_core_register_type_handles"] = function() {}; bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js index 43ff590b4..d8bc06fcf 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAlias.js @@ -106,6 +106,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js index 814736050..b98b2af7e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js @@ -1064,6 +1064,7 @@ export async function createInstantiator(options, swift) { const value = structHelpers.Point.lift(); return swift.memory.retain(value); } + bjs["bjs_core_register_type_handles"] = function() {}; bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js index a31c96450..bc0df916b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js @@ -150,6 +150,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js index 169ade160..838e3062b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCase.js @@ -130,6 +130,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js index fa128130a..b4e67b6b8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js @@ -111,6 +111,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js index 859703175..0a691374b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.Global.js @@ -150,6 +150,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js index 81c1eacd9..03f0a8d9a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumNamespace.js @@ -131,6 +131,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js index ac8dc0ff5..92e1868c7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js @@ -492,6 +492,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js index a009f8d71..56a31b784 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/FixedWidthIntegers.js @@ -107,6 +107,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js index e01f6fffc..f9a599e80 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js @@ -51,6 +51,7 @@ export async function createInstantiator(options, swift) { return; } __bjs_typeHandlesRegistered = true; + instance.exports["bjs_core_register_type_handles"](); instance.exports["bjs_TestModule_register_type_handles"](); } function __bjs_codecForTypeId(typeId) { @@ -501,7 +502,7 @@ export async function createInstantiator(options, swift) { const value = structHelpers.GenericPoint.lift(); return swift.memory.retain(value); } - bjs["bjs_TestModule_register_type_handles"] = function(base, count) { + bjs["bjs_core_register_type_handles"] = function(base, count) { const codecs = [ __bjs_primitiveCodecs.Bool, __bjs_primitiveCodecs.Int, @@ -518,7 +519,17 @@ export async function createInstantiator(options, swift) { __bjs_primitiveCodecs.Double, __bjs_primitiveCodecs.String, __bjs_primitiveCodecs.JSValue, - ].concat([ + ]; + if (count !== codecs.length) { + throw new Error("BridgeJS: type handle registration mismatch for core types"); + } + const typeIds = new Int32Array(memory.buffer, base >>> 0, count >>> 0); + for (let i = 0; i < count; i++) { + __bjs_codecByTypeId.set(typeIds[i], codecs[i]); + } + } + bjs["bjs_TestModule_register_type_handles"] = function(base, count) { + const codecs = [ { lower: (v) => { structHelpers.GenericPoint.lower(v); @@ -569,7 +580,7 @@ export async function createInstantiator(options, swift) { return enumValue; }, }, - ]); + ]; const typeIds = new Int32Array(memory.buffer, base >>> 0, count >>> 0); for (let i = 0; i < count; i++) { __bjs_codecByTypeId.set(typeIds[i], codecs[i]); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js index b1d830768..adb70913c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalGetter.js @@ -107,6 +107,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js index 6f43c2d9c..760a6b50c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GlobalThisImports.js @@ -106,6 +106,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js index 83f53d8a6..1e1d14696 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.ConfigPointer.js @@ -106,6 +106,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js index bb6f36902..c85aee3af 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.PerClass.js @@ -106,6 +106,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js index bb6f36902..c85aee3af 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/IdentityModeClass.js @@ -106,6 +106,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js index bf1707b56..77cde8a89 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js @@ -417,6 +417,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js index 8974e3722..e3fbdba8d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js @@ -472,6 +472,7 @@ export async function createInstantiator(options, swift) { const value = structHelpers.FooContainer.lift(); return swift.memory.retain(value); } + bjs["bjs_core_register_type_handles"] = function() {}; bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js index 8d1ac2698..e8fe5ec10 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/InvalidPropertyNames.js @@ -107,6 +107,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js index 08215f159..15b48d4b9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClass.js @@ -107,6 +107,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js index a38b0a391..5eaba3c8f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSClassStaticFunctions.js @@ -107,6 +107,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModule.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModule.js index 1c995923a..6d1b1b6fb 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModule.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModule.js @@ -112,6 +112,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModuleFallback.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModuleFallback.js index 038374240..9428698be 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModuleFallback.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportBareModuleFallback.js @@ -109,6 +109,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.js index e03dcbab4..aacf5e61a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSImportModule.js @@ -109,6 +109,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.js index 026acf3f4..7d11a24ff 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.js @@ -135,6 +135,7 @@ export async function createInstantiator(options, swift) { const value = structHelpers.RenamedVector.lift(); return swift.memory.retain(value); } + bjs["bjs_core_register_type_handles"] = function() {}; bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.js index 5c713cc78..f02f6bcf2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSTypedArrayTypes.js @@ -106,6 +106,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js index f39091a1f..136167f2a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js @@ -417,6 +417,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js index 39ecf8d99..5db38dde5 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedGlobal.js @@ -106,6 +106,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js index 62d7651e8..66818952b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedModules.js @@ -106,6 +106,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js index 69bfe5ff1..a732808a6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/MixedPrivate.js @@ -106,6 +106,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js index fcb6dd88d..ef10ff9b9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js @@ -416,6 +416,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js index ef083c4d7..bb4fce7a6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js @@ -416,6 +416,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js index e03b09221..ad0c75942 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js @@ -145,6 +145,7 @@ export async function createInstantiator(options, swift) { const value = structHelpers.Player_Stats.lift(); return swift.memory.retain(value); } + bjs["bjs_core_register_type_handles"] = function() {}; bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js index 0a4fcc28c..7d073e02a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js @@ -417,6 +417,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js index 46d57d793..d4480a65c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveParameters.js @@ -107,6 +107,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js index bb4e8552d..e9b298fb2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PrimitiveReturn.js @@ -107,6 +107,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js index 61560134a..beb9417df 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/PropertyTypes.js @@ -106,6 +106,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js index e2c711f8f..c28ceeb31 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js @@ -473,6 +473,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js index 01f9fe0e1..eed26c581 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ProtocolInClosure.js @@ -131,6 +131,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js index 8f783865e..88fb0c321 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js @@ -150,6 +150,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js index 4841e3350..7c614f070 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js @@ -150,6 +150,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js index 189db1f0e..e2a9093b6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.Global.js @@ -111,6 +111,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js index a5a003a1c..f442745e5 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticProperties.js @@ -111,6 +111,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js index 2c3da5f26..ebddbefd2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringParameter.js @@ -107,6 +107,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js index 057bf9658..d2dfa204f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StringReturn.js @@ -107,6 +107,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.js index 3270abd58..06873bf26 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.js @@ -193,6 +193,7 @@ export async function createInstantiator(options, swift) { const value = structHelpers.Widget_Bounds.lift(); return swift.memory.retain(value); } + bjs["bjs_core_register_type_handles"] = function() {}; bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js index be63f59be..92ef435fb 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClass.js @@ -107,6 +107,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js index bebe9179d..e208ff35c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js @@ -551,6 +551,7 @@ export async function createInstantiator(options, swift) { const value = structHelpers.Animal.lift(); return swift.memory.retain(value); } + bjs["bjs_core_register_type_handles"] = function() {}; bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js index d03915f87..96c78dd22 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosureImports.js @@ -221,6 +221,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js index c16b674ae..ad8d4e29d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js @@ -662,6 +662,7 @@ export async function createInstantiator(options, swift) { const value = structHelpers.Vector2D.lift(); return swift.memory.retain(value); } + bjs["bjs_core_register_type_handles"] = function() {}; bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js index 9d613c8a9..e9add7027 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js @@ -435,6 +435,7 @@ export async function createInstantiator(options, swift) { const value = structHelpers.Point.lift(); return swift.memory.retain(value); } + bjs["bjs_core_register_type_handles"] = function() {}; bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.js index 66d6494fd..500a005a3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftTypedClosureAccess.js @@ -131,6 +131,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js index 6ff126525..58ff6a85a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Throws.js @@ -106,6 +106,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js index 704dbb021..ecc14e5ae 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js @@ -130,6 +130,7 @@ export async function createInstantiator(options, swift) { const value = structHelpers.PointerFields.lift(); return swift.memory.retain(value); } + bjs["bjs_core_register_type_handles"] = function() {}; bjs["bjs_TestModule_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js index 3c75771c5..81b09eaf4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/VoidParameterVoidReturn.js @@ -107,6 +107,7 @@ export async function createInstantiator(options, swift) { const copy = memory.buffer.slice(ptr, ptr + byteLen); taStack.push(Array.from(new Ctor(copy))); } + bjs["bjs_core_register_type_handles"] = function() {}; const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); bjs["swift_js_make_promise"] = function() { let resolve, reject; diff --git a/Plugins/PackageToJS/Templates/instantiate.js b/Plugins/PackageToJS/Templates/instantiate.js index 71aea21ee..3bb1c67af 100644 --- a/Plugins/PackageToJS/Templates/instantiate.js +++ b/Plugins/PackageToJS/Templates/instantiate.js @@ -70,6 +70,9 @@ async function createInstantiator(options, swift) { swift_js_closure_unregister: unexpectedBjsCall, swift_js_push_typed_array: unexpectedBjsCall, swift_js_make_promise: unexpectedBjsCall, + // Imported unconditionally by JavaScriptKit's core type-handle + // registration export, which is only invoked by BridgeJS glue. + bjs_core_register_type_handles: unexpectedBjsCall, }; }, /** @param {WebAssembly.Instance} instance */ diff --git a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift index b15e07b5d..71f7fffce 100644 --- a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift +++ b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift @@ -1013,6 +1013,56 @@ extension JSValue: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = JSValue.bridgeJSMakeTypeHandle() } +// MARK: Core generic type-handle registration +// +// Every `BridgedSwiftGenericBridgeable` type publishes its runtime type ID to the +// JS glue, which pairs the IDs with the codec array it emitted in the same order. +// The core types below are owned by this library, so their registration lives +// here once for the whole binary instead of being copied into every module's +// generated registration function; generated per-module registration only carries +// that module's own `@JS` types. +// +// The order is the ABI contract with the JS side: it must match +// `BridgeType.genericBridgeablePrimitives` in +// `Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift`, from which +// the link step builds the core codec array. `CoreTypeRegistrationContractTests` +// checks the two lists stay in sync at build time, and the generated JS verifies +// the count at registration time. +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_core_register_type_handles") +private func _bjs_core_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +/// Publishes the core (primitive) BridgeJS type handles to the JS glue. +/// +/// Called by the generated glue once per instance, before any module's own +/// registration function. Not intended to be called from user code. +@_expose(wasm, "bjs_core_register_type_handles") +public func _bjs_core_register_type_handles() { + // BEGIN bjs_core_type_handles + let typeIds: [Int32] = [ + Bool.bridgeJSTypeID, + Int.bridgeJSTypeID, + Int8.bridgeJSTypeID, + UInt8.bridgeJSTypeID, + Int16.bridgeJSTypeID, + UInt16.bridgeJSTypeID, + Int32.bridgeJSTypeID, + UInt32.bridgeJSTypeID, + UInt.bridgeJSTypeID, + Int64.bridgeJSTypeID, + UInt64.bridgeJSTypeID, + Float.bridgeJSTypeID, + Double.bridgeJSTypeID, + String.bridgeJSTypeID, + JSValue.bridgeJSTypeID, + ] + // END bjs_core_type_handles + typeIds.withUnsafeBufferPointer { buffer in + _bjs_core_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif + /// A protocol that Swift heap objects exposed to JavaScript via `@JS class` must conform to. /// /// The conformance is automatically synthesized by the BridgeJS code generator. diff --git a/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift b/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift index deedc1ccf..91638a428 100644 --- a/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSGlobalTests/Generated/BridgeJS.swift @@ -378,21 +378,6 @@ fileprivate func _bjs_BridgeJSGlobalTests_register_type_handles_extern(_ base: U @_expose(wasm, "bjs_BridgeJSGlobalTests_register_type_handles") public func _bjs_BridgeJSGlobalTests_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, GlobalNetworking.API.CallMethod.bridgeJSTypeID, GlobalConfiguration.PublicLogLevel.bridgeJSTypeID, GlobalConfiguration.AvailablePort.bridgeJSTypeID, diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index 9c7cc6d2a..c70de88dc 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -19047,21 +19047,6 @@ fileprivate func _bjs_BridgeJSRuntimeTests_register_type_handles_extern(_ base: @_expose(wasm, "bjs_BridgeJSRuntimeTests_register_type_handles") public func _bjs_BridgeJSRuntimeTests_register_type_handles() { let typeIds: [Int32] = [ - Bool.bridgeJSTypeID, - Int.bridgeJSTypeID, - Int8.bridgeJSTypeID, - UInt8.bridgeJSTypeID, - Int16.bridgeJSTypeID, - UInt16.bridgeJSTypeID, - Int32.bridgeJSTypeID, - UInt32.bridgeJSTypeID, - UInt.bridgeJSTypeID, - Int64.bridgeJSTypeID, - UInt64.bridgeJSTypeID, - Float.bridgeJSTypeID, - Double.bridgeJSTypeID, - String.bridgeJSTypeID, - JSValue.bridgeJSTypeID, JSCoordinate.bridgeJSTypeID, NestedStructGroupA.Metadata.bridgeJSTypeID, NestedStructGroupB.Metadata.bridgeJSTypeID, From a09973645680eae790a92d8ba4d7d693e93f7f35 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Tue, 11 Aug 2026 14:51:19 +0200 Subject: [PATCH 40/50] BridgeJS: Share named stack codecs across generated glue --- .../Sources/BridgeJSLink/BridgeJSLink.swift | 86 ++- .../Sources/BridgeJSLink/JSGlueGen.swift | 204 ++++++-- .../BridgeJSLink/JSIntrinsicRegistry.swift | 39 ++ .../NamedCodecHelperTests.swift | 105 ++++ .../__Snapshots__/BridgeJSLinkTests/Alias.js | 89 ++-- .../BridgeJSLinkTests/ArrayTypes.js | 488 +++++++----------- .../__Snapshots__/BridgeJSLinkTests/Async.js | 88 ++-- .../BridgeJSLinkTests/DefaultParameters.js | 55 +- .../BridgeJSLinkTests/DictionaryTypes.js | 100 ++-- .../BridgeJSLinkTests/EnumAssociatedValue.js | 217 ++++---- .../BridgeJSLinkTests/EnumRawType.js | 53 +- .../BridgeJSLinkTests/GenericImports.js | 107 ++-- .../BridgeJSLinkTests/ImportArray.js | 27 +- .../ImportedTypeInExportedInterface.js | 110 +--- .../BridgeJSLinkTests/JSValue.js | 25 +- .../BridgeJSLinkTests/Namespaces.Global.js | 34 +- .../BridgeJSLinkTests/Namespaces.js | 34 +- .../BridgeJSLinkTests/Optionals.js | 93 ++-- .../BridgeJSLinkTests/Protocol.js | 151 +----- .../BridgeJSLinkTests/SwiftClosure.js | 27 +- .../BridgeJSLinkTests/SwiftStruct.js | 103 ++-- .../BridgeJSLinkTests/SwiftStructImports.js | 23 +- 22 files changed, 1031 insertions(+), 1227 deletions(-) create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/NamedCodecHelperTests.swift diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index 081d1c642..5fd37437f 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -413,22 +413,13 @@ public struct BridgeJSLink { ) } - /// Emits a `{ lower, lift }` codec literal for one bridgeable type. - /// `prefix` is prepended to the opening brace (e.g. an assignment) and - /// `suffix` is appended to the closing brace (e.g. `","` in an array). - private func appendGenericCodecLiteral( - type: BridgeType, - into printer: CodeFragmentPrinter, - prefix: String = "", - suffix: String = "," - ) throws { - try ContainerCodecJS.writeCodecLiteral( - type: type, - into: printer, - context: makeCodecPrintContext(printer: printer), - prefix: prefix, - suffix: suffix - ) + /// Returns the module-scope codec helper for one bridgeable type, declaring + /// it if this is the first reference. + /// + /// The registration table and the container combinators' element positions + /// go through the same helper, so a type's stack ABI is described once. + private func genericCodecReference(type: BridgeType, into printer: CodeFragmentPrinter) throws -> String { + try ContainerCodecJS.codecExpression(for: type, context: makeCodecPrintContext(printer: printer)) } /// Pairs the type IDs Swift pushed with codecs in the matching skeleton order. @@ -487,10 +478,13 @@ public struct BridgeJSLink { printer.write("bjs[\"\(hookName)\"] = function(base, count) {") try printer.indent { // Same order as the module's Swift registration function. + let codecNames = try moduleEntries.map { + try genericCodecReference(type: $0.bridgeType, into: printer) + } printer.write("const codecs = [") - try printer.indent { - for entry in moduleEntries { - try appendGenericCodecLiteral(type: entry.bridgeType, into: printer) + printer.indent { + for name in codecNames { + printer.write("\(name),") } } printer.write("];") @@ -1277,6 +1271,18 @@ public struct BridgeJSLink { printer.nextLine() } + // The named codec helpers come after the intrinsics because they are + // built out of the combinators and the primitive codec table, and + // before everything that uses them: they are hoisted here so that no + // call site ever composes a codec. Helpers that delegate to the + // `structHelpers` / `enumHelpers` tables only read those tables when + // called, so declaring them ahead of the tables being populated is + // fine. + if intrinsicRegistry.hasNamedCodecs { + printer.write(lines: intrinsicRegistry.emitNamedCodecLines()) + printer.nextLine() + } + printer.write(lines: bodyPrinter.lines) } printer.indent() @@ -1367,12 +1373,54 @@ public struct BridgeJSLink { } } } + intrinsicRegistry.typeOwnerModules = collectTypeOwnerModules() let data = try collectLinkData() let outputJs = try generateJavaScript(data: data) let outputDts = generateTypeScript(data: data) return (outputJs, outputDts) } + /// Maps every type name a `BridgeType` can carry to the module that declares + /// it, so identifiers minted from type names can be module-qualified. + /// + /// A name declared by two modules is a pre-existing ambiguity in the + /// skeleton format (`BridgeType` carries only the name), so the first + /// declaration wins, which keeps the output deterministic. + private func collectTypeOwnerModules() -> [String: String] { + var result: [String: String] = [:] + func record(_ name: String, _ moduleName: String) { + if result[name] == nil { + result[name] = moduleName + } + } + for unified in skeletons { + let moduleName = unified.moduleName + if let skeleton = unified.exported { + for structDef in skeleton.structs { + record(structDef.name, moduleName) + record(structDef.abiName, moduleName) + } + for klass in skeleton.classes { + record(klass.name, moduleName) + record(klass.abiName, moduleName) + } + for enumDef in skeleton.enums { + record(enumDef.name, moduleName) + record(enumDef.abiName, moduleName) + } + for protocolDef in skeleton.protocols { + record(protocolDef.name, moduleName) + } + } + for file in unified.imported?.children ?? [] { + for type in file.types { + record(type.name, moduleName) + } + } + } + return result + } + private func enumHelperAssignments() -> CodeFragmentPrinter { let printer = CodeFragmentPrinter() diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift index 8da83fa18..f8b5d08a6 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift @@ -102,6 +102,17 @@ final class JSGlueVariableScope { try intrinsicRegistry.register(name: name, build: build) } + /// Registers a module-scope `{ lower, lift }` codec helper shared by every + /// site that needs a codec for the same type shape. + func registerNamedCodec(_ name: String, build: (CodeFragmentPrinter) throws -> Void) rethrows { + try intrinsicRegistry.registerNamedCodec(name: name, build: build) + } + + /// The module declaring `typeName`, when the link step knows it. + func moduleName(declaringType typeName: String) -> String? { + intrinsicRegistry.typeOwnerModules[typeName] + } + func makeChildScope() -> JSGlueVariableScope { JSGlueVariableScope(intrinsicRegistry: intrinsicRegistry) } @@ -197,7 +208,9 @@ enum ContainerCodecJS { static let arrayCodec = "__bjs_arrayCodec" static let optionalCodec = "__bjs_optionalCodec" static let dictCodec = "__bjs_dictCodec" - static let enumCodec = "__bjs_enumCodec" + + /// Prefix of the module-scope codec helper `const`s. + static let namedCodecPrefix = "__bjs_codec_" private static let combinatorIntrinsicName = "containerCodecCombinators" private static let primitiveCodecIntrinsicName = "containerPrimitiveCodecs" @@ -271,18 +284,6 @@ enum ContainerCodecJS { " },", " };", "}", - // Adapts an associated-value enum helper (whose lower returns the case - // tag and whose lift takes it) to the plain stack codec protocol. - "function \(enumCodec)(helper) {", - " return {", - " lower(value) {", - " \(i32).push(helper.lower(value));", - " },", - " lift() {", - " return helper.lift(\(i32).pop());", - " },", - " };", - "}", ] } @@ -365,50 +366,145 @@ enum ContainerCodecJS { printer.write("}\(suffix)") } - /// Returns a JS expression evaluating to the `{ lower, lift }` codec for - /// one element type, registering the shared codec runtime as needed. May - /// write supporting statements (a local codec literal) to the context's - /// printer for element shapes without a named shared codec. + /// A codec that is reachable by name from module scope. + /// + /// `token` is the stable, module-qualified spelling of the type shape; codec + /// names for compositions are derived from their elements' tokens, so the + /// whole naming scheme inherits module qualification from its leaves. + struct NamedCodec { + let expression: String + let token: String + } + + /// Returns a JS expression evaluating to the `{ lower, lift }` codec for one + /// element type, registering the shared codec runtime as needed. + /// + /// Every codec is a module-scope `const`, so a call site never builds one: + /// the same type shape resolves to the same helper wherever it appears, + /// including the generic type-handle registration table. static func codecExpression( for elementType: BridgeType, context: IntrinsicJSFragment.PrintCodeContext ) throws -> String { + try namedCodec(for: elementType, context: context).expression + } + + static func namedCodec( + for elementType: BridgeType, + context: IntrinsicJSFragment.PrintCodeContext + ) throws -> NamedCodec { registerCombinators(scope: context.scope) try registerPrimitiveCodecs(context: context) let type = elementType.unaliased switch type { case .array(let element): - return "\(arrayCodec)(\(try codecExpression(for: element, context: context)))" + let element = try namedCodec(for: element, context: context) + return composedCodec( + token: "Array_\(element.token)", + factory: "\(arrayCodec)(\(element.expression))", + context: context + ) case .dictionary(let value): - return "\(dictCodec)(\(try codecExpression(for: value, context: context)))" + let value = try namedCodec(for: value, context: context) + return composedCodec( + token: "Dict_\(value.token)", + factory: "\(dictCodec)(\(value.expression))", + context: context + ) case .nullable(let wrapped, let kind): - let element = try codecExpression(for: wrapped, context: context) - return optionalCodecExpression(elementCodec: element, kind: kind) + let wrapped = try namedCodec(for: wrapped, context: context) + let prefix = kind == .null ? "Optional" : "UndefinedOr" + return composedCodec( + token: "\(prefix)_\(wrapped.token)", + factory: optionalCodecExpression(elementCodec: wrapped.expression, kind: kind), + context: context + ) case .string, .rawValueEnum(_, .string): - return JSGlueVariableScope.reservedStringCodec - case .swiftStruct(let fullName): - // `@JS` struct helpers already expose the codec protocol. - let base = fullName.replacingOccurrences(of: ".", with: "_") - return "\(JSGlueVariableScope.reservedStructHelpers).\(base)" - case .associatedValueEnum(let fullName): - let base = fullName.components(separatedBy: ".").last ?? fullName - return "\(enumCodec)(\(JSGlueVariableScope.reservedEnumHelpers).\(base))" + // A string-backed raw value enum bridges exactly as its raw value. + return NamedCodec(expression: JSGlueVariableScope.reservedStringCodec, token: "String") default: if let token = BridgeType.genericBridgeablePrimitives.first(where: { $0.type == type })?.token { - return "\(JSGlueVariableScope.reservedPrimitiveCodecs).\(token)" + return NamedCodec( + expression: "\(JSGlueVariableScope.reservedPrimitiveCodecs).\(token)", + token: token + ) } - // Element shapes without a named shared codec (case enums, non-string - // raw-value enums, JSObject, Swift heap objects, ...) get a local - // codec literal built from the same element stack fragments. - let codecVar = context.scope.variable("elemCodec") + return try leafCodec(for: type, context: context) + } + } + + /// Declares (once) a module-scope `const` holding a container combinator + /// instantiated with an already-declared element codec. + private static func composedCodec( + token: String, + factory: String, + context: IntrinsicJSFragment.PrintCodeContext + ) -> NamedCodec { + let name = "\(namedCodecPrefix)\(token)" + context.scope.registerNamedCodec(name) { printer in + printer.write("const \(name) = \(factory);") + } + return NamedCodec(expression: name, token: token) + } + + /// Declares (once) a module-scope `const` holding the codec for a type that + /// is not a container: primitives are handled by the shared table, so this + /// covers `@JS` structs, enums, classes, `JSObject`, protocols and friends. + /// + /// The body comes from ``writeCodecLiteral``, the same emitter the generic + /// type-handle registration uses, so both reference one helper per type. + private static func leafCodec( + for type: BridgeType, + context: IntrinsicJSFragment.PrintCodeContext + ) throws -> NamedCodec { + let token = leafToken(for: type, scope: context.scope) + let name = "\(namedCodecPrefix)\(token)" + // The helper lives at module scope, outside `createExports`, so exported + // Swift classes are not in lexical scope here and must be reached + // through `_exports`. + let hoistedContext = context.with(\.hasDirectAccessToSwiftClass, false) + try context.scope.registerNamedCodec(name) { printer in try writeCodecLiteral( type: type, - into: context.printer, - context: context, - prefix: "const \(codecVar) = ", + into: printer, + context: hoistedContext, + prefix: "const \(name) = ", suffix: ";" ) - return codecVar + } + return NamedCodec(expression: name, token: token) + } + + /// The module-qualified token identifying a non-container type shape. + /// + /// Types declared by a `@JS` module are qualified with the declaring module + /// so two modules declaring the same type name do not mint the same helper. + private static func leafToken(for type: BridgeType, scope: JSGlueVariableScope) -> String { + func sanitized(_ name: String) -> String { + String(name.map { $0.isLetter || $0.isNumber || $0 == "_" ? $0 : "_" }) + } + func qualified(_ name: String) -> String { + let base = sanitized(name) + guard let module = scope.moduleName(declaringType: name) ?? scope.moduleName(declaringType: base) else { + return base + } + return "\(sanitized(module))_\(base)" + } + switch type { + case .jsObject(nil): + return "JSObject" + case .jsObject(let name?): + return qualified(name) + case .swiftStruct(let name), + .swiftHeapObject(let name), + .swiftProtocol(let name), + .caseEnum(let name), + .rawValueEnum(let name, _), + .associatedValueEnum(let name), + .namespaceEnum(let name): + return qualified(name) + default: + return sanitized(type.mangleTypeName) } } } @@ -2033,8 +2129,8 @@ struct IntrinsicJSFragment: Sendable { return IntrinsicJSFragment( parameters: ["arr"], printCode: { arguments, context in - let element = try ContainerCodecJS.codecExpression(for: elementType, context: context) - context.printer.write("\(ContainerCodecJS.arrayCodec)(\(element)).lower(\(arguments[0]));") + let codec = try ContainerCodecJS.codecExpression(for: .array(elementType), context: context) + context.printer.write("\(codec).lower(\(arguments[0]));") return [] } ) @@ -2045,8 +2141,8 @@ struct IntrinsicJSFragment: Sendable { return IntrinsicJSFragment( parameters: ["dict"], printCode: { arguments, context in - let value = try ContainerCodecJS.codecExpression(for: valueType, context: context) - context.printer.write("\(ContainerCodecJS.dictCodec)(\(value)).lower(\(arguments[0]));") + let codec = try ContainerCodecJS.codecExpression(for: .dictionary(valueType), context: context) + context.printer.write("\(codec).lower(\(arguments[0]));") return [] } ) @@ -2057,11 +2153,9 @@ struct IntrinsicJSFragment: Sendable { return IntrinsicJSFragment( parameters: [], printCode: { _, context in - let element = try ContainerCodecJS.codecExpression(for: elementType, context: context) + let codec = try ContainerCodecJS.codecExpression(for: .array(elementType), context: context) let resultVar = context.scope.variable("arrayResult") - context.printer.write( - "const \(resultVar) = \(ContainerCodecJS.arrayCodec)(\(element)).lift();" - ) + context.printer.write("const \(resultVar) = \(codec).lift();") return [resultVar] } ) @@ -2072,11 +2166,9 @@ struct IntrinsicJSFragment: Sendable { return IntrinsicJSFragment( parameters: [], printCode: { _, context in - let value = try ContainerCodecJS.codecExpression(for: valueType, context: context) + let codec = try ContainerCodecJS.codecExpression(for: .dictionary(valueType), context: context) let resultVar = context.scope.variable("dictResult") - context.printer.write( - "const \(resultVar) = \(ContainerCodecJS.dictCodec)(\(value)).lift();" - ) + context.printer.write("const \(resultVar) = \(codec).lift();") return [resultVar] } ) @@ -2339,9 +2431,11 @@ struct IntrinsicJSFragment: Sendable { return IntrinsicJSFragment( parameters: [], printCode: { _, context in - let element = try ContainerCodecJS.codecExpression(for: wrappedType, context: context) + let codec = try ContainerCodecJS.codecExpression( + for: .nullable(wrappedType, kind), + context: context + ) let resultVar = context.scope.variable("optValue") - let codec = ContainerCodecJS.optionalCodecExpression(elementCodec: element, kind: kind) context.printer.write("const \(resultVar) = \(codec).lift();") return [resultVar] } @@ -2358,8 +2452,10 @@ struct IntrinsicJSFragment: Sendable { return IntrinsicJSFragment( parameters: ["value"], printCode: { arguments, context in - let element = try ContainerCodecJS.codecExpression(for: wrappedType, context: context) - let codec = ContainerCodecJS.optionalCodecExpression(elementCodec: element, kind: kind) + let codec = try ContainerCodecJS.codecExpression( + for: .nullable(wrappedType, kind), + context: context + ) context.printer.write("\(codec).lower(\(arguments[0]));") return [] } diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/JSIntrinsicRegistry.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/JSIntrinsicRegistry.swift index e3654e89f..5c6596bcf 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/JSIntrinsicRegistry.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/JSIntrinsicRegistry.swift @@ -7,6 +7,20 @@ final class JSIntrinsicRegistry { private var entries: [String: [String]] = [:] var classNamespaces: [String: [String]] = [:] + /// Maps a type name as carried by `BridgeType` (struct ABI name, class name, + /// enum name, ...) to the module that declares it, so generated identifiers + /// derived from type names can be module-qualified. + /// + /// The whole link output shares one JS scope, so two modules declaring a + /// same-named `@JS` type would otherwise mint the same identifier. + var typeOwnerModules: [String: String] = [:] + + /// Module-scope `{ lower, lift }` codec helpers, one per type shape, in + /// dependency order: a composed codec is appended after the codecs it is + /// built from, so the emitted `const`s can be evaluated top to bottom. + private var codecNameOrder: [String] = [] + private var codecBodies: [String: [String]] = [:] + var isEmpty: Bool { entries.isEmpty } @@ -18,9 +32,34 @@ final class JSIntrinsicRegistry { entries[name] = printer.lines } + /// Registers a named codec helper once per name. + /// + /// `build` may itself register the codecs this one is composed from; those + /// are appended first, which is what keeps the emitted declarations in a + /// valid evaluation order. + func registerNamedCodec(name: String, build: (CodeFragmentPrinter) throws -> Void) rethrows { + guard codecBodies[name] == nil else { return } + let printer = CodeFragmentPrinter() + try build(printer) + guard codecBodies[name] == nil else { return } + codecBodies[name] = printer.lines + codecNameOrder.append(name) + } + + var hasNamedCodecs: Bool { + !codecNameOrder.isEmpty + } + + func emitNamedCodecLines() -> [String] { + codecNameOrder.flatMap { codecBodies[$0] ?? [] } + } + func reset() { entries.removeAll() classNamespaces.removeAll() + typeOwnerModules.removeAll() + codecNameOrder.removeAll() + codecBodies.removeAll() } func emitLines() -> [String] { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/NamedCodecHelperTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/NamedCodecHelperTests.swift new file mode 100644 index 000000000..4e73e02d7 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/NamedCodecHelperTests.swift @@ -0,0 +1,105 @@ +import Testing + +@testable import BridgeJSLink +@testable import BridgeJSSkeleton + +/// Every type shape gets one module-scope `{ lower, lift }` helper, shared by the +/// container combinators' element positions and by the generic type-handle +/// registration table, and composed codecs are hoisted so that no call site +/// builds one. +@Suite struct NamedCodecHelperTests { + private func codecDeclarations(in js: String) -> [String] { + js.split(separator: "\n") + .map { $0.trimmingCharacters(in: .whitespaces) } + .filter { $0.hasPrefix("const \(ContainerCodecJS.namedCodecPrefix)") } + } + + @Test + func composedCodecsAreHoistedAndReusedByCallSites() throws { + let js = try linkSource( + """ + @JS func mirror(_ values: [String: Int?]) -> [String: Int?] { values } + @JS func mirrorAgain(_ values: [String: Int?]) -> [String: Int?] { values } + """ + ).js + + // Declared once, at module scope, out of the thunks. + #expect( + codecDeclarations(in: js) == [ + "const __bjs_codec_Optional_Int = __bjs_optionalCodec(__bjs_primitiveCodecs.Int);", + "const __bjs_codec_Dict_Optional_Int = __bjs_dictCodec(__bjs_codec_Optional_Int);", + ] + ) + // Call sites only read the helper; they never compose one. + #expect(js.contains("__bjs_codec_Dict_Optional_Int.lower(values);")) + #expect(js.contains("__bjs_codec_Dict_Optional_Int.lift();")) + let composedAtCallSite = js.contains("__bjs_dictCodec(__bjs_optionalCodec(") + #expect(!composedAtCallSite) + } + + @Test + func helperNamesAreQualifiedWithTheDeclaringModule() throws { + let js = try linkSource( + """ + @JS struct Point { + var x: Int + @JS init(x: Int) { self.x = x } + } + @JS func mirror(_ points: [Point]) -> [Point] { points } + """, + moduleName: "Core" + ).js + + #expect(js.contains("const __bjs_codec_Core_Point = {")) + #expect(js.contains("const __bjs_codec_Array_Core_Point = __bjs_arrayCodec(__bjs_codec_Core_Point);")) + } + + /// The type-table entry and the element position of a container must resolve + /// to the same helper, so a type's stack ABI is described exactly once. + @Test + func registrationTableReusesTheSameHelperAsElementPositions() throws { + let js = try linkSource( + """ + @JS struct Point { + var x: Int + @JS init(x: Int) { self.x = x } + } + @JS func mirror(_ points: [Point]) -> [Point] { points } + @JSClass struct Consumer { + @JSFunction func identity(_ value: T) throws(JSException) -> T + } + """, + moduleName: "Core" + ).js + + #expect(js.contains("const __bjs_codec_Core_Point = {")) + #expect(js.contains("const __bjs_codec_Array_Core_Point = __bjs_arrayCodec(__bjs_codec_Core_Point);")) + // One entry in the registration array, referencing the same helper. + let registrationArray = + js + .components(separatedBy: "bjs[\"bjs_Core_register_type_handles\"] = function(base, count) {") + .last + .map { $0.components(separatedBy: "];")[0] } + #expect(registrationArray?.contains("__bjs_codec_Core_Point,") == true) + // The struct's marshalling code is emitted once, in its helper factory. + #expect(js.components(separatedBy: "structHelpers.Point.lower(v);").count - 1 == 1) + } + + /// A string-backed raw value enum bridges exactly as `String`, so it shares + /// the string codec instead of minting a redundant helper. + @Test + func stringBackedRawValueEnumsShareTheStringCodec() throws { + let js = try linkSource( + """ + @JS enum Mode: String { + case light + case dark + } + @JS func mirror(_ modes: [Mode]) -> [Mode] { modes } + """ + ).js + + #expect(js.contains("const __bjs_codec_Array_String = __bjs_arrayCodec(__bjs_stringCodec);")) + #expect(!js.contains("__bjs_codec_TestModule_Mode")) + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js index c9c09bd97..fff8779ef 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js @@ -99,16 +99,6 @@ export async function createInstantiator(options, swift) { }, }; } - function __bjs_enumCodec(helper) { - return { - lower(value) { - i32Stack.push(helper.lower(value)); - }, - lift() { - return helper.lift(i32Stack.pop()); - }, - }; - } const __bjs_stringCodec = { lower: (v) => { @@ -347,6 +337,43 @@ export async function createInstantiator(options, swift) { return jsValue; } + const __bjs_codec_TestModule_PolygonReference = { + lower: (v) => { + ptrStack.push(v.pointer); + }, + lift: () => { + const ptr = ptrStack.pop(); + const obj = _exports['PolygonReference'].__construct(ptr); + return obj; + }, + }; + const __bjs_codec_Array_TestModule_PolygonReference = __bjs_arrayCodec(__bjs_codec_TestModule_PolygonReference); + const __bjs_codec_TestModule_InnerTag = { + lower: (v) => { + const caseId = enumHelpers.InnerTag.lower(v); + i32Stack.push(caseId); + }, + lift: () => { + const enumValue = enumHelpers.InnerTag.lift(i32Stack.pop()); + return enumValue; + }, + }; + const __bjs_codec_Optional_TestModule_InnerTag = __bjs_optionalCodec(__bjs_codec_TestModule_InnerTag); + const __bjs_codec_Array_Optional_TestModule_InnerTag = __bjs_arrayCodec(__bjs_codec_Optional_TestModule_InnerTag); + const __bjs_codec_TestModule_Surface = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + const __bjs_codec_Optional_TestModule_Surface = __bjs_optionalCodec(__bjs_codec_TestModule_Surface); + const __bjs_createInnerTagValuesHelpers = () => ({ lower: (value) => { const enumTag = value.tag; @@ -596,19 +623,7 @@ export async function createInstantiator(options, swift) { TestModule["bjs_produceOptionalCanvas"] = function bjs_produceOptionalCanvas() { try { let ret = imports.produceOptionalCanvas(); - const elemCodec = { - lower: (v) => { - const objId = swift.memory.retain(v); - i32Stack.push(objId); - }, - lift: () => { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - return obj; - }, - }; - __bjs_optionalCodec(elemCodec).lower(ret); + __bjs_codec_Optional_TestModule_Surface.lower(ret); } catch (error) { setException(error); } @@ -759,29 +774,9 @@ export async function createInstantiator(options, swift) { return optResult; }, polygonArray: function bjs_polygonArray(polygons) { - const elemCodec = { - lower: (v) => { - ptrStack.push(v.pointer); - }, - lift: () => { - const ptr = ptrStack.pop(); - const obj = PolygonReference.__construct(ptr); - return obj; - }, - }; - __bjs_arrayCodec(elemCodec).lower(polygons); + __bjs_codec_Array_TestModule_PolygonReference.lower(polygons); instance.exports.bjs_polygonArray(); - const elemCodec1 = { - lower: (v) => { - ptrStack.push(v.pointer); - }, - lift: () => { - const ptr = ptrStack.pop(); - const obj = PolygonReference.__construct(ptr); - return obj; - }, - }; - const arrayResult = __bjs_arrayCodec(elemCodec1).lift(); + const arrayResult = __bjs_codec_Array_TestModule_PolygonReference.lift(); return arrayResult; }, validatePolygon: function bjs_validatePolygon(polygon) { @@ -801,9 +796,9 @@ export async function createInstantiator(options, swift) { return TagReference.__construct(ret); }, roundtripTags: function bjs_roundtripTags(xs) { - __bjs_arrayCodec(__bjs_optionalCodec(__bjs_enumCodec(enumHelpers.InnerTag))).lower(xs); + __bjs_codec_Array_Optional_TestModule_InnerTag.lower(xs); instance.exports.bjs_roundtripTags(); - const arrayResult = __bjs_arrayCodec(__bjs_optionalCodec(__bjs_enumCodec(enumHelpers.InnerTag))).lift(); + const arrayResult = __bjs_codec_Array_Optional_TestModule_InnerTag.lift(); return arrayResult; }, describeUser: function bjs_describeUser(owner) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js index 86a84490e..e038620c1 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js @@ -106,16 +106,6 @@ export async function createInstantiator(options, swift) { }, }; } - function __bjs_enumCodec(helper) { - return { - lower(value) { - i32Stack.push(helper.lower(value)); - }, - lift() { - return helper.lift(i32Stack.pop()); - }, - }; - } const __bjs_stringCodec = { lower: (v) => { @@ -354,6 +344,114 @@ export async function createInstantiator(options, swift) { return jsValue; } + const __bjs_codec_Array_Int = __bjs_arrayCodec(__bjs_primitiveCodecs.Int); + const __bjs_codec_Array_String = __bjs_arrayCodec(__bjs_stringCodec); + const __bjs_codec_Array_Double = __bjs_arrayCodec(__bjs_primitiveCodecs.Double); + const __bjs_codec_Array_Bool = __bjs_arrayCodec(__bjs_primitiveCodecs.Bool); + const __bjs_codec_TestModule_Point = { + lower: (v) => { + structHelpers.Point.lower(v); + }, + lift: () => { + const struct = structHelpers.Point.lift(); + return struct; + }, + }; + const __bjs_codec_Array_TestModule_Point = __bjs_arrayCodec(__bjs_codec_TestModule_Point); + const __bjs_codec_TestModule_Direction = { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const caseId = i32Stack.pop(); + return caseId; + }, + }; + const __bjs_codec_Array_TestModule_Direction = __bjs_arrayCodec(__bjs_codec_TestModule_Direction); + const __bjs_codec_TestModule_Status = { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const rawValue = i32Stack.pop(); + return rawValue; + }, + }; + const __bjs_codec_Array_TestModule_Status = __bjs_arrayCodec(__bjs_codec_TestModule_Status); + const __bjs_codec_Surp = { + lower: (v) => { + ptrStack.push((v | 0)); + }, + lift: () => { + const pointer = ptrStack.pop(); + return pointer; + }, + }; + const __bjs_codec_Array_Surp = __bjs_arrayCodec(__bjs_codec_Surp); + const __bjs_codec_Sumrp = { + lower: (v) => { + ptrStack.push((v | 0)); + }, + lift: () => { + const pointer = ptrStack.pop(); + return pointer; + }, + }; + const __bjs_codec_Array_Sumrp = __bjs_arrayCodec(__bjs_codec_Sumrp); + const __bjs_codec_Sop = { + lower: (v) => { + ptrStack.push((v | 0)); + }, + lift: () => { + const pointer = ptrStack.pop(); + return pointer; + }, + }; + const __bjs_codec_Array_Sop = __bjs_arrayCodec(__bjs_codec_Sop); + const __bjs_codec_Optional_Int = __bjs_optionalCodec(__bjs_primitiveCodecs.Int); + const __bjs_codec_Array_Optional_Int = __bjs_arrayCodec(__bjs_codec_Optional_Int); + const __bjs_codec_Optional_String = __bjs_optionalCodec(__bjs_stringCodec); + const __bjs_codec_Array_Optional_String = __bjs_arrayCodec(__bjs_codec_Optional_String); + const __bjs_codec_Optional_Array_Int = __bjs_optionalCodec(__bjs_codec_Array_Int); + const __bjs_codec_Optional_TestModule_Point = __bjs_optionalCodec(__bjs_codec_TestModule_Point); + const __bjs_codec_Array_Optional_TestModule_Point = __bjs_arrayCodec(__bjs_codec_Optional_TestModule_Point); + const __bjs_codec_Optional_TestModule_Direction = __bjs_optionalCodec(__bjs_codec_TestModule_Direction); + const __bjs_codec_Array_Optional_TestModule_Direction = __bjs_arrayCodec(__bjs_codec_Optional_TestModule_Direction); + const __bjs_codec_Optional_TestModule_Status = __bjs_optionalCodec(__bjs_codec_TestModule_Status); + const __bjs_codec_Array_Optional_TestModule_Status = __bjs_arrayCodec(__bjs_codec_Optional_TestModule_Status); + const __bjs_codec_Array_Array_Int = __bjs_arrayCodec(__bjs_codec_Array_Int); + const __bjs_codec_Array_Array_String = __bjs_arrayCodec(__bjs_codec_Array_String); + const __bjs_codec_Array_Array_TestModule_Point = __bjs_arrayCodec(__bjs_codec_Array_TestModule_Point); + const __bjs_codec_TestModule_Item = { + lower: (v) => { + ptrStack.push(v.pointer); + }, + lift: () => { + const ptr = ptrStack.pop(); + const obj = _exports['Item'].__construct(ptr); + return obj; + }, + }; + const __bjs_codec_Array_TestModule_Item = __bjs_arrayCodec(__bjs_codec_TestModule_Item); + const __bjs_codec_Array_Array_TestModule_Item = __bjs_arrayCodec(__bjs_codec_Array_TestModule_Item); + const __bjs_codec_JSObject = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + const __bjs_codec_Array_JSObject = __bjs_arrayCodec(__bjs_codec_JSObject); + const __bjs_codec_Optional_JSObject = __bjs_optionalCodec(__bjs_codec_JSObject); + const __bjs_codec_Array_Optional_JSObject = __bjs_arrayCodec(__bjs_codec_Optional_JSObject); + const __bjs_codec_Array_Array_JSObject = __bjs_arrayCodec(__bjs_codec_Array_JSObject); + const __bjs_codec_Optional_Array_String = __bjs_optionalCodec(__bjs_codec_Array_String); + const __bjs_createPointHelpers = () => ({ lower: (value) => { f64Stack.push(value.x); @@ -576,7 +674,7 @@ export async function createInstantiator(options, swift) { } TestModule["bjs_importProcessNumbers"] = function bjs_importProcessNumbers() { try { - const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.Double).lift(); + const arrayResult = __bjs_codec_Array_Double.lift(); imports.importProcessNumbers(arrayResult); } catch (error) { setException(error); @@ -585,34 +683,34 @@ export async function createInstantiator(options, swift) { TestModule["bjs_importGetNumbers"] = function bjs_importGetNumbers() { try { let ret = imports.importGetNumbers(); - __bjs_arrayCodec(__bjs_primitiveCodecs.Double).lower(ret); + __bjs_codec_Array_Double.lower(ret); } catch (error) { setException(error); } } TestModule["bjs_importTransformNumbers"] = function bjs_importTransformNumbers() { try { - const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.Double).lift(); + const arrayResult = __bjs_codec_Array_Double.lift(); let ret = imports.importTransformNumbers(arrayResult); - __bjs_arrayCodec(__bjs_primitiveCodecs.Double).lower(ret); + __bjs_codec_Array_Double.lower(ret); } catch (error) { setException(error); } } TestModule["bjs_importProcessStrings"] = function bjs_importProcessStrings() { try { - const arrayResult = __bjs_arrayCodec(__bjs_stringCodec).lift(); + const arrayResult = __bjs_codec_Array_String.lift(); let ret = imports.importProcessStrings(arrayResult); - __bjs_arrayCodec(__bjs_stringCodec).lower(ret); + __bjs_codec_Array_String.lower(ret); } catch (error) { setException(error); } } TestModule["bjs_importProcessBooleans"] = function bjs_importProcessBooleans() { try { - const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.Bool).lift(); + const arrayResult = __bjs_codec_Array_Bool.lift(); let ret = imports.importProcessBooleans(arrayResult); - __bjs_arrayCodec(__bjs_primitiveCodecs.Bool).lower(ret); + __bjs_codec_Array_Bool.lower(ret); } catch (error) { setException(error); } @@ -695,19 +793,19 @@ export async function createInstantiator(options, swift) { } constructor(nums, strs) { - __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lower(nums); - __bjs_arrayCodec(__bjs_stringCodec).lower(strs); + __bjs_codec_Array_Int.lower(nums); + __bjs_codec_Array_String.lower(strs); const ret = instance.exports.bjs_MultiArrayContainer_init(); return MultiArrayContainer.__construct(ret); } get numbers() { instance.exports.bjs_MultiArrayContainer_numbers_get(this.pointer); - const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lift(); + const arrayResult = __bjs_codec_Array_Int.lift(); return arrayResult; } get strings() { instance.exports.bjs_MultiArrayContainer_strings_get(this.pointer); - const arrayResult = __bjs_arrayCodec(__bjs_stringCodec).lift(); + const arrayResult = __bjs_codec_Array_String.lift(); return arrayResult; } } @@ -716,90 +814,54 @@ export async function createInstantiator(options, swift) { const exports = { processIntArray: function bjs_processIntArray(values) { - __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lower(values); + __bjs_codec_Array_Int.lower(values); instance.exports.bjs_processIntArray(); - const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lift(); + const arrayResult = __bjs_codec_Array_Int.lift(); return arrayResult; }, processStringArray: function bjs_processStringArray(values) { - __bjs_arrayCodec(__bjs_stringCodec).lower(values); + __bjs_codec_Array_String.lower(values); instance.exports.bjs_processStringArray(); - const arrayResult = __bjs_arrayCodec(__bjs_stringCodec).lift(); + const arrayResult = __bjs_codec_Array_String.lift(); return arrayResult; }, processDoubleArray: function bjs_processDoubleArray(values) { - __bjs_arrayCodec(__bjs_primitiveCodecs.Double).lower(values); + __bjs_codec_Array_Double.lower(values); instance.exports.bjs_processDoubleArray(); - const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.Double).lift(); + const arrayResult = __bjs_codec_Array_Double.lift(); return arrayResult; }, processBoolArray: function bjs_processBoolArray(values) { - __bjs_arrayCodec(__bjs_primitiveCodecs.Bool).lower(values); + __bjs_codec_Array_Bool.lower(values); instance.exports.bjs_processBoolArray(); - const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.Bool).lift(); + const arrayResult = __bjs_codec_Array_Bool.lift(); return arrayResult; }, processPointArray: function bjs_processPointArray(points) { - __bjs_arrayCodec(structHelpers.Point).lower(points); + __bjs_codec_Array_TestModule_Point.lower(points); instance.exports.bjs_processPointArray(); - const arrayResult = __bjs_arrayCodec(structHelpers.Point).lift(); + const arrayResult = __bjs_codec_Array_TestModule_Point.lift(); return arrayResult; }, processDirectionArray: function bjs_processDirectionArray(directions) { - const elemCodec = { - lower: (v) => { - i32Stack.push((v | 0)); - }, - lift: () => { - const caseId = i32Stack.pop(); - return caseId; - }, - }; - __bjs_arrayCodec(elemCodec).lower(directions); + __bjs_codec_Array_TestModule_Direction.lower(directions); instance.exports.bjs_processDirectionArray(); - const elemCodec1 = { - lower: (v) => { - i32Stack.push((v | 0)); - }, - lift: () => { - const caseId = i32Stack.pop(); - return caseId; - }, - }; - const arrayResult = __bjs_arrayCodec(elemCodec1).lift(); + const arrayResult = __bjs_codec_Array_TestModule_Direction.lift(); return arrayResult; }, processStatusArray: function bjs_processStatusArray(statuses) { - const elemCodec = { - lower: (v) => { - i32Stack.push((v | 0)); - }, - lift: () => { - const rawValue = i32Stack.pop(); - return rawValue; - }, - }; - __bjs_arrayCodec(elemCodec).lower(statuses); + __bjs_codec_Array_TestModule_Status.lower(statuses); instance.exports.bjs_processStatusArray(); - const elemCodec1 = { - lower: (v) => { - i32Stack.push((v | 0)); - }, - lift: () => { - const rawValue = i32Stack.pop(); - return rawValue; - }, - }; - const arrayResult = __bjs_arrayCodec(elemCodec1).lift(); + const arrayResult = __bjs_codec_Array_TestModule_Status.lift(); return arrayResult; }, sumIntArray: function bjs_sumIntArray(values) { - __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lower(values); + __bjs_codec_Array_Int.lower(values); const ret = instance.exports.bjs_sumIntArray(); return ret; }, findFirstPoint: function bjs_findFirstPoint(points, matching) { - __bjs_arrayCodec(structHelpers.Point).lower(points); + __bjs_codec_Array_TestModule_Point.lower(points); const matchingBytes = textEncoder.encode(matching); const matchingId = swift.memory.retain(matchingBytes); instance.exports.bjs_findFirstPoint(matchingId, matchingBytes.length); @@ -807,318 +869,116 @@ export async function createInstantiator(options, swift) { return structValue; }, processUnsafeRawPointerArray: function bjs_processUnsafeRawPointerArray(values) { - const elemCodec = { - lower: (v) => { - ptrStack.push((v | 0)); - }, - lift: () => { - const pointer = ptrStack.pop(); - return pointer; - }, - }; - __bjs_arrayCodec(elemCodec).lower(values); + __bjs_codec_Array_Surp.lower(values); instance.exports.bjs_processUnsafeRawPointerArray(); - const elemCodec1 = { - lower: (v) => { - ptrStack.push((v | 0)); - }, - lift: () => { - const pointer = ptrStack.pop(); - return pointer; - }, - }; - const arrayResult = __bjs_arrayCodec(elemCodec1).lift(); + const arrayResult = __bjs_codec_Array_Surp.lift(); return arrayResult; }, processUnsafeMutableRawPointerArray: function bjs_processUnsafeMutableRawPointerArray(values) { - const elemCodec = { - lower: (v) => { - ptrStack.push((v | 0)); - }, - lift: () => { - const pointer = ptrStack.pop(); - return pointer; - }, - }; - __bjs_arrayCodec(elemCodec).lower(values); + __bjs_codec_Array_Sumrp.lower(values); instance.exports.bjs_processUnsafeMutableRawPointerArray(); - const elemCodec1 = { - lower: (v) => { - ptrStack.push((v | 0)); - }, - lift: () => { - const pointer = ptrStack.pop(); - return pointer; - }, - }; - const arrayResult = __bjs_arrayCodec(elemCodec1).lift(); + const arrayResult = __bjs_codec_Array_Sumrp.lift(); return arrayResult; }, processOpaquePointerArray: function bjs_processOpaquePointerArray(values) { - const elemCodec = { - lower: (v) => { - ptrStack.push((v | 0)); - }, - lift: () => { - const pointer = ptrStack.pop(); - return pointer; - }, - }; - __bjs_arrayCodec(elemCodec).lower(values); + __bjs_codec_Array_Sop.lower(values); instance.exports.bjs_processOpaquePointerArray(); - const elemCodec1 = { - lower: (v) => { - ptrStack.push((v | 0)); - }, - lift: () => { - const pointer = ptrStack.pop(); - return pointer; - }, - }; - const arrayResult = __bjs_arrayCodec(elemCodec1).lift(); + const arrayResult = __bjs_codec_Array_Sop.lift(); return arrayResult; }, processOptionalIntArray: function bjs_processOptionalIntArray(values) { - __bjs_arrayCodec(__bjs_optionalCodec(__bjs_primitiveCodecs.Int)).lower(values); + __bjs_codec_Array_Optional_Int.lower(values); instance.exports.bjs_processOptionalIntArray(); - const arrayResult = __bjs_arrayCodec(__bjs_optionalCodec(__bjs_primitiveCodecs.Int)).lift(); + const arrayResult = __bjs_codec_Array_Optional_Int.lift(); return arrayResult; }, processOptionalStringArray: function bjs_processOptionalStringArray(values) { - __bjs_arrayCodec(__bjs_optionalCodec(__bjs_stringCodec)).lower(values); + __bjs_codec_Array_Optional_String.lower(values); instance.exports.bjs_processOptionalStringArray(); - const arrayResult = __bjs_arrayCodec(__bjs_optionalCodec(__bjs_stringCodec)).lift(); + const arrayResult = __bjs_codec_Array_Optional_String.lift(); return arrayResult; }, processOptionalArray: function bjs_processOptionalArray(values) { - __bjs_optionalCodec(__bjs_arrayCodec(__bjs_primitiveCodecs.Int)).lower(values); + __bjs_codec_Optional_Array_Int.lower(values); instance.exports.bjs_processOptionalArray(); - const optValue = __bjs_optionalCodec(__bjs_arrayCodec(__bjs_primitiveCodecs.Int)).lift(); + const optValue = __bjs_codec_Optional_Array_Int.lift(); return optValue; }, processOptionalPointArray: function bjs_processOptionalPointArray(points) { - __bjs_arrayCodec(__bjs_optionalCodec(structHelpers.Point)).lower(points); + __bjs_codec_Array_Optional_TestModule_Point.lower(points); instance.exports.bjs_processOptionalPointArray(); - const arrayResult = __bjs_arrayCodec(__bjs_optionalCodec(structHelpers.Point)).lift(); + const arrayResult = __bjs_codec_Array_Optional_TestModule_Point.lift(); return arrayResult; }, processOptionalDirectionArray: function bjs_processOptionalDirectionArray(directions) { - const elemCodec = { - lower: (v) => { - i32Stack.push((v | 0)); - }, - lift: () => { - const caseId = i32Stack.pop(); - return caseId; - }, - }; - __bjs_arrayCodec(__bjs_optionalCodec(elemCodec)).lower(directions); + __bjs_codec_Array_Optional_TestModule_Direction.lower(directions); instance.exports.bjs_processOptionalDirectionArray(); - const elemCodec1 = { - lower: (v) => { - i32Stack.push((v | 0)); - }, - lift: () => { - const caseId = i32Stack.pop(); - return caseId; - }, - }; - const arrayResult = __bjs_arrayCodec(__bjs_optionalCodec(elemCodec1)).lift(); + const arrayResult = __bjs_codec_Array_Optional_TestModule_Direction.lift(); return arrayResult; }, processOptionalStatusArray: function bjs_processOptionalStatusArray(statuses) { - const elemCodec = { - lower: (v) => { - i32Stack.push((v | 0)); - }, - lift: () => { - const rawValue = i32Stack.pop(); - return rawValue; - }, - }; - __bjs_arrayCodec(__bjs_optionalCodec(elemCodec)).lower(statuses); + __bjs_codec_Array_Optional_TestModule_Status.lower(statuses); instance.exports.bjs_processOptionalStatusArray(); - const elemCodec1 = { - lower: (v) => { - i32Stack.push((v | 0)); - }, - lift: () => { - const rawValue = i32Stack.pop(); - return rawValue; - }, - }; - const arrayResult = __bjs_arrayCodec(__bjs_optionalCodec(elemCodec1)).lift(); + const arrayResult = __bjs_codec_Array_Optional_TestModule_Status.lift(); return arrayResult; }, processNestedIntArray: function bjs_processNestedIntArray(values) { - __bjs_arrayCodec(__bjs_arrayCodec(__bjs_primitiveCodecs.Int)).lower(values); + __bjs_codec_Array_Array_Int.lower(values); instance.exports.bjs_processNestedIntArray(); - const arrayResult = __bjs_arrayCodec(__bjs_arrayCodec(__bjs_primitiveCodecs.Int)).lift(); + const arrayResult = __bjs_codec_Array_Array_Int.lift(); return arrayResult; }, processNestedStringArray: function bjs_processNestedStringArray(values) { - __bjs_arrayCodec(__bjs_arrayCodec(__bjs_stringCodec)).lower(values); + __bjs_codec_Array_Array_String.lower(values); instance.exports.bjs_processNestedStringArray(); - const arrayResult = __bjs_arrayCodec(__bjs_arrayCodec(__bjs_stringCodec)).lift(); + const arrayResult = __bjs_codec_Array_Array_String.lift(); return arrayResult; }, processNestedPointArray: function bjs_processNestedPointArray(points) { - __bjs_arrayCodec(__bjs_arrayCodec(structHelpers.Point)).lower(points); + __bjs_codec_Array_Array_TestModule_Point.lower(points); instance.exports.bjs_processNestedPointArray(); - const arrayResult = __bjs_arrayCodec(__bjs_arrayCodec(structHelpers.Point)).lift(); + const arrayResult = __bjs_codec_Array_Array_TestModule_Point.lift(); return arrayResult; }, processItemArray: function bjs_processItemArray(items) { - const elemCodec = { - lower: (v) => { - ptrStack.push(v.pointer); - }, - lift: () => { - const ptr = ptrStack.pop(); - const obj = Item.__construct(ptr); - return obj; - }, - }; - __bjs_arrayCodec(elemCodec).lower(items); + __bjs_codec_Array_TestModule_Item.lower(items); instance.exports.bjs_processItemArray(); - const elemCodec1 = { - lower: (v) => { - ptrStack.push(v.pointer); - }, - lift: () => { - const ptr = ptrStack.pop(); - const obj = Item.__construct(ptr); - return obj; - }, - }; - const arrayResult = __bjs_arrayCodec(elemCodec1).lift(); + const arrayResult = __bjs_codec_Array_TestModule_Item.lift(); return arrayResult; }, processNestedItemArray: function bjs_processNestedItemArray(items) { - const elemCodec = { - lower: (v) => { - ptrStack.push(v.pointer); - }, - lift: () => { - const ptr = ptrStack.pop(); - const obj = Item.__construct(ptr); - return obj; - }, - }; - __bjs_arrayCodec(__bjs_arrayCodec(elemCodec)).lower(items); + __bjs_codec_Array_Array_TestModule_Item.lower(items); instance.exports.bjs_processNestedItemArray(); - const elemCodec1 = { - lower: (v) => { - ptrStack.push(v.pointer); - }, - lift: () => { - const ptr = ptrStack.pop(); - const obj = Item.__construct(ptr); - return obj; - }, - }; - const arrayResult = __bjs_arrayCodec(__bjs_arrayCodec(elemCodec1)).lift(); + const arrayResult = __bjs_codec_Array_Array_TestModule_Item.lift(); return arrayResult; }, processJSObjectArray: function bjs_processJSObjectArray(objects) { - const elemCodec = { - lower: (v) => { - const objId = swift.memory.retain(v); - i32Stack.push(objId); - }, - lift: () => { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - return obj; - }, - }; - __bjs_arrayCodec(elemCodec).lower(objects); + __bjs_codec_Array_JSObject.lower(objects); instance.exports.bjs_processJSObjectArray(); - const elemCodec1 = { - lower: (v) => { - const objId = swift.memory.retain(v); - i32Stack.push(objId); - }, - lift: () => { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - return obj; - }, - }; - const arrayResult = __bjs_arrayCodec(elemCodec1).lift(); + const arrayResult = __bjs_codec_Array_JSObject.lift(); return arrayResult; }, processOptionalJSObjectArray: function bjs_processOptionalJSObjectArray(objects) { - const elemCodec = { - lower: (v) => { - const objId = swift.memory.retain(v); - i32Stack.push(objId); - }, - lift: () => { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - return obj; - }, - }; - __bjs_arrayCodec(__bjs_optionalCodec(elemCodec)).lower(objects); + __bjs_codec_Array_Optional_JSObject.lower(objects); instance.exports.bjs_processOptionalJSObjectArray(); - const elemCodec1 = { - lower: (v) => { - const objId = swift.memory.retain(v); - i32Stack.push(objId); - }, - lift: () => { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - return obj; - }, - }; - const arrayResult = __bjs_arrayCodec(__bjs_optionalCodec(elemCodec1)).lift(); + const arrayResult = __bjs_codec_Array_Optional_JSObject.lift(); return arrayResult; }, processNestedJSObjectArray: function bjs_processNestedJSObjectArray(objects) { - const elemCodec = { - lower: (v) => { - const objId = swift.memory.retain(v); - i32Stack.push(objId); - }, - lift: () => { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - return obj; - }, - }; - __bjs_arrayCodec(__bjs_arrayCodec(elemCodec)).lower(objects); + __bjs_codec_Array_Array_JSObject.lower(objects); instance.exports.bjs_processNestedJSObjectArray(); - const elemCodec1 = { - lower: (v) => { - const objId = swift.memory.retain(v); - i32Stack.push(objId); - }, - lift: () => { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - return obj; - }, - }; - const arrayResult = __bjs_arrayCodec(__bjs_arrayCodec(elemCodec1)).lift(); + const arrayResult = __bjs_codec_Array_Array_JSObject.lift(); return arrayResult; }, multiArrayParams: function bjs_multiArrayParams(nums, strs) { - __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lower(nums); - __bjs_arrayCodec(__bjs_stringCodec).lower(strs); + __bjs_codec_Array_Int.lower(nums); + __bjs_codec_Array_String.lower(strs); const ret = instance.exports.bjs_multiArrayParams(); return ret; }, multiOptionalArrayParams: function bjs_multiOptionalArrayParams(a, b) { - __bjs_optionalCodec(__bjs_arrayCodec(__bjs_primitiveCodecs.Int)).lower(a); - __bjs_optionalCodec(__bjs_arrayCodec(__bjs_stringCodec)).lower(b); + __bjs_codec_Optional_Array_Int.lower(a); + __bjs_codec_Optional_Array_String.lower(b); const ret = instance.exports.bjs_multiOptionalArrayParams(); return ret; }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js index 4b3e0c3ed..7bd19602d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js @@ -103,16 +103,6 @@ export async function createInstantiator(options, swift) { }, }; } - function __bjs_enumCodec(helper) { - return { - lower(value) { - i32Stack.push(helper.lower(value)); - }, - lift() { - return helper.lift(i32Stack.pop()); - }, - }; - } const __bjs_stringCodec = { lower: (v) => { @@ -351,6 +341,30 @@ export async function createInstantiator(options, swift) { return jsValue; } + const __bjs_codec_TestModule_AsyncPoint = { + lower: (v) => { + structHelpers.AsyncPoint.lower(v); + }, + lift: () => { + const struct = structHelpers.AsyncPoint.lift(); + return struct; + }, + }; + const __bjs_codec_Optional_TestModule_AsyncPoint = __bjs_optionalCodec(__bjs_codec_TestModule_AsyncPoint); + const __bjs_codec_Array_TestModule_AsyncPoint = __bjs_arrayCodec(__bjs_codec_TestModule_AsyncPoint); + const __bjs_codec_TestModule_AsyncDirection = { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const caseId = i32Stack.pop(); + return caseId; + }, + }; + const __bjs_codec_Array_TestModule_AsyncDirection = __bjs_arrayCodec(__bjs_codec_TestModule_AsyncDirection); + const __bjs_codec_Dict_TestModule_AsyncPoint = __bjs_dictCodec(__bjs_codec_TestModule_AsyncPoint); + const __bjs_codec_Dict_TestModule_AsyncDirection = __bjs_dictCodec(__bjs_codec_TestModule_AsyncDirection); + const __bjs_createAsyncPointHelpers = () => ({ lower: (value) => { i32Stack.push((value.x | 0)); @@ -563,7 +577,7 @@ export async function createInstantiator(options, swift) { } bjs["promise_resolve_TestModule_Sa10AsyncPointV"] = function(promise) { try { - const arrayResult = __bjs_arrayCodec(structHelpers.AsyncPoint).lift(); + const arrayResult = __bjs_codec_Array_TestModule_AsyncPoint.lift(); swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(arrayResult); } catch (error) { setException(error); @@ -571,16 +585,7 @@ export async function createInstantiator(options, swift) { } bjs["promise_resolve_TestModule_Sa14AsyncDirectionO"] = function(promise) { try { - const elemCodec = { - lower: (v) => { - i32Stack.push((v | 0)); - }, - lift: () => { - const caseId = i32Stack.pop(); - return caseId; - }, - }; - const arrayResult = __bjs_arrayCodec(elemCodec).lift(); + const arrayResult = __bjs_codec_Array_TestModule_AsyncDirection.lift(); swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(arrayResult); } catch (error) { setException(error); @@ -588,7 +593,7 @@ export async function createInstantiator(options, swift) { } bjs["promise_resolve_TestModule_SD10AsyncPointV"] = function(promise) { try { - const dictResult = __bjs_dictCodec(structHelpers.AsyncPoint).lift(); + const dictResult = __bjs_codec_Dict_TestModule_AsyncPoint.lift(); swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(dictResult); } catch (error) { setException(error); @@ -596,16 +601,7 @@ export async function createInstantiator(options, swift) { } bjs["promise_resolve_TestModule_SD14AsyncDirectionO"] = function(promise) { try { - const elemCodec = { - lower: (v) => { - i32Stack.push((v | 0)); - }, - lift: () => { - const caseId = i32Stack.pop(); - return caseId; - }, - }; - const dictResult = __bjs_dictCodec(elemCodec).lift(); + const dictResult = __bjs_codec_Dict_TestModule_AsyncDirection.lift(); swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(dictResult); } catch (error) { setException(error); @@ -850,53 +846,35 @@ export async function createInstantiator(options, swift) { return ret1; }, asyncRoundTripOptionalStruct: function bjs_asyncRoundTripOptionalStruct(v) { - __bjs_optionalCodec(structHelpers.AsyncPoint).lower(v); + __bjs_codec_Optional_TestModule_AsyncPoint.lower(v); const ret = instance.exports.bjs_asyncRoundTripOptionalStruct(); const ret1 = swift.memory.getObject(ret); swift.memory.release(ret); return ret1; }, asyncRoundTripStructArray: function bjs_asyncRoundTripStructArray(v) { - __bjs_arrayCodec(structHelpers.AsyncPoint).lower(v); + __bjs_codec_Array_TestModule_AsyncPoint.lower(v); const ret = instance.exports.bjs_asyncRoundTripStructArray(); const ret1 = swift.memory.getObject(ret); swift.memory.release(ret); return ret1; }, asyncRoundTripEnumArray: function bjs_asyncRoundTripEnumArray(v) { - const elemCodec = { - lower: (v) => { - i32Stack.push((v | 0)); - }, - lift: () => { - const caseId = i32Stack.pop(); - return caseId; - }, - }; - __bjs_arrayCodec(elemCodec).lower(v); + __bjs_codec_Array_TestModule_AsyncDirection.lower(v); const ret = instance.exports.bjs_asyncRoundTripEnumArray(); const ret1 = swift.memory.getObject(ret); swift.memory.release(ret); return ret1; }, asyncRoundTripStructDictionary: function bjs_asyncRoundTripStructDictionary(v) { - __bjs_dictCodec(structHelpers.AsyncPoint).lower(v); + __bjs_codec_Dict_TestModule_AsyncPoint.lower(v); const ret = instance.exports.bjs_asyncRoundTripStructDictionary(); const ret1 = swift.memory.getObject(ret); swift.memory.release(ret); return ret1; }, asyncRoundTripEnumDictionary: function bjs_asyncRoundTripEnumDictionary(v) { - const elemCodec = { - lower: (v) => { - i32Stack.push((v | 0)); - }, - lift: () => { - const caseId = i32Stack.pop(); - return caseId; - }, - }; - __bjs_dictCodec(elemCodec).lower(v); + __bjs_codec_Dict_TestModule_AsyncDirection.lower(v); const ret = instance.exports.bjs_asyncRoundTripEnumDictionary(); const ret1 = swift.memory.getObject(ret); swift.memory.release(ret); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js index ac3a508da..ef00bad23 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js @@ -99,16 +99,6 @@ export async function createInstantiator(options, swift) { }, }; } - function __bjs_enumCodec(helper) { - return { - lower(value) { - i32Stack.push(helper.lower(value)); - }, - lift() { - return helper.lift(i32Stack.pop()); - }, - }; - } const __bjs_stringCodec = { lower: (v) => { @@ -347,6 +337,21 @@ export async function createInstantiator(options, swift) { return jsValue; } + const __bjs_codec_TestModule_Config = { + lower: (v) => { + structHelpers.Config.lower(v); + }, + lift: () => { + const struct = structHelpers.Config.lift(); + return struct; + }, + }; + const __bjs_codec_Optional_TestModule_Config = __bjs_optionalCodec(__bjs_codec_TestModule_Config); + const __bjs_codec_Array_Int = __bjs_arrayCodec(__bjs_primitiveCodecs.Int); + const __bjs_codec_Array_String = __bjs_arrayCodec(__bjs_stringCodec); + const __bjs_codec_Array_Double = __bjs_arrayCodec(__bjs_primitiveCodecs.Double); + const __bjs_codec_Array_Bool = __bjs_arrayCodec(__bjs_primitiveCodecs.Bool); + const __bjs_createConfigHelpers = () => ({ lower: (value) => { const bytes = textEncoder.encode(value.name); @@ -847,51 +852,51 @@ export async function createInstantiator(options, swift) { return EmptyGreeter.__construct(ret); }, testOptionalStructDefault: function bjs_testOptionalStructDefault(point = null) { - __bjs_optionalCodec(structHelpers.Config).lower(point); + __bjs_codec_Optional_TestModule_Config.lower(point); instance.exports.bjs_testOptionalStructDefault(); - const optValue = __bjs_optionalCodec(structHelpers.Config).lift(); + const optValue = __bjs_codec_Optional_TestModule_Config.lift(); return optValue; }, testOptionalStructWithValueDefault: function bjs_testOptionalStructWithValueDefault(point = { name: "default", value: 42, enabled: true }) { - __bjs_optionalCodec(structHelpers.Config).lower(point); + __bjs_codec_Optional_TestModule_Config.lower(point); instance.exports.bjs_testOptionalStructWithValueDefault(); - const optValue = __bjs_optionalCodec(structHelpers.Config).lift(); + const optValue = __bjs_codec_Optional_TestModule_Config.lift(); return optValue; }, testIntArrayDefault: function bjs_testIntArrayDefault(values = [1, 2, 3]) { - __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lower(values); + __bjs_codec_Array_Int.lower(values); instance.exports.bjs_testIntArrayDefault(); - const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lift(); + const arrayResult = __bjs_codec_Array_Int.lift(); return arrayResult; }, testStringArrayDefault: function bjs_testStringArrayDefault(names = ["a", "b", "c"]) { - __bjs_arrayCodec(__bjs_stringCodec).lower(names); + __bjs_codec_Array_String.lower(names); instance.exports.bjs_testStringArrayDefault(); - const arrayResult = __bjs_arrayCodec(__bjs_stringCodec).lift(); + const arrayResult = __bjs_codec_Array_String.lift(); return arrayResult; }, testDoubleArrayDefault: function bjs_testDoubleArrayDefault(values = [1.5, 2.5, 3.5]) { - __bjs_arrayCodec(__bjs_primitiveCodecs.Double).lower(values); + __bjs_codec_Array_Double.lower(values); instance.exports.bjs_testDoubleArrayDefault(); - const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.Double).lift(); + const arrayResult = __bjs_codec_Array_Double.lift(); return arrayResult; }, testBoolArrayDefault: function bjs_testBoolArrayDefault(flags = [true, false, true]) { - __bjs_arrayCodec(__bjs_primitiveCodecs.Bool).lower(flags); + __bjs_codec_Array_Bool.lower(flags); instance.exports.bjs_testBoolArrayDefault(); - const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.Bool).lift(); + const arrayResult = __bjs_codec_Array_Bool.lift(); return arrayResult; }, testEmptyArrayDefault: function bjs_testEmptyArrayDefault(items = []) { - __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lower(items); + __bjs_codec_Array_Int.lower(items); instance.exports.bjs_testEmptyArrayDefault(); - const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lift(); + const arrayResult = __bjs_codec_Array_Int.lift(); return arrayResult; }, testMixedWithArrayDefault: function bjs_testMixedWithArrayDefault(name = "test", values = [10, 20, 30], enabled = true) { const nameBytes = textEncoder.encode(name); const nameId = swift.memory.retain(nameBytes); - __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lower(values); + __bjs_codec_Array_Int.lower(values); instance.exports.bjs_testMixedWithArrayDefault(nameId, nameBytes.length, enabled); const ret = tmpRetString; tmpRetString = undefined; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js index 2ddf3e217..74d9e7e59 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js @@ -93,16 +93,6 @@ export async function createInstantiator(options, swift) { }, }; } - function __bjs_enumCodec(helper) { - return { - lower(value) { - i32Stack.push(helper.lower(value)); - }, - lift() { - return helper.lift(i32Stack.pop()); - }, - }; - } const __bjs_stringCodec = { lower: (v) => { @@ -341,16 +331,38 @@ export async function createInstantiator(options, swift) { return jsValue; } + const __bjs_codec_Dict_Int = __bjs_dictCodec(__bjs_primitiveCodecs.Int); + const __bjs_codec_Dict_String = __bjs_dictCodec(__bjs_stringCodec); + const __bjs_codec_Optional_Dict_String = __bjs_optionalCodec(__bjs_codec_Dict_String); + const __bjs_codec_Array_Int = __bjs_arrayCodec(__bjs_primitiveCodecs.Int); + const __bjs_codec_Dict_Array_Int = __bjs_dictCodec(__bjs_codec_Array_Int); + const __bjs_codec_TestModule_Box = { + lower: (v) => { + ptrStack.push(v.pointer); + }, + lift: () => { + const ptr = ptrStack.pop(); + const obj = _exports['Box'].__construct(ptr); + return obj; + }, + }; + const __bjs_codec_Dict_TestModule_Box = __bjs_dictCodec(__bjs_codec_TestModule_Box); + const __bjs_codec_Optional_TestModule_Box = __bjs_optionalCodec(__bjs_codec_TestModule_Box); + const __bjs_codec_Dict_Optional_TestModule_Box = __bjs_dictCodec(__bjs_codec_Optional_TestModule_Box); + const __bjs_codec_Dict_Double = __bjs_dictCodec(__bjs_primitiveCodecs.Double); + const __bjs_codec_Optional_Int = __bjs_optionalCodec(__bjs_primitiveCodecs.Int); + const __bjs_codec_Dict_Optional_Int = __bjs_dictCodec(__bjs_codec_Optional_Int); + const __bjs_createCountersHelpers = () => ({ lower: (value) => { const bytes = textEncoder.encode(value.name); const id = swift.memory.retain(bytes); i32Stack.push(bytes.length); i32Stack.push(id); - __bjs_dictCodec(__bjs_optionalCodec(__bjs_primitiveCodecs.Int)).lower(value.counts); + __bjs_codec_Dict_Optional_Int.lower(value.counts); }, lift: () => { - const dictResult = __bjs_dictCodec(__bjs_optionalCodec(__bjs_primitiveCodecs.Int)).lift(); + const dictResult = __bjs_codec_Dict_Optional_Int.lift(); const string = strStack.pop(); return { name: string, counts: dictResult }; } @@ -548,9 +560,9 @@ export async function createInstantiator(options, swift) { const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; TestModule["bjs_importMirrorDictionary"] = function bjs_importMirrorDictionary() { try { - const dictResult = __bjs_dictCodec(__bjs_primitiveCodecs.Double).lift(); + const dictResult = __bjs_codec_Dict_Double.lift(); let ret = imports.importMirrorDictionary(dictResult); - __bjs_dictCodec(__bjs_primitiveCodecs.Double).lower(ret); + __bjs_codec_Dict_Double.lower(ret); } catch (error) { setException(error); } @@ -632,73 +644,33 @@ export async function createInstantiator(options, swift) { const exports = { mirrorDictionary: function bjs_mirrorDictionary(values) { - __bjs_dictCodec(__bjs_primitiveCodecs.Int).lower(values); + __bjs_codec_Dict_Int.lower(values); instance.exports.bjs_mirrorDictionary(); - const dictResult = __bjs_dictCodec(__bjs_primitiveCodecs.Int).lift(); + const dictResult = __bjs_codec_Dict_Int.lift(); return dictResult; }, optionalDictionary: function bjs_optionalDictionary(values) { - __bjs_optionalCodec(__bjs_dictCodec(__bjs_stringCodec)).lower(values); + __bjs_codec_Optional_Dict_String.lower(values); instance.exports.bjs_optionalDictionary(); - const optValue = __bjs_optionalCodec(__bjs_dictCodec(__bjs_stringCodec)).lift(); + const optValue = __bjs_codec_Optional_Dict_String.lift(); return optValue; }, nestedDictionary: function bjs_nestedDictionary(values) { - __bjs_dictCodec(__bjs_arrayCodec(__bjs_primitiveCodecs.Int)).lower(values); + __bjs_codec_Dict_Array_Int.lower(values); instance.exports.bjs_nestedDictionary(); - const dictResult = __bjs_dictCodec(__bjs_arrayCodec(__bjs_primitiveCodecs.Int)).lift(); + const dictResult = __bjs_codec_Dict_Array_Int.lift(); return dictResult; }, boxDictionary: function bjs_boxDictionary(boxes) { - const elemCodec = { - lower: (v) => { - ptrStack.push(v.pointer); - }, - lift: () => { - const ptr = ptrStack.pop(); - const obj = Box.__construct(ptr); - return obj; - }, - }; - __bjs_dictCodec(elemCodec).lower(boxes); + __bjs_codec_Dict_TestModule_Box.lower(boxes); instance.exports.bjs_boxDictionary(); - const elemCodec1 = { - lower: (v) => { - ptrStack.push(v.pointer); - }, - lift: () => { - const ptr = ptrStack.pop(); - const obj = Box.__construct(ptr); - return obj; - }, - }; - const dictResult = __bjs_dictCodec(elemCodec1).lift(); + const dictResult = __bjs_codec_Dict_TestModule_Box.lift(); return dictResult; }, optionalBoxDictionary: function bjs_optionalBoxDictionary(boxes) { - const elemCodec = { - lower: (v) => { - ptrStack.push(v.pointer); - }, - lift: () => { - const ptr = ptrStack.pop(); - const obj = Box.__construct(ptr); - return obj; - }, - }; - __bjs_dictCodec(__bjs_optionalCodec(elemCodec)).lower(boxes); + __bjs_codec_Dict_Optional_TestModule_Box.lower(boxes); instance.exports.bjs_optionalBoxDictionary(); - const elemCodec1 = { - lower: (v) => { - ptrStack.push(v.pointer); - }, - lift: () => { - const ptr = ptrStack.pop(); - const obj = Box.__construct(ptr); - return obj; - }, - }; - const dictResult = __bjs_dictCodec(__bjs_optionalCodec(elemCodec1)).lift(); + const dictResult = __bjs_codec_Dict_Optional_TestModule_Box.lift(); return dictResult; }, roundtripCounters: function bjs_roundtripCounters(counters) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js index b98b2af7e..eef5cdf30 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js @@ -174,16 +174,6 @@ export async function createInstantiator(options, swift) { }, }; } - function __bjs_enumCodec(helper) { - return { - lower(value) { - i32Stack.push(helper.lower(value)); - }, - lift() { - return helper.lift(i32Stack.pop()); - }, - }; - } const __bjs_stringCodec = { lower: (v) => { @@ -422,6 +412,77 @@ export async function createInstantiator(options, swift) { return jsValue; } + const __bjs_codec_Optional_String = __bjs_optionalCodec(__bjs_stringCodec); + const __bjs_codec_Optional_Bool = __bjs_optionalCodec(__bjs_primitiveCodecs.Bool); + const __bjs_codec_Optional_Int = __bjs_optionalCodec(__bjs_primitiveCodecs.Int); + const __bjs_codec_TestModule_Precision = { + lower: (v) => { + f32Stack.push(Math.fround(v)); + }, + lift: () => { + const rawValue = f32Stack.pop(); + return rawValue; + }, + }; + const __bjs_codec_Optional_TestModule_Precision = __bjs_optionalCodec(__bjs_codec_TestModule_Precision); + const __bjs_codec_TestModule_CardinalDirection = { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const caseId = i32Stack.pop(); + return caseId; + }, + }; + const __bjs_codec_Optional_TestModule_CardinalDirection = __bjs_optionalCodec(__bjs_codec_TestModule_CardinalDirection); + const __bjs_codec_Array_Int = __bjs_arrayCodec(__bjs_primitiveCodecs.Int); + const __bjs_codec_TestModule_Point = { + lower: (v) => { + structHelpers.Point.lower(v); + }, + lift: () => { + const struct = structHelpers.Point.lift(); + return struct; + }, + }; + const __bjs_codec_Optional_TestModule_Point = __bjs_optionalCodec(__bjs_codec_TestModule_Point); + const __bjs_codec_TestModule_User = { + lower: (v) => { + ptrStack.push(v.pointer); + }, + lift: () => { + const ptr = ptrStack.pop(); + const obj = _exports['User'].__construct(ptr); + return obj; + }, + }; + const __bjs_codec_Optional_TestModule_User = __bjs_optionalCodec(__bjs_codec_TestModule_User); + const __bjs_codec_JSObject = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + const __bjs_codec_Optional_JSObject = __bjs_optionalCodec(__bjs_codec_JSObject); + const __bjs_codec_TestModule_APIResult = { + lower: (v) => { + const caseId = enumHelpers.APIResult.lower(v); + i32Stack.push(caseId); + }, + lift: () => { + const enumValue = enumHelpers.APIResult.lift(i32Stack.pop()); + return enumValue; + }, + }; + const __bjs_codec_Optional_TestModule_APIResult = __bjs_optionalCodec(__bjs_codec_TestModule_APIResult); + const __bjs_codec_Optional_Array_Int = __bjs_optionalCodec(__bjs_codec_Array_Int); + const __bjs_createPointHelpers = () => ({ lower: (value) => { f64Stack.push(value.x); @@ -692,18 +753,18 @@ export async function createInstantiator(options, swift) { const enumTag = value.tag; switch (enumTag) { case APIOptionalResultValues.Tag.Success: { - __bjs_optionalCodec(__bjs_stringCodec).lower(value.param0); + __bjs_codec_Optional_String.lower(value.param0); return APIOptionalResultValues.Tag.Success; } case APIOptionalResultValues.Tag.Failure: { - __bjs_optionalCodec(__bjs_primitiveCodecs.Bool).lower(value.param1); - __bjs_optionalCodec(__bjs_primitiveCodecs.Int).lower(value.param0); + __bjs_codec_Optional_Bool.lower(value.param1); + __bjs_codec_Optional_Int.lower(value.param0); return APIOptionalResultValues.Tag.Failure; } case APIOptionalResultValues.Tag.Status: { - __bjs_optionalCodec(__bjs_stringCodec).lower(value.param2); - __bjs_optionalCodec(__bjs_primitiveCodecs.Int).lower(value.param1); - __bjs_optionalCodec(__bjs_primitiveCodecs.Bool).lower(value.param0); + __bjs_codec_Optional_String.lower(value.param2); + __bjs_codec_Optional_Int.lower(value.param1); + __bjs_codec_Optional_Bool.lower(value.param0); return APIOptionalResultValues.Tag.Status; } default: throw new Error("Unknown APIOptionalResultValues tag: " + String(enumTag)); @@ -713,18 +774,18 @@ export async function createInstantiator(options, swift) { tag = tag | 0; switch (tag) { case APIOptionalResultValues.Tag.Success: { - const optValue = __bjs_optionalCodec(__bjs_stringCodec).lift(); + const optValue = __bjs_codec_Optional_String.lift(); return { tag: APIOptionalResultValues.Tag.Success, param0: optValue }; } case APIOptionalResultValues.Tag.Failure: { - const optValue = __bjs_optionalCodec(__bjs_primitiveCodecs.Bool).lift(); - const optValue1 = __bjs_optionalCodec(__bjs_primitiveCodecs.Int).lift(); + const optValue = __bjs_codec_Optional_Bool.lift(); + const optValue1 = __bjs_codec_Optional_Int.lift(); return { tag: APIOptionalResultValues.Tag.Failure, param0: optValue1, param1: optValue }; } case APIOptionalResultValues.Tag.Status: { - const optValue = __bjs_optionalCodec(__bjs_stringCodec).lift(); - const optValue1 = __bjs_optionalCodec(__bjs_primitiveCodecs.Int).lift(); - const optValue2 = __bjs_optionalCodec(__bjs_primitiveCodecs.Bool).lift(); + const optValue = __bjs_codec_Optional_String.lift(); + const optValue1 = __bjs_codec_Optional_Int.lift(); + const optValue2 = __bjs_codec_Optional_Bool.lift(); return { tag: APIOptionalResultValues.Tag.Status, param0: optValue2, param1: optValue1, param2: optValue }; } default: throw new Error("Unknown APIOptionalResultValues tag returned from Swift: " + String(tag)); @@ -744,29 +805,11 @@ export async function createInstantiator(options, swift) { return TypedPayloadResultValues.Tag.Direction; } case TypedPayloadResultValues.Tag.OptPrecision: { - const elemCodec = { - lower: (v) => { - f32Stack.push(Math.fround(v)); - }, - lift: () => { - const rawValue = f32Stack.pop(); - return rawValue; - }, - }; - __bjs_optionalCodec(elemCodec).lower(value.param0); + __bjs_codec_Optional_TestModule_Precision.lower(value.param0); return TypedPayloadResultValues.Tag.OptPrecision; } case TypedPayloadResultValues.Tag.OptDirection: { - const elemCodec = { - lower: (v) => { - i32Stack.push((v | 0)); - }, - lift: () => { - const caseId = i32Stack.pop(); - return caseId; - }, - }; - __bjs_optionalCodec(elemCodec).lower(value.param0); + __bjs_codec_Optional_TestModule_CardinalDirection.lower(value.param0); return TypedPayloadResultValues.Tag.OptDirection; } case TypedPayloadResultValues.Tag.Empty: { @@ -787,29 +830,11 @@ export async function createInstantiator(options, swift) { return { tag: TypedPayloadResultValues.Tag.Direction, param0: caseId }; } case TypedPayloadResultValues.Tag.OptPrecision: { - const elemCodec = { - lower: (v) => { - f32Stack.push(Math.fround(v)); - }, - lift: () => { - const rawValue = f32Stack.pop(); - return rawValue; - }, - }; - const optValue = __bjs_optionalCodec(elemCodec).lift(); + const optValue = __bjs_codec_Optional_TestModule_Precision.lift(); return { tag: TypedPayloadResultValues.Tag.OptPrecision, param0: optValue }; } case TypedPayloadResultValues.Tag.OptDirection: { - const elemCodec = { - lower: (v) => { - i32Stack.push((v | 0)); - }, - lift: () => { - const caseId = i32Stack.pop(); - return caseId; - }, - }; - const optValue = __bjs_optionalCodec(elemCodec).lift(); + const optValue = __bjs_codec_Optional_TestModule_CardinalDirection.lift(); return { tag: TypedPayloadResultValues.Tag.OptDirection, param0: optValue }; } case TypedPayloadResultValues.Tag.Empty: return { tag: TypedPayloadResultValues.Tag.Empty }; @@ -840,7 +865,7 @@ export async function createInstantiator(options, swift) { return AllTypesResultValues.Tag.NestedEnum; } case AllTypesResultValues.Tag.ArrayPayload: { - __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lower(value.param0); + __bjs_codec_Array_Int.lower(value.param0); return AllTypesResultValues.Tag.ArrayPayload; } case AllTypesResultValues.Tag.Empty: { @@ -872,7 +897,7 @@ export async function createInstantiator(options, swift) { return { tag: AllTypesResultValues.Tag.NestedEnum, param0: enumValue }; } case AllTypesResultValues.Tag.ArrayPayload: { - const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lift(); + const arrayResult = __bjs_codec_Array_Int.lift(); return { tag: AllTypesResultValues.Tag.ArrayPayload, param0: arrayResult }; } case AllTypesResultValues.Tag.Empty: return { tag: AllTypesResultValues.Tag.Empty }; @@ -885,45 +910,23 @@ export async function createInstantiator(options, swift) { const enumTag = value.tag; switch (enumTag) { case OptionalAllTypesResultValues.Tag.OptStruct: { - __bjs_optionalCodec(structHelpers.Point).lower(value.param0); + __bjs_codec_Optional_TestModule_Point.lower(value.param0); return OptionalAllTypesResultValues.Tag.OptStruct; } case OptionalAllTypesResultValues.Tag.OptClass: { - const elemCodec = { - lower: (v) => { - ptrStack.push(v.pointer); - }, - lift: () => { - const ptr = ptrStack.pop(); - const obj = _exports['User'].__construct(ptr); - return obj; - }, - }; - __bjs_optionalCodec(elemCodec).lower(value.param0); + __bjs_codec_Optional_TestModule_User.lower(value.param0); return OptionalAllTypesResultValues.Tag.OptClass; } case OptionalAllTypesResultValues.Tag.OptJSObject: { - const elemCodec = { - lower: (v) => { - const objId = swift.memory.retain(v); - i32Stack.push(objId); - }, - lift: () => { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - return obj; - }, - }; - __bjs_optionalCodec(elemCodec).lower(value.param0); + __bjs_codec_Optional_JSObject.lower(value.param0); return OptionalAllTypesResultValues.Tag.OptJSObject; } case OptionalAllTypesResultValues.Tag.OptNestedEnum: { - __bjs_optionalCodec(__bjs_enumCodec(enumHelpers.APIResult)).lower(value.param0); + __bjs_codec_Optional_TestModule_APIResult.lower(value.param0); return OptionalAllTypesResultValues.Tag.OptNestedEnum; } case OptionalAllTypesResultValues.Tag.OptArray: { - __bjs_optionalCodec(__bjs_arrayCodec(__bjs_primitiveCodecs.Int)).lower(value.param0); + __bjs_codec_Optional_Array_Int.lower(value.param0); return OptionalAllTypesResultValues.Tag.OptArray; } case OptionalAllTypesResultValues.Tag.Empty: { @@ -936,45 +939,23 @@ export async function createInstantiator(options, swift) { tag = tag | 0; switch (tag) { case OptionalAllTypesResultValues.Tag.OptStruct: { - const optValue = __bjs_optionalCodec(structHelpers.Point).lift(); + const optValue = __bjs_codec_Optional_TestModule_Point.lift(); return { tag: OptionalAllTypesResultValues.Tag.OptStruct, param0: optValue }; } case OptionalAllTypesResultValues.Tag.OptClass: { - const elemCodec = { - lower: (v) => { - ptrStack.push(v.pointer); - }, - lift: () => { - const ptr = ptrStack.pop(); - const obj = _exports['User'].__construct(ptr); - return obj; - }, - }; - const optValue = __bjs_optionalCodec(elemCodec).lift(); + const optValue = __bjs_codec_Optional_TestModule_User.lift(); return { tag: OptionalAllTypesResultValues.Tag.OptClass, param0: optValue }; } case OptionalAllTypesResultValues.Tag.OptJSObject: { - const elemCodec = { - lower: (v) => { - const objId = swift.memory.retain(v); - i32Stack.push(objId); - }, - lift: () => { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - return obj; - }, - }; - const optValue = __bjs_optionalCodec(elemCodec).lift(); + const optValue = __bjs_codec_Optional_JSObject.lift(); return { tag: OptionalAllTypesResultValues.Tag.OptJSObject, param0: optValue }; } case OptionalAllTypesResultValues.Tag.OptNestedEnum: { - const optValue = __bjs_optionalCodec(__bjs_enumCodec(enumHelpers.APIResult)).lift(); + const optValue = __bjs_codec_Optional_TestModule_APIResult.lift(); return { tag: OptionalAllTypesResultValues.Tag.OptNestedEnum, param0: optValue }; } case OptionalAllTypesResultValues.Tag.OptArray: { - const optValue = __bjs_optionalCodec(__bjs_arrayCodec(__bjs_primitiveCodecs.Int)).lift(); + const optValue = __bjs_codec_Optional_Array_Int.lift(); return { tag: OptionalAllTypesResultValues.Tag.OptArray, param0: optValue }; } case OptionalAllTypesResultValues.Tag.Empty: return { tag: OptionalAllTypesResultValues.Tag.Empty }; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js index 92e1868c7..13e9e9015 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js @@ -168,16 +168,6 @@ export async function createInstantiator(options, swift) { }, }; } - function __bjs_enumCodec(helper) { - return { - lower(value) { - i32Stack.push(helper.lower(value)); - }, - lift() { - return helper.lift(i32Stack.pop()); - }, - }; - } const __bjs_stringCodec = { lower: (v) => { @@ -416,6 +406,27 @@ export async function createInstantiator(options, swift) { return jsValue; } + const __bjs_codec_TestModule_FileSize = { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const rawValue = i64Stack.pop(); + return rawValue; + }, + }; + const __bjs_codec_Optional_TestModule_FileSize = __bjs_optionalCodec(__bjs_codec_TestModule_FileSize); + const __bjs_codec_TestModule_SessionId = { + lower: (v) => { + i64Stack.push(v); + }, + lift: () => { + const rawValue = i64Stack.pop(); + return rawValue; + }, + }; + const __bjs_codec_Optional_TestModule_SessionId = __bjs_optionalCodec(__bjs_codec_TestModule_SessionId); + return { /** @@ -760,16 +771,7 @@ export async function createInstantiator(options, swift) { roundTripOptionalFileSize: function bjs_roundTripOptionalFileSize(input) { const isSome = input != null; instance.exports.bjs_roundTripOptionalFileSize(+isSome, isSome ? input : 0n); - const elemCodec = { - lower: (v) => { - i64Stack.push(v); - }, - lift: () => { - const rawValue = i64Stack.pop(); - return rawValue; - }, - }; - const optValue = __bjs_optionalCodec(elemCodec).lift(); + const optValue = __bjs_codec_Optional_TestModule_FileSize.lift(); return optValue; }, setUserId: function bjs_setUserId(id) { @@ -810,16 +812,7 @@ export async function createInstantiator(options, swift) { roundTripOptionalSessionId: function bjs_roundTripOptionalSessionId(input) { const isSome = input != null; instance.exports.bjs_roundTripOptionalSessionId(+isSome, isSome ? input : 0n); - const elemCodec = { - lower: (v) => { - i64Stack.push(v); - }, - lift: () => { - const rawValue = i64Stack.pop(); - return rawValue; - }, - }; - const optValue = __bjs_optionalCodec(elemCodec).lift(); + const optValue = __bjs_codec_Optional_TestModule_SessionId.lift(); return optValue; }, setPrecision: function bjs_setPrecision(precision) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js index f9a599e80..677b0e16a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js @@ -127,16 +127,6 @@ export async function createInstantiator(options, swift) { }, }; } - function __bjs_enumCodec(helper) { - return { - lower(value) { - i32Stack.push(helper.lower(value)); - }, - lift() { - return helper.lift(i32Stack.pop()); - }, - }; - } const __bjs_stringCodec = { lower: (v) => { @@ -375,6 +365,46 @@ export async function createInstantiator(options, swift) { return jsValue; } + const __bjs_codec_Array_Int = __bjs_arrayCodec(__bjs_primitiveCodecs.Int); + const __bjs_codec_TestModule_GenericPoint = { + lower: (v) => { + structHelpers.GenericPoint.lower(v); + }, + lift: () => { + const struct = structHelpers.GenericPoint.lift(); + return struct; + }, + }; + const __bjs_codec_TestModule_GenericImportBox = { + lower: (v) => { + ptrStack.push(v.pointer); + }, + lift: () => { + const ptr = ptrStack.pop(); + const obj = _exports['GenericImportBox'].__construct(ptr); + return obj; + }, + }; + const __bjs_codec_TestModule_GenericColor = { + lower: (v) => { + i32Stack.push((v | 0)); + }, + lift: () => { + const caseId = i32Stack.pop(); + return caseId; + }, + }; + const __bjs_codec_TestModule_GenericTagged = { + lower: (v) => { + const caseId = enumHelpers.GenericTagged.lower(v); + i32Stack.push(caseId); + }, + lift: () => { + const enumValue = enumHelpers.GenericTagged.lift(i32Stack.pop()); + return enumValue; + }, + }; + const __bjs_createGenericPointHelpers = () => ({ lower: (value) => { i32Stack.push((value.x | 0)); @@ -530,56 +560,11 @@ export async function createInstantiator(options, swift) { } bjs["bjs_TestModule_register_type_handles"] = function(base, count) { const codecs = [ - { - lower: (v) => { - structHelpers.GenericPoint.lower(v); - }, - lift: () => { - const struct = structHelpers.GenericPoint.lift(); - return struct; - }, - }, - { - lower: (v) => { - ptrStack.push(v.pointer); - }, - lift: () => { - const ptr = ptrStack.pop(); - const obj = _exports['GenericImportBox'].__construct(ptr); - return obj; - }, - }, - { - lower: (v) => { - i32Stack.push((v | 0)); - }, - lift: () => { - const caseId = i32Stack.pop(); - return caseId; - }, - }, - { - lower: (v) => { - const bytes = textEncoder.encode(v); - const id = swift.memory.retain(bytes); - i32Stack.push(bytes.length); - i32Stack.push(id); - }, - lift: () => { - const rawValue = strStack.pop(); - return rawValue; - }, - }, - { - lower: (v) => { - const caseId = enumHelpers.GenericTagged.lower(v); - i32Stack.push(caseId); - }, - lift: () => { - const enumValue = enumHelpers.GenericTagged.lift(i32Stack.pop()); - return enumValue; - }, - }, + __bjs_codec_TestModule_GenericPoint, + __bjs_codec_TestModule_GenericImportBox, + __bjs_codec_TestModule_GenericColor, + __bjs_stringCodec, + __bjs_codec_TestModule_GenericTagged, ]; const typeIds = new Int32Array(memory.buffer, base >>> 0, count >>> 0); for (let i = 0; i < count; i++) { @@ -771,7 +756,7 @@ export async function createInstantiator(options, swift) { const codecT = __bjs_codecForTypeId(tTypeId); let optResult; if (values) { - const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lift(); + const arrayResult = __bjs_codec_Array_Int.lift(); optResult = arrayResult; } else { optResult = null; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js index 77cde8a89..535effde3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js @@ -93,16 +93,6 @@ export async function createInstantiator(options, swift) { }, }; } - function __bjs_enumCodec(helper) { - return { - lower(value) { - i32Stack.push(helper.lower(value)); - }, - lift() { - return helper.lift(i32Stack.pop()); - }, - }; - } const __bjs_stringCodec = { lower: (v) => { @@ -341,6 +331,9 @@ export async function createInstantiator(options, swift) { return jsValue; } + const __bjs_codec_Array_Int = __bjs_arrayCodec(__bjs_primitiveCodecs.Int); + const __bjs_codec_Array_String = __bjs_arrayCodec(__bjs_stringCodec); + return { /** @@ -518,16 +511,16 @@ export async function createInstantiator(options, swift) { const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; TestModule["bjs_roundtrip"] = function bjs_roundtrip() { try { - const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lift(); + const arrayResult = __bjs_codec_Array_Int.lift(); let ret = imports.roundtrip(arrayResult); - __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lower(ret); + __bjs_codec_Array_Int.lower(ret); } catch (error) { setException(error); } } TestModule["bjs_logStrings"] = function bjs_logStrings() { try { - const arrayResult = __bjs_arrayCodec(__bjs_stringCodec).lift(); + const arrayResult = __bjs_codec_Array_String.lift(); imports.logStrings(arrayResult); } catch (error) { setException(error); @@ -537,12 +530,12 @@ export async function createInstantiator(options, swift) { try { let optResult; if (a) { - const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lift(); + const arrayResult = __bjs_codec_Array_Int.lift(); optResult = arrayResult; } else { optResult = null; } - const arrayResult1 = __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lift(); + const arrayResult1 = __bjs_codec_Array_Int.lift(); let ret = imports.optionalArrayThenArray(optResult, arrayResult1); return ret; } catch (error) { @@ -555,12 +548,12 @@ export async function createInstantiator(options, swift) { const string = decodeString(sBytes, sCount); let optResult; if (a) { - const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lift(); + const arrayResult = __bjs_codec_Array_Int.lift(); optResult = arrayResult; } else { optResult = null; } - const arrayResult1 = __bjs_arrayCodec(__bjs_primitiveCodecs.Int).lift(); + const arrayResult1 = __bjs_codec_Array_Int.lift(); let ret = imports.borrowedStringAroundStackParams(string, optResult, arrayResult1); return ret; } catch (error) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js index e3fbdba8d..4a8cd2a4d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js @@ -93,16 +93,6 @@ export async function createInstantiator(options, swift) { }, }; } - function __bjs_enumCodec(helper) { - return { - lower(value) { - i32Stack.push(helper.lower(value)); - }, - lift() { - return helper.lift(i32Stack.pop()); - }, - }; - } const __bjs_stringCodec = { lower: (v) => { @@ -341,6 +331,22 @@ export async function createInstantiator(options, swift) { return jsValue; } + const __bjs_codec_TestModule_Foo = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + const __bjs_codec_Array_TestModule_Foo = __bjs_arrayCodec(__bjs_codec_TestModule_Foo); + const __bjs_codec_Optional_TestModule_Foo = __bjs_optionalCodec(__bjs_codec_TestModule_Foo); + const __bjs_codec_Array_Optional_TestModule_Foo = __bjs_arrayCodec(__bjs_codec_Optional_TestModule_Foo); + const __bjs_createFooContainerHelpers = () => ({ lower: (value) => { let id; @@ -350,34 +356,10 @@ export async function createInstantiator(options, swift) { id = undefined; } i32Stack.push(id !== undefined ? id : 0); - const elemCodec = { - lower: (v) => { - const objId = swift.memory.retain(v); - i32Stack.push(objId); - }, - lift: () => { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - return obj; - }, - }; - __bjs_optionalCodec(elemCodec).lower(value.optionalFoo); + __bjs_codec_Optional_TestModule_Foo.lower(value.optionalFoo); }, lift: () => { - const elemCodec = { - lower: (v) => { - const objId = swift.memory.retain(v); - i32Stack.push(objId); - }, - lift: () => { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - return obj; - }, - }; - const optValue = __bjs_optionalCodec(elemCodec).lift(); + const optValue = __bjs_codec_Optional_TestModule_Foo.lift(); const objectId = i32Stack.pop(); let value; if (objectId !== 0) { @@ -611,63 +593,15 @@ export async function createInstantiator(options, swift) { return ret1; }, processFooArray: function bjs_processFooArray(foos) { - const elemCodec = { - lower: (v) => { - const objId = swift.memory.retain(v); - i32Stack.push(objId); - }, - lift: () => { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - return obj; - }, - }; - __bjs_arrayCodec(elemCodec).lower(foos); + __bjs_codec_Array_TestModule_Foo.lower(foos); instance.exports.bjs_processFooArray(); - const elemCodec1 = { - lower: (v) => { - const objId = swift.memory.retain(v); - i32Stack.push(objId); - }, - lift: () => { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - return obj; - }, - }; - const arrayResult = __bjs_arrayCodec(elemCodec1).lift(); + const arrayResult = __bjs_codec_Array_TestModule_Foo.lift(); return arrayResult; }, processOptionalFooArray: function bjs_processOptionalFooArray(foos) { - const elemCodec = { - lower: (v) => { - const objId = swift.memory.retain(v); - i32Stack.push(objId); - }, - lift: () => { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - return obj; - }, - }; - __bjs_arrayCodec(__bjs_optionalCodec(elemCodec)).lower(foos); + __bjs_codec_Array_Optional_TestModule_Foo.lower(foos); instance.exports.bjs_processOptionalFooArray(); - const elemCodec1 = { - lower: (v) => { - const objId = swift.memory.retain(v); - i32Stack.push(objId); - }, - lift: () => { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - return obj; - }, - }; - const arrayResult = __bjs_arrayCodec(__bjs_optionalCodec(elemCodec1)).lift(); + const arrayResult = __bjs_codec_Array_Optional_TestModule_Foo.lift(); return arrayResult; }, roundtripFooContainer: function bjs_roundtripFooContainer(container) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js index 136167f2a..d46ffb1a8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js @@ -93,16 +93,6 @@ export async function createInstantiator(options, swift) { }, }; } - function __bjs_enumCodec(helper) { - return { - lower(value) { - i32Stack.push(helper.lower(value)); - }, - lift() { - return helper.lift(i32Stack.pop()); - }, - }; - } const __bjs_stringCodec = { lower: (v) => { @@ -341,6 +331,9 @@ export async function createInstantiator(options, swift) { return jsValue; } + const __bjs_codec_Array_JSValue = __bjs_arrayCodec(__bjs_primitiveCodecs.JSValue); + const __bjs_codec_Optional_Array_JSValue = __bjs_optionalCodec(__bjs_codec_Array_JSValue); + return { /** @@ -538,9 +531,9 @@ export async function createInstantiator(options, swift) { } TestModule["bjs_jsEchoJSValueArray"] = function bjs_jsEchoJSValueArray() { try { - const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.JSValue).lift(); + const arrayResult = __bjs_codec_Array_JSValue.lift(); let ret = imports.jsEchoJSValueArray(arrayResult); - __bjs_arrayCodec(__bjs_primitiveCodecs.JSValue).lower(ret); + __bjs_codec_Array_JSValue.lower(ret); } catch (error) { setException(error); } @@ -766,15 +759,15 @@ export async function createInstantiator(options, swift) { return optResult; }, roundTripJSValueArray: function bjs_roundTripJSValueArray(values) { - __bjs_arrayCodec(__bjs_primitiveCodecs.JSValue).lower(values); + __bjs_codec_Array_JSValue.lower(values); instance.exports.bjs_roundTripJSValueArray(); - const arrayResult = __bjs_arrayCodec(__bjs_primitiveCodecs.JSValue).lift(); + const arrayResult = __bjs_codec_Array_JSValue.lift(); return arrayResult; }, roundTripOptionalJSValueArray: function bjs_roundTripOptionalJSValueArray(values) { - __bjs_optionalCodec(__bjs_arrayCodec(__bjs_primitiveCodecs.JSValue)).lower(values); + __bjs_codec_Optional_Array_JSValue.lower(values); instance.exports.bjs_roundTripOptionalJSValueArray(); - const optValue = __bjs_optionalCodec(__bjs_arrayCodec(__bjs_primitiveCodecs.JSValue)).lift(); + const optValue = __bjs_codec_Optional_Array_JSValue.lift(); return optValue; }, JSValueHolder, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js index ef10ff9b9..40b5bd079 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js @@ -93,16 +93,6 @@ export async function createInstantiator(options, swift) { }, }; } - function __bjs_enumCodec(helper) { - return { - lower(value) { - i32Stack.push(helper.lower(value)); - }, - lift() { - return helper.lift(i32Stack.pop()); - }, - }; - } const __bjs_stringCodec = { lower: (v) => { @@ -341,6 +331,18 @@ export async function createInstantiator(options, swift) { return jsValue; } + const __bjs_codec_TestModule_Greeter = { + lower: (v) => { + ptrStack.push(v.pointer); + }, + lift: () => { + const ptr = ptrStack.pop(); + const obj = _exports.__Swift.Foundation.Greeter.__construct(ptr); + return obj; + }, + }; + const __bjs_codec_Array_TestModule_Greeter = __bjs_arrayCodec(__bjs_codec_TestModule_Greeter); + return { /** @@ -667,17 +669,7 @@ export async function createInstantiator(options, swift) { } getItems() { instance.exports.bjs_Collections_Container_getItems(this.pointer); - const elemCodec = { - lower: (v) => { - ptrStack.push(v.pointer); - }, - lift: () => { - const ptr = ptrStack.pop(); - const obj = Greeter.__construct(ptr); - return obj; - }, - }; - const arrayResult = __bjs_arrayCodec(elemCodec).lift(); + const arrayResult = __bjs_codec_Array_TestModule_Greeter.lift(); return arrayResult; } addItem(item) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js index bb4fce7a6..18f03f8d8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js @@ -93,16 +93,6 @@ export async function createInstantiator(options, swift) { }, }; } - function __bjs_enumCodec(helper) { - return { - lower(value) { - i32Stack.push(helper.lower(value)); - }, - lift() { - return helper.lift(i32Stack.pop()); - }, - }; - } const __bjs_stringCodec = { lower: (v) => { @@ -341,6 +331,18 @@ export async function createInstantiator(options, swift) { return jsValue; } + const __bjs_codec_TestModule_Greeter = { + lower: (v) => { + ptrStack.push(v.pointer); + }, + lift: () => { + const ptr = ptrStack.pop(); + const obj = _exports.__Swift.Foundation.Greeter.__construct(ptr); + return obj; + }, + }; + const __bjs_codec_Array_TestModule_Greeter = __bjs_arrayCodec(__bjs_codec_TestModule_Greeter); + return { /** @@ -667,17 +669,7 @@ export async function createInstantiator(options, swift) { } getItems() { instance.exports.bjs_Collections_Container_getItems(this.pointer); - const elemCodec = { - lower: (v) => { - ptrStack.push(v.pointer); - }, - lift: () => { - const ptr = ptrStack.pop(); - const obj = Greeter.__construct(ptr); - return obj; - }, - }; - const arrayResult = __bjs_arrayCodec(elemCodec).lift(); + const arrayResult = __bjs_codec_Array_TestModule_Greeter.lift(); return arrayResult; } addItem(item) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js index 7d073e02a..2745d5a97 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js @@ -93,16 +93,6 @@ export async function createInstantiator(options, swift) { }, }; } - function __bjs_enumCodec(helper) { - return { - lower(value) { - i32Stack.push(helper.lower(value)); - }, - lift() { - return helper.lift(i32Stack.pop()); - }, - }; - } const __bjs_stringCodec = { lower: (v) => { @@ -341,6 +331,33 @@ export async function createInstantiator(options, swift) { return jsValue; } + const __bjs_codec_JSObject = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + const __bjs_codec_Optional_JSObject = __bjs_optionalCodec(__bjs_codec_JSObject); + const __bjs_codec_TestModule_WithOptionalJSClass = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + const __bjs_codec_Optional_TestModule_WithOptionalJSClass = __bjs_optionalCodec(__bjs_codec_TestModule_WithOptionalJSClass); + return { /** @@ -625,19 +642,7 @@ export async function createInstantiator(options, swift) { TestModule["bjs_WithOptionalJSClass_childOrNull_get"] = function bjs_WithOptionalJSClass_childOrNull_get(self) { try { let ret = swift.memory.getObject(self).childOrNull; - const elemCodec = { - lower: (v) => { - const objId = swift.memory.retain(v); - i32Stack.push(objId); - }, - lift: () => { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - return obj; - }, - }; - __bjs_optionalCodec(elemCodec).lower(ret); + __bjs_codec_Optional_TestModule_WithOptionalJSClass.lower(ret); } catch (error) { setException(error); } @@ -808,19 +813,7 @@ export async function createInstantiator(options, swift) { TestModule["bjs_WithOptionalJSClass_roundTripChildOrNull"] = function bjs_WithOptionalJSClass_roundTripChildOrNull(self, valueIsSome, valueObjectId) { try { let ret = swift.memory.getObject(self).roundTripChildOrNull(valueIsSome ? swift.memory.getObject(valueObjectId) : null); - const elemCodec = { - lower: (v) => { - const objId = swift.memory.retain(v); - i32Stack.push(objId); - }, - lift: () => { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - return obj; - }, - }; - __bjs_optionalCodec(elemCodec).lower(ret); + __bjs_codec_Optional_TestModule_WithOptionalJSClass.lower(ret); } catch (error) { setException(error); } @@ -1047,19 +1040,7 @@ export async function createInstantiator(options, swift) { result = 0; } instance.exports.bjs_roundTripExportedOptionalJSObject(+isSome, result); - const elemCodec = { - lower: (v) => { - const objId = swift.memory.retain(v); - i32Stack.push(objId); - }, - lift: () => { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - return obj; - }, - }; - const optValue = __bjs_optionalCodec(elemCodec).lift(); + const optValue = __bjs_codec_Optional_JSObject.lift(); return optValue; }, roundTripExportedOptionalJSClass: function bjs_roundTripExportedOptionalJSClass(value) { @@ -1071,19 +1052,7 @@ export async function createInstantiator(options, swift) { result = 0; } instance.exports.bjs_roundTripExportedOptionalJSClass(+isSome, result); - const elemCodec = { - lower: (v) => { - const objId = swift.memory.retain(v); - i32Stack.push(objId); - }, - lift: () => { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - return obj; - }, - }; - const optValue = __bjs_optionalCodec(elemCodec).lift(); + const optValue = __bjs_codec_Optional_TestModule_WithOptionalJSClass.lift(); return optValue; }, roundTripString: function bjs_roundTripString(name) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js index c28ceeb31..65bf34266 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js @@ -117,16 +117,6 @@ export async function createInstantiator(options, swift) { }, }; } - function __bjs_enumCodec(helper) { - return { - lower(value) { - i32Stack.push(helper.lower(value)); - }, - lift() { - return helper.lift(i32Stack.pop()); - }, - }; - } const __bjs_stringCodec = { lower: (v) => { @@ -365,6 +355,21 @@ export async function createInstantiator(options, swift) { return jsValue; } + const __bjs_codec_TestModule_MyViewControllerDelegate = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + const __bjs_codec_Array_TestModule_MyViewControllerDelegate = __bjs_arrayCodec(__bjs_codec_TestModule_MyViewControllerDelegate); + const __bjs_codec_Dict_TestModule_MyViewControllerDelegate = __bjs_dictCodec(__bjs_codec_TestModule_MyViewControllerDelegate); + const __bjs_createResultValuesHelpers = () => ({ lower: (value) => { const enumTag = value.tag; @@ -1036,19 +1041,7 @@ export async function createInstantiator(options, swift) { } constructor(delegates) { - const elemCodec = { - lower: (v) => { - const objId = swift.memory.retain(v); - i32Stack.push(objId); - }, - lift: () => { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - return obj; - }, - }; - __bjs_arrayCodec(elemCodec).lower(delegates); + __bjs_codec_Array_TestModule_MyViewControllerDelegate.lower(delegates); const ret = instance.exports.bjs_DelegateManager_init(); return DelegateManager.__construct(ret); } @@ -1057,68 +1050,20 @@ export async function createInstantiator(options, swift) { } get delegates() { instance.exports.bjs_DelegateManager_delegates_get(this.pointer); - const elemCodec = { - lower: (v) => { - const objId = swift.memory.retain(v); - i32Stack.push(objId); - }, - lift: () => { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - return obj; - }, - }; - const arrayResult = __bjs_arrayCodec(elemCodec).lift(); + const arrayResult = __bjs_codec_Array_TestModule_MyViewControllerDelegate.lift(); return arrayResult; } set delegates(value) { - const elemCodec = { - lower: (v) => { - const objId = swift.memory.retain(v); - i32Stack.push(objId); - }, - lift: () => { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - return obj; - }, - }; - __bjs_arrayCodec(elemCodec).lower(value); + __bjs_codec_Array_TestModule_MyViewControllerDelegate.lower(value); instance.exports.bjs_DelegateManager_delegates_set(this.pointer); } get delegatesByName() { instance.exports.bjs_DelegateManager_delegatesByName_get(this.pointer); - const elemCodec = { - lower: (v) => { - const objId = swift.memory.retain(v); - i32Stack.push(objId); - }, - lift: () => { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - return obj; - }, - }; - const dictResult = __bjs_dictCodec(elemCodec).lift(); + const dictResult = __bjs_codec_Dict_TestModule_MyViewControllerDelegate.lift(); return dictResult; } set delegatesByName(value) { - const elemCodec = { - lower: (v) => { - const objId = swift.memory.retain(v); - i32Stack.push(objId); - }, - lift: () => { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - return obj; - }, - }; - __bjs_dictCodec(elemCodec).lower(value); + __bjs_codec_Dict_TestModule_MyViewControllerDelegate.lower(value); instance.exports.bjs_DelegateManager_delegatesByName_set(this.pointer); } } @@ -1127,63 +1072,15 @@ export async function createInstantiator(options, swift) { const exports = { processDelegates: function bjs_processDelegates(delegates) { - const elemCodec = { - lower: (v) => { - const objId = swift.memory.retain(v); - i32Stack.push(objId); - }, - lift: () => { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - return obj; - }, - }; - __bjs_arrayCodec(elemCodec).lower(delegates); + __bjs_codec_Array_TestModule_MyViewControllerDelegate.lower(delegates); instance.exports.bjs_processDelegates(); - const elemCodec1 = { - lower: (v) => { - const objId = swift.memory.retain(v); - i32Stack.push(objId); - }, - lift: () => { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - return obj; - }, - }; - const arrayResult = __bjs_arrayCodec(elemCodec1).lift(); + const arrayResult = __bjs_codec_Array_TestModule_MyViewControllerDelegate.lift(); return arrayResult; }, processDelegatesByName: function bjs_processDelegatesByName(delegates) { - const elemCodec = { - lower: (v) => { - const objId = swift.memory.retain(v); - i32Stack.push(objId); - }, - lift: () => { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - return obj; - }, - }; - __bjs_dictCodec(elemCodec).lower(delegates); + __bjs_codec_Dict_TestModule_MyViewControllerDelegate.lower(delegates); instance.exports.bjs_processDelegatesByName(); - const elemCodec1 = { - lower: (v) => { - const objId = swift.memory.retain(v); - i32Stack.push(objId); - }, - lift: () => { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - return obj; - }, - }; - const dictResult = __bjs_dictCodec(elemCodec1).lift(); + const dictResult = __bjs_codec_Dict_TestModule_MyViewControllerDelegate.lift(); return dictResult; }, Direction: DirectionValues, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js index e208ff35c..cbf97bb5e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js @@ -123,16 +123,6 @@ export async function createInstantiator(options, swift) { }, }; } - function __bjs_enumCodec(helper) { - return { - lower(value) { - i32Stack.push(helper.lower(value)); - }, - lift() { - return helper.lift(i32Stack.pop()); - }, - }; - } const __bjs_stringCodec = { lower: (v) => { @@ -396,6 +386,17 @@ export async function createInstantiator(options, swift) { return swift.memory.retain(real); }; + const __bjs_codec_TestModule_Animal = { + lower: (v) => { + structHelpers.Animal.lower(v); + }, + lift: () => { + const struct = structHelpers.Animal.lift(); + return struct; + }, + }; + const __bjs_codec_Optional_TestModule_Animal = __bjs_optionalCodec(__bjs_codec_TestModule_Animal); + const __bjs_createAnimalHelpers = () => ({ lower: (value) => { const bytes = textEncoder.encode(value.type); @@ -1086,16 +1087,16 @@ export async function createInstantiator(options, swift) { optResult = null; } let ret = callback(optResult); - __bjs_optionalCodec(structHelpers.Animal).lower(ret); + __bjs_codec_Optional_TestModule_Animal.lower(ret); } catch (error) { setException(error); } } bjs["make_swift_closure_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV"] = function(boxPtr, file, line) { const lower_closure_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV = function(param0) { - __bjs_optionalCodec(structHelpers.Animal).lower(param0); + __bjs_codec_Optional_TestModule_Animal.lower(param0); instance.exports.invoke_swift_closure_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV(boxPtr); - const optValue = __bjs_optionalCodec(structHelpers.Animal).lift(); + const optValue = __bjs_codec_Optional_TestModule_Animal.lift(); if (tmpRetException) { const error = swift.memory.getObject(tmpRetException); swift.memory.release(tmpRetException); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js index ad8d4e29d..a5496d4ee 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js @@ -98,16 +98,6 @@ export async function createInstantiator(options, swift) { }, }; } - function __bjs_enumCodec(helper) { - return { - lower(value) { - i32Stack.push(helper.lower(value)); - }, - lift() { - return helper.lift(i32Stack.pop()); - }, - }; - } const __bjs_stringCodec = { lower: (v) => { @@ -346,6 +336,33 @@ export async function createInstantiator(options, swift) { return jsValue; } + const __bjs_codec_Optional_Int = __bjs_optionalCodec(__bjs_primitiveCodecs.Int); + const __bjs_codec_Optional_Bool = __bjs_optionalCodec(__bjs_primitiveCodecs.Bool); + const __bjs_codec_Optional_String = __bjs_optionalCodec(__bjs_stringCodec); + const __bjs_codec_TestModule_Precision = { + lower: (v) => { + f32Stack.push(Math.fround(v)); + }, + lift: () => { + const rawValue = f32Stack.pop(); + return rawValue; + }, + }; + const __bjs_codec_Optional_TestModule_Precision = __bjs_optionalCodec(__bjs_codec_TestModule_Precision); + const __bjs_codec_JSObject = { + lower: (v) => { + const objId = swift.memory.retain(v); + i32Stack.push(objId); + }, + lift: () => { + const objId = i32Stack.pop(); + const obj = swift.memory.getObject(objId); + swift.memory.release(objId); + return obj; + }, + }; + const __bjs_codec_Optional_JSObject = __bjs_optionalCodec(__bjs_codec_JSObject); + const __bjs_createDataPointHelpers = () => ({ lower: (value) => { f64Stack.push(value.x); @@ -354,12 +371,12 @@ export async function createInstantiator(options, swift) { const id = swift.memory.retain(bytes); i32Stack.push(bytes.length); i32Stack.push(id); - __bjs_optionalCodec(__bjs_primitiveCodecs.Int).lower(value.optCount); - __bjs_optionalCodec(__bjs_primitiveCodecs.Bool).lower(value.optFlag); + __bjs_codec_Optional_Int.lower(value.optCount); + __bjs_codec_Optional_Bool.lower(value.optFlag); }, lift: () => { - const optValue = __bjs_optionalCodec(__bjs_primitiveCodecs.Bool).lift(); - const optValue1 = __bjs_optionalCodec(__bjs_primitiveCodecs.Int).lift(); + const optValue = __bjs_codec_Optional_Bool.lift(); + const optValue1 = __bjs_codec_Optional_Int.lift(); const string = strStack.pop(); const f64 = f64Stack.pop(); const f641 = f64Stack.pop(); @@ -376,10 +393,10 @@ export async function createInstantiator(options, swift) { const id1 = swift.memory.retain(bytes1); i32Stack.push(bytes1.length); i32Stack.push(id1); - __bjs_optionalCodec(__bjs_primitiveCodecs.Int).lower(value.zipCode); + __bjs_codec_Optional_Int.lower(value.zipCode); }, lift: () => { - const optValue = __bjs_optionalCodec(__bjs_primitiveCodecs.Int).lift(); + const optValue = __bjs_codec_Optional_Int.lift(); const string = strStack.pop(); const string1 = strStack.pop(); return { street: string1, city: string, zipCode: optValue }; @@ -393,10 +410,10 @@ export async function createInstantiator(options, swift) { i32Stack.push(id); i32Stack.push((value.age | 0)); structHelpers.Address.lower(value.address); - __bjs_optionalCodec(__bjs_stringCodec).lower(value.email); + __bjs_codec_Optional_String.lower(value.email); }, lift: () => { - const optValue = __bjs_optionalCodec(__bjs_stringCodec).lift(); + const optValue = __bjs_codec_Optional_String.lift(); const struct = structHelpers.Address.lift(); const int = i32Stack.pop(); const string = strStack.pop(); @@ -419,28 +436,10 @@ export async function createInstantiator(options, swift) { lower: (value) => { f64Stack.push(value.value); f32Stack.push(Math.fround(value.precision)); - const elemCodec = { - lower: (v) => { - f32Stack.push(Math.fround(v)); - }, - lift: () => { - const rawValue = f32Stack.pop(); - return rawValue; - }, - }; - __bjs_optionalCodec(elemCodec).lower(value.optionalPrecision); + __bjs_codec_Optional_TestModule_Precision.lower(value.optionalPrecision); }, lift: () => { - const elemCodec = { - lower: (v) => { - f32Stack.push(Math.fround(v)); - }, - lift: () => { - const rawValue = f32Stack.pop(); - return rawValue; - }, - }; - const optValue = __bjs_optionalCodec(elemCodec).lift(); + const optValue = __bjs_codec_Optional_TestModule_Precision.lift(); const rawValue = f32Stack.pop(); const f64 = f64Stack.pop(); return { value: f64, precision: rawValue, optionalPrecision: optValue }; @@ -462,34 +461,10 @@ export async function createInstantiator(options, swift) { id = undefined; } i32Stack.push(id !== undefined ? id : 0); - const elemCodec = { - lower: (v) => { - const objId = swift.memory.retain(v); - i32Stack.push(objId); - }, - lift: () => { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - return obj; - }, - }; - __bjs_optionalCodec(elemCodec).lower(value.optionalObject); + __bjs_codec_Optional_JSObject.lower(value.optionalObject); }, lift: () => { - const elemCodec = { - lower: (v) => { - const objId = swift.memory.retain(v); - i32Stack.push(objId); - }, - lift: () => { - const objId = i32Stack.pop(); - const obj = swift.memory.getObject(objId); - swift.memory.release(objId); - return obj; - }, - }; - const optValue = __bjs_optionalCodec(elemCodec).lift(); + const optValue = __bjs_codec_Optional_JSObject.lift(); const objectId = i32Stack.pop(); let value; if (objectId !== 0) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js index e9add7027..159d4b616 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js @@ -93,16 +93,6 @@ export async function createInstantiator(options, swift) { }, }; } - function __bjs_enumCodec(helper) { - return { - lower(value) { - i32Stack.push(helper.lower(value)); - }, - lift() { - return helper.lift(i32Stack.pop()); - }, - }; - } const __bjs_stringCodec = { lower: (v) => { @@ -341,6 +331,17 @@ export async function createInstantiator(options, swift) { return jsValue; } + const __bjs_codec_TestModule_Point = { + lower: (v) => { + structHelpers.Point.lower(v); + }, + lift: () => { + const struct = structHelpers.Point.lift(); + return struct; + }, + }; + const __bjs_codec_Optional_TestModule_Point = __bjs_optionalCodec(__bjs_codec_TestModule_Point); + const __bjs_createPointHelpers = () => ({ lower: (value) => { i32Stack.push((value.x | 0)); @@ -554,7 +555,7 @@ export async function createInstantiator(options, swift) { optResult = null; } let ret = imports.roundTripOptional(optResult); - __bjs_optionalCodec(structHelpers.Point).lower(ret); + __bjs_codec_Optional_TestModule_Point.lower(ret); } catch (error) { setException(error); } From 81dee2feaf5c1f3d7a4f872f88ad84a9c150ea8d Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Tue, 11 Aug 2026 14:51:48 +0200 Subject: [PATCH 41/50] BridgeJS: Reuse container codecs by element type --- .../Sources/BridgeJSLink/JSGlueGen.swift | 37 +++++++++++++++++-- .../__Snapshots__/BridgeJSLinkTests/Alias.js | 29 +++++++++++++-- .../BridgeJSLinkTests/ArrayTypes.js | 29 +++++++++++++-- .../__Snapshots__/BridgeJSLinkTests/Async.js | 29 +++++++++++++-- .../BridgeJSLinkTests/DefaultParameters.js | 29 +++++++++++++-- .../BridgeJSLinkTests/DictionaryTypes.js | 29 +++++++++++++-- .../BridgeJSLinkTests/EnumAssociatedValue.js | 29 +++++++++++++-- .../BridgeJSLinkTests/EnumRawType.js | 29 +++++++++++++-- .../BridgeJSLinkTests/GenericImports.js | 29 +++++++++++++-- .../BridgeJSLinkTests/ImportArray.js | 29 +++++++++++++-- .../ImportedTypeInExportedInterface.js | 29 +++++++++++++-- .../BridgeJSLinkTests/JSValue.js | 29 +++++++++++++-- .../BridgeJSLinkTests/Namespaces.Global.js | 29 +++++++++++++-- .../BridgeJSLinkTests/Namespaces.js | 29 +++++++++++++-- .../BridgeJSLinkTests/Optionals.js | 29 +++++++++++++-- .../BridgeJSLinkTests/Protocol.js | 29 +++++++++++++-- .../BridgeJSLinkTests/SwiftClosure.js | 29 +++++++++++++-- .../BridgeJSLinkTests/SwiftStruct.js | 29 +++++++++++++-- .../BridgeJSLinkTests/SwiftStructImports.js | 29 +++++++++++++-- 19 files changed, 502 insertions(+), 57 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift index f8b5d08a6..060f4f507 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift @@ -216,12 +216,23 @@ enum ContainerCodecJS { private static let primitiveCodecIntrinsicName = "containerPrimitiveCodecs" /// The single description of each container shape's stack ABI. + /// + /// The combinators memoize per element codec object. Statically known + /// compositions are hoisted into module-scope `const`s and so instantiate a + /// combinator only once, but a generic call site resolves its element codec + /// from a runtime type ID and cannot be hoisted; memoizing keeps those call + /// sites from allocating a fresh codec on every call. static func combinatorDeclarations() -> [String] { let i32 = JSGlueVariableScope.reservedI32Stack let stringCodec = JSGlueVariableScope.reservedStringCodec return [ + "const \(arrayCodec)Cache = new WeakMap();", "function \(arrayCodec)(elementCodec) {", - " return {", + " let codec = \(arrayCodec)Cache.get(elementCodec);", + " if (codec !== undefined) {", + " return codec;", + " }", + " codec = {", " lower(value) {", " for (let i = 0; i < value.length; i++) {", " elementCodec.lower(value[i]);", @@ -240,11 +251,22 @@ enum ContainerCodecJS { " return result;", " },", " };", + " \(arrayCodec)Cache.set(elementCodec, codec);", + " return codec;", "}", // `isUndefinedOr` selects the `JSUndefinedOr` flavor: `null` is then a // present value and absence surfaces as `undefined` instead of `null`. + // The two flavors are cached separately because they differ in + // behavior, not just in the element codec. + "const \(optionalCodec)Cache = new WeakMap();", + "const \(optionalCodec)UndefinedOrCache = new WeakMap();", "function \(optionalCodec)(elementCodec, isUndefinedOr = false) {", - " return {", + " const cache = isUndefinedOr ? \(optionalCodec)UndefinedOrCache : \(optionalCodec)Cache;", + " let codec = cache.get(elementCodec);", + " if (codec !== undefined) {", + " return codec;", + " }", + " codec = {", " lower(value) {", " const isSome = isUndefinedOr ? value !== undefined : value != null;", " if (isSome) {", @@ -261,9 +283,16 @@ enum ContainerCodecJS { " return elementCodec.lift();", " },", " };", + " cache.set(elementCodec, codec);", + " return codec;", "}", + "const \(dictCodec)Cache = new WeakMap();", "function \(dictCodec)(valueCodec) {", - " return {", + " let codec = \(dictCodec)Cache.get(valueCodec);", + " if (codec !== undefined) {", + " return codec;", + " }", + " codec = {", " lower(value) {", " const keys = Object.keys(value);", " for (let i = 0; i < keys.length; i++) {", @@ -283,6 +312,8 @@ enum ContainerCodecJS { " return result;", " },", " };", + " \(dictCodec)Cache.set(valueCodec, codec);", + " return codec;", "}", ] } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js index fff8779ef..d70db0f42 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js @@ -37,8 +37,13 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + const __bjs_arrayCodecCache = new WeakMap(); function __bjs_arrayCodec(elementCodec) { - return { + let codec = __bjs_arrayCodecCache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { for (let i = 0; i < value.length; i++) { elementCodec.lower(value[i]); @@ -57,9 +62,18 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_arrayCodecCache.set(elementCodec, codec); + return codec; } + const __bjs_optionalCodecCache = new WeakMap(); + const __bjs_optionalCodecUndefinedOrCache = new WeakMap(); function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { - return { + const cache = isUndefinedOr ? __bjs_optionalCodecUndefinedOrCache : __bjs_optionalCodecCache; + let codec = cache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const isSome = isUndefinedOr ? value !== undefined : value != null; if (isSome) { @@ -76,9 +90,16 @@ export async function createInstantiator(options, swift) { return elementCodec.lift(); }, }; + cache.set(elementCodec, codec); + return codec; } + const __bjs_dictCodecCache = new WeakMap(); function __bjs_dictCodec(valueCodec) { - return { + let codec = __bjs_dictCodecCache.get(valueCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const keys = Object.keys(value); for (let i = 0; i < keys.length; i++) { @@ -98,6 +119,8 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_dictCodecCache.set(valueCodec, codec); + return codec; } const __bjs_stringCodec = { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js index e038620c1..aaa9460c8 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js @@ -44,8 +44,13 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + const __bjs_arrayCodecCache = new WeakMap(); function __bjs_arrayCodec(elementCodec) { - return { + let codec = __bjs_arrayCodecCache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { for (let i = 0; i < value.length; i++) { elementCodec.lower(value[i]); @@ -64,9 +69,18 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_arrayCodecCache.set(elementCodec, codec); + return codec; } + const __bjs_optionalCodecCache = new WeakMap(); + const __bjs_optionalCodecUndefinedOrCache = new WeakMap(); function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { - return { + const cache = isUndefinedOr ? __bjs_optionalCodecUndefinedOrCache : __bjs_optionalCodecCache; + let codec = cache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const isSome = isUndefinedOr ? value !== undefined : value != null; if (isSome) { @@ -83,9 +97,16 @@ export async function createInstantiator(options, swift) { return elementCodec.lift(); }, }; + cache.set(elementCodec, codec); + return codec; } + const __bjs_dictCodecCache = new WeakMap(); function __bjs_dictCodec(valueCodec) { - return { + let codec = __bjs_dictCodecCache.get(valueCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const keys = Object.keys(value); for (let i = 0; i < keys.length; i++) { @@ -105,6 +126,8 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_dictCodecCache.set(valueCodec, codec); + return codec; } const __bjs_stringCodec = { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js index 7bd19602d..2b667aefa 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js @@ -41,8 +41,13 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + const __bjs_arrayCodecCache = new WeakMap(); function __bjs_arrayCodec(elementCodec) { - return { + let codec = __bjs_arrayCodecCache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { for (let i = 0; i < value.length; i++) { elementCodec.lower(value[i]); @@ -61,9 +66,18 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_arrayCodecCache.set(elementCodec, codec); + return codec; } + const __bjs_optionalCodecCache = new WeakMap(); + const __bjs_optionalCodecUndefinedOrCache = new WeakMap(); function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { - return { + const cache = isUndefinedOr ? __bjs_optionalCodecUndefinedOrCache : __bjs_optionalCodecCache; + let codec = cache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const isSome = isUndefinedOr ? value !== undefined : value != null; if (isSome) { @@ -80,9 +94,16 @@ export async function createInstantiator(options, swift) { return elementCodec.lift(); }, }; + cache.set(elementCodec, codec); + return codec; } + const __bjs_dictCodecCache = new WeakMap(); function __bjs_dictCodec(valueCodec) { - return { + let codec = __bjs_dictCodecCache.get(valueCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const keys = Object.keys(value); for (let i = 0; i < keys.length; i++) { @@ -102,6 +123,8 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_dictCodecCache.set(valueCodec, codec); + return codec; } const __bjs_stringCodec = { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js index ef00bad23..3dc39e445 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js @@ -37,8 +37,13 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + const __bjs_arrayCodecCache = new WeakMap(); function __bjs_arrayCodec(elementCodec) { - return { + let codec = __bjs_arrayCodecCache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { for (let i = 0; i < value.length; i++) { elementCodec.lower(value[i]); @@ -57,9 +62,18 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_arrayCodecCache.set(elementCodec, codec); + return codec; } + const __bjs_optionalCodecCache = new WeakMap(); + const __bjs_optionalCodecUndefinedOrCache = new WeakMap(); function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { - return { + const cache = isUndefinedOr ? __bjs_optionalCodecUndefinedOrCache : __bjs_optionalCodecCache; + let codec = cache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const isSome = isUndefinedOr ? value !== undefined : value != null; if (isSome) { @@ -76,9 +90,16 @@ export async function createInstantiator(options, swift) { return elementCodec.lift(); }, }; + cache.set(elementCodec, codec); + return codec; } + const __bjs_dictCodecCache = new WeakMap(); function __bjs_dictCodec(valueCodec) { - return { + let codec = __bjs_dictCodecCache.get(valueCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const keys = Object.keys(value); for (let i = 0; i < keys.length; i++) { @@ -98,6 +119,8 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_dictCodecCache.set(valueCodec, codec); + return codec; } const __bjs_stringCodec = { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js index 74d9e7e59..6d8ea7392 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js @@ -31,8 +31,13 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + const __bjs_arrayCodecCache = new WeakMap(); function __bjs_arrayCodec(elementCodec) { - return { + let codec = __bjs_arrayCodecCache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { for (let i = 0; i < value.length; i++) { elementCodec.lower(value[i]); @@ -51,9 +56,18 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_arrayCodecCache.set(elementCodec, codec); + return codec; } + const __bjs_optionalCodecCache = new WeakMap(); + const __bjs_optionalCodecUndefinedOrCache = new WeakMap(); function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { - return { + const cache = isUndefinedOr ? __bjs_optionalCodecUndefinedOrCache : __bjs_optionalCodecCache; + let codec = cache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const isSome = isUndefinedOr ? value !== undefined : value != null; if (isSome) { @@ -70,9 +84,16 @@ export async function createInstantiator(options, swift) { return elementCodec.lift(); }, }; + cache.set(elementCodec, codec); + return codec; } + const __bjs_dictCodecCache = new WeakMap(); function __bjs_dictCodec(valueCodec) { - return { + let codec = __bjs_dictCodecCache.get(valueCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const keys = Object.keys(value); for (let i = 0; i < keys.length; i++) { @@ -92,6 +113,8 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_dictCodecCache.set(valueCodec, codec); + return codec; } const __bjs_stringCodec = { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js index eef5cdf30..2a8ed684c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js @@ -112,8 +112,13 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + const __bjs_arrayCodecCache = new WeakMap(); function __bjs_arrayCodec(elementCodec) { - return { + let codec = __bjs_arrayCodecCache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { for (let i = 0; i < value.length; i++) { elementCodec.lower(value[i]); @@ -132,9 +137,18 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_arrayCodecCache.set(elementCodec, codec); + return codec; } + const __bjs_optionalCodecCache = new WeakMap(); + const __bjs_optionalCodecUndefinedOrCache = new WeakMap(); function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { - return { + const cache = isUndefinedOr ? __bjs_optionalCodecUndefinedOrCache : __bjs_optionalCodecCache; + let codec = cache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const isSome = isUndefinedOr ? value !== undefined : value != null; if (isSome) { @@ -151,9 +165,16 @@ export async function createInstantiator(options, swift) { return elementCodec.lift(); }, }; + cache.set(elementCodec, codec); + return codec; } + const __bjs_dictCodecCache = new WeakMap(); function __bjs_dictCodec(valueCodec) { - return { + let codec = __bjs_dictCodecCache.get(valueCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const keys = Object.keys(value); for (let i = 0; i < keys.length; i++) { @@ -173,6 +194,8 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_dictCodecCache.set(valueCodec, codec); + return codec; } const __bjs_stringCodec = { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js index 13e9e9015..082aa6c38 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js @@ -106,8 +106,13 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + const __bjs_arrayCodecCache = new WeakMap(); function __bjs_arrayCodec(elementCodec) { - return { + let codec = __bjs_arrayCodecCache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { for (let i = 0; i < value.length; i++) { elementCodec.lower(value[i]); @@ -126,9 +131,18 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_arrayCodecCache.set(elementCodec, codec); + return codec; } + const __bjs_optionalCodecCache = new WeakMap(); + const __bjs_optionalCodecUndefinedOrCache = new WeakMap(); function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { - return { + const cache = isUndefinedOr ? __bjs_optionalCodecUndefinedOrCache : __bjs_optionalCodecCache; + let codec = cache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const isSome = isUndefinedOr ? value !== undefined : value != null; if (isSome) { @@ -145,9 +159,16 @@ export async function createInstantiator(options, swift) { return elementCodec.lift(); }, }; + cache.set(elementCodec, codec); + return codec; } + const __bjs_dictCodecCache = new WeakMap(); function __bjs_dictCodec(valueCodec) { - return { + let codec = __bjs_dictCodecCache.get(valueCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const keys = Object.keys(value); for (let i = 0; i < keys.length; i++) { @@ -167,6 +188,8 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_dictCodecCache.set(valueCodec, codec); + return codec; } const __bjs_stringCodec = { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js index 677b0e16a..7a91ef9d7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js @@ -65,8 +65,13 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + const __bjs_arrayCodecCache = new WeakMap(); function __bjs_arrayCodec(elementCodec) { - return { + let codec = __bjs_arrayCodecCache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { for (let i = 0; i < value.length; i++) { elementCodec.lower(value[i]); @@ -85,9 +90,18 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_arrayCodecCache.set(elementCodec, codec); + return codec; } + const __bjs_optionalCodecCache = new WeakMap(); + const __bjs_optionalCodecUndefinedOrCache = new WeakMap(); function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { - return { + const cache = isUndefinedOr ? __bjs_optionalCodecUndefinedOrCache : __bjs_optionalCodecCache; + let codec = cache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const isSome = isUndefinedOr ? value !== undefined : value != null; if (isSome) { @@ -104,9 +118,16 @@ export async function createInstantiator(options, swift) { return elementCodec.lift(); }, }; + cache.set(elementCodec, codec); + return codec; } + const __bjs_dictCodecCache = new WeakMap(); function __bjs_dictCodec(valueCodec) { - return { + let codec = __bjs_dictCodecCache.get(valueCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const keys = Object.keys(value); for (let i = 0; i < keys.length; i++) { @@ -126,6 +147,8 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_dictCodecCache.set(valueCodec, codec); + return codec; } const __bjs_stringCodec = { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js index 535effde3..42c02479f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js @@ -31,8 +31,13 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + const __bjs_arrayCodecCache = new WeakMap(); function __bjs_arrayCodec(elementCodec) { - return { + let codec = __bjs_arrayCodecCache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { for (let i = 0; i < value.length; i++) { elementCodec.lower(value[i]); @@ -51,9 +56,18 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_arrayCodecCache.set(elementCodec, codec); + return codec; } + const __bjs_optionalCodecCache = new WeakMap(); + const __bjs_optionalCodecUndefinedOrCache = new WeakMap(); function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { - return { + const cache = isUndefinedOr ? __bjs_optionalCodecUndefinedOrCache : __bjs_optionalCodecCache; + let codec = cache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const isSome = isUndefinedOr ? value !== undefined : value != null; if (isSome) { @@ -70,9 +84,16 @@ export async function createInstantiator(options, swift) { return elementCodec.lift(); }, }; + cache.set(elementCodec, codec); + return codec; } + const __bjs_dictCodecCache = new WeakMap(); function __bjs_dictCodec(valueCodec) { - return { + let codec = __bjs_dictCodecCache.get(valueCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const keys = Object.keys(value); for (let i = 0; i < keys.length; i++) { @@ -92,6 +113,8 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_dictCodecCache.set(valueCodec, codec); + return codec; } const __bjs_stringCodec = { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js index 4a8cd2a4d..1a95bcb6e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js @@ -31,8 +31,13 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + const __bjs_arrayCodecCache = new WeakMap(); function __bjs_arrayCodec(elementCodec) { - return { + let codec = __bjs_arrayCodecCache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { for (let i = 0; i < value.length; i++) { elementCodec.lower(value[i]); @@ -51,9 +56,18 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_arrayCodecCache.set(elementCodec, codec); + return codec; } + const __bjs_optionalCodecCache = new WeakMap(); + const __bjs_optionalCodecUndefinedOrCache = new WeakMap(); function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { - return { + const cache = isUndefinedOr ? __bjs_optionalCodecUndefinedOrCache : __bjs_optionalCodecCache; + let codec = cache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const isSome = isUndefinedOr ? value !== undefined : value != null; if (isSome) { @@ -70,9 +84,16 @@ export async function createInstantiator(options, swift) { return elementCodec.lift(); }, }; + cache.set(elementCodec, codec); + return codec; } + const __bjs_dictCodecCache = new WeakMap(); function __bjs_dictCodec(valueCodec) { - return { + let codec = __bjs_dictCodecCache.get(valueCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const keys = Object.keys(value); for (let i = 0; i < keys.length; i++) { @@ -92,6 +113,8 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_dictCodecCache.set(valueCodec, codec); + return codec; } const __bjs_stringCodec = { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js index d46ffb1a8..9fe12ff47 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSValue.js @@ -31,8 +31,13 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + const __bjs_arrayCodecCache = new WeakMap(); function __bjs_arrayCodec(elementCodec) { - return { + let codec = __bjs_arrayCodecCache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { for (let i = 0; i < value.length; i++) { elementCodec.lower(value[i]); @@ -51,9 +56,18 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_arrayCodecCache.set(elementCodec, codec); + return codec; } + const __bjs_optionalCodecCache = new WeakMap(); + const __bjs_optionalCodecUndefinedOrCache = new WeakMap(); function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { - return { + const cache = isUndefinedOr ? __bjs_optionalCodecUndefinedOrCache : __bjs_optionalCodecCache; + let codec = cache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const isSome = isUndefinedOr ? value !== undefined : value != null; if (isSome) { @@ -70,9 +84,16 @@ export async function createInstantiator(options, swift) { return elementCodec.lift(); }, }; + cache.set(elementCodec, codec); + return codec; } + const __bjs_dictCodecCache = new WeakMap(); function __bjs_dictCodec(valueCodec) { - return { + let codec = __bjs_dictCodecCache.get(valueCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const keys = Object.keys(value); for (let i = 0; i < keys.length; i++) { @@ -92,6 +113,8 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_dictCodecCache.set(valueCodec, codec); + return codec; } const __bjs_stringCodec = { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js index 40b5bd079..024ef49c1 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js @@ -31,8 +31,13 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + const __bjs_arrayCodecCache = new WeakMap(); function __bjs_arrayCodec(elementCodec) { - return { + let codec = __bjs_arrayCodecCache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { for (let i = 0; i < value.length; i++) { elementCodec.lower(value[i]); @@ -51,9 +56,18 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_arrayCodecCache.set(elementCodec, codec); + return codec; } + const __bjs_optionalCodecCache = new WeakMap(); + const __bjs_optionalCodecUndefinedOrCache = new WeakMap(); function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { - return { + const cache = isUndefinedOr ? __bjs_optionalCodecUndefinedOrCache : __bjs_optionalCodecCache; + let codec = cache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const isSome = isUndefinedOr ? value !== undefined : value != null; if (isSome) { @@ -70,9 +84,16 @@ export async function createInstantiator(options, swift) { return elementCodec.lift(); }, }; + cache.set(elementCodec, codec); + return codec; } + const __bjs_dictCodecCache = new WeakMap(); function __bjs_dictCodec(valueCodec) { - return { + let codec = __bjs_dictCodecCache.get(valueCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const keys = Object.keys(value); for (let i = 0; i < keys.length; i++) { @@ -92,6 +113,8 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_dictCodecCache.set(valueCodec, codec); + return codec; } const __bjs_stringCodec = { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js index 18f03f8d8..7da962422 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js @@ -31,8 +31,13 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + const __bjs_arrayCodecCache = new WeakMap(); function __bjs_arrayCodec(elementCodec) { - return { + let codec = __bjs_arrayCodecCache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { for (let i = 0; i < value.length; i++) { elementCodec.lower(value[i]); @@ -51,9 +56,18 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_arrayCodecCache.set(elementCodec, codec); + return codec; } + const __bjs_optionalCodecCache = new WeakMap(); + const __bjs_optionalCodecUndefinedOrCache = new WeakMap(); function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { - return { + const cache = isUndefinedOr ? __bjs_optionalCodecUndefinedOrCache : __bjs_optionalCodecCache; + let codec = cache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const isSome = isUndefinedOr ? value !== undefined : value != null; if (isSome) { @@ -70,9 +84,16 @@ export async function createInstantiator(options, swift) { return elementCodec.lift(); }, }; + cache.set(elementCodec, codec); + return codec; } + const __bjs_dictCodecCache = new WeakMap(); function __bjs_dictCodec(valueCodec) { - return { + let codec = __bjs_dictCodecCache.get(valueCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const keys = Object.keys(value); for (let i = 0; i < keys.length; i++) { @@ -92,6 +113,8 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_dictCodecCache.set(valueCodec, codec); + return codec; } const __bjs_stringCodec = { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js index 2745d5a97..f9761419b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js @@ -31,8 +31,13 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + const __bjs_arrayCodecCache = new WeakMap(); function __bjs_arrayCodec(elementCodec) { - return { + let codec = __bjs_arrayCodecCache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { for (let i = 0; i < value.length; i++) { elementCodec.lower(value[i]); @@ -51,9 +56,18 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_arrayCodecCache.set(elementCodec, codec); + return codec; } + const __bjs_optionalCodecCache = new WeakMap(); + const __bjs_optionalCodecUndefinedOrCache = new WeakMap(); function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { - return { + const cache = isUndefinedOr ? __bjs_optionalCodecUndefinedOrCache : __bjs_optionalCodecCache; + let codec = cache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const isSome = isUndefinedOr ? value !== undefined : value != null; if (isSome) { @@ -70,9 +84,16 @@ export async function createInstantiator(options, swift) { return elementCodec.lift(); }, }; + cache.set(elementCodec, codec); + return codec; } + const __bjs_dictCodecCache = new WeakMap(); function __bjs_dictCodec(valueCodec) { - return { + let codec = __bjs_dictCodecCache.get(valueCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const keys = Object.keys(value); for (let i = 0; i < keys.length; i++) { @@ -92,6 +113,8 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_dictCodecCache.set(valueCodec, codec); + return codec; } const __bjs_stringCodec = { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js index 65bf34266..73c93c039 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js @@ -55,8 +55,13 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + const __bjs_arrayCodecCache = new WeakMap(); function __bjs_arrayCodec(elementCodec) { - return { + let codec = __bjs_arrayCodecCache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { for (let i = 0; i < value.length; i++) { elementCodec.lower(value[i]); @@ -75,9 +80,18 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_arrayCodecCache.set(elementCodec, codec); + return codec; } + const __bjs_optionalCodecCache = new WeakMap(); + const __bjs_optionalCodecUndefinedOrCache = new WeakMap(); function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { - return { + const cache = isUndefinedOr ? __bjs_optionalCodecUndefinedOrCache : __bjs_optionalCodecCache; + let codec = cache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const isSome = isUndefinedOr ? value !== undefined : value != null; if (isSome) { @@ -94,9 +108,16 @@ export async function createInstantiator(options, swift) { return elementCodec.lift(); }, }; + cache.set(elementCodec, codec); + return codec; } + const __bjs_dictCodecCache = new WeakMap(); function __bjs_dictCodec(valueCodec) { - return { + let codec = __bjs_dictCodecCache.get(valueCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const keys = Object.keys(value); for (let i = 0; i < keys.length; i++) { @@ -116,6 +137,8 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_dictCodecCache.set(valueCodec, codec); + return codec; } const __bjs_stringCodec = { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js index cbf97bb5e..24f037350 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js @@ -61,8 +61,13 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + const __bjs_arrayCodecCache = new WeakMap(); function __bjs_arrayCodec(elementCodec) { - return { + let codec = __bjs_arrayCodecCache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { for (let i = 0; i < value.length; i++) { elementCodec.lower(value[i]); @@ -81,9 +86,18 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_arrayCodecCache.set(elementCodec, codec); + return codec; } + const __bjs_optionalCodecCache = new WeakMap(); + const __bjs_optionalCodecUndefinedOrCache = new WeakMap(); function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { - return { + const cache = isUndefinedOr ? __bjs_optionalCodecUndefinedOrCache : __bjs_optionalCodecCache; + let codec = cache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const isSome = isUndefinedOr ? value !== undefined : value != null; if (isSome) { @@ -100,9 +114,16 @@ export async function createInstantiator(options, swift) { return elementCodec.lift(); }, }; + cache.set(elementCodec, codec); + return codec; } + const __bjs_dictCodecCache = new WeakMap(); function __bjs_dictCodec(valueCodec) { - return { + let codec = __bjs_dictCodecCache.get(valueCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const keys = Object.keys(value); for (let i = 0; i < keys.length; i++) { @@ -122,6 +143,8 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_dictCodecCache.set(valueCodec, codec); + return codec; } const __bjs_stringCodec = { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js index a5496d4ee..bb0de3d03 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js @@ -36,8 +36,13 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + const __bjs_arrayCodecCache = new WeakMap(); function __bjs_arrayCodec(elementCodec) { - return { + let codec = __bjs_arrayCodecCache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { for (let i = 0; i < value.length; i++) { elementCodec.lower(value[i]); @@ -56,9 +61,18 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_arrayCodecCache.set(elementCodec, codec); + return codec; } + const __bjs_optionalCodecCache = new WeakMap(); + const __bjs_optionalCodecUndefinedOrCache = new WeakMap(); function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { - return { + const cache = isUndefinedOr ? __bjs_optionalCodecUndefinedOrCache : __bjs_optionalCodecCache; + let codec = cache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const isSome = isUndefinedOr ? value !== undefined : value != null; if (isSome) { @@ -75,9 +89,16 @@ export async function createInstantiator(options, swift) { return elementCodec.lift(); }, }; + cache.set(elementCodec, codec); + return codec; } + const __bjs_dictCodecCache = new WeakMap(); function __bjs_dictCodec(valueCodec) { - return { + let codec = __bjs_dictCodecCache.get(valueCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const keys = Object.keys(value); for (let i = 0; i < keys.length; i++) { @@ -97,6 +118,8 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_dictCodecCache.set(valueCodec, codec); + return codec; } const __bjs_stringCodec = { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js index 159d4b616..f603bee2e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js @@ -31,8 +31,13 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + const __bjs_arrayCodecCache = new WeakMap(); function __bjs_arrayCodec(elementCodec) { - return { + let codec = __bjs_arrayCodecCache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { for (let i = 0; i < value.length; i++) { elementCodec.lower(value[i]); @@ -51,9 +56,18 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_arrayCodecCache.set(elementCodec, codec); + return codec; } + const __bjs_optionalCodecCache = new WeakMap(); + const __bjs_optionalCodecUndefinedOrCache = new WeakMap(); function __bjs_optionalCodec(elementCodec, isUndefinedOr = false) { - return { + const cache = isUndefinedOr ? __bjs_optionalCodecUndefinedOrCache : __bjs_optionalCodecCache; + let codec = cache.get(elementCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const isSome = isUndefinedOr ? value !== undefined : value != null; if (isSome) { @@ -70,9 +84,16 @@ export async function createInstantiator(options, swift) { return elementCodec.lift(); }, }; + cache.set(elementCodec, codec); + return codec; } + const __bjs_dictCodecCache = new WeakMap(); function __bjs_dictCodec(valueCodec) { - return { + let codec = __bjs_dictCodecCache.get(valueCodec); + if (codec !== undefined) { + return codec; + } + codec = { lower(value) { const keys = Object.keys(value); for (let i = 0; i < keys.length; i++) { @@ -92,6 +113,8 @@ export async function createInstantiator(options, swift) { return result; }, }; + __bjs_dictCodecCache.set(valueCodec, codec); + return codec; } const __bjs_stringCodec = { From bf00750a572565108455bb6b368d9d65672213a1 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Tue, 11 Aug 2026 23:44:15 +0200 Subject: [PATCH 42/50] BridgeJS: Qualify generated JS helper names by module --- .../Sources/BridgeJSCore/ExportSwift.swift | 12 - .../Sources/BridgeJSLink/BridgeJSLink.swift | 103 ++++----- .../Sources/BridgeJSLink/JSGlueGen.swift | 205 ++++++++---------- .../BridgeJSLink/JSIntrinsicRegistry.swift | 14 -- .../BridgeJSSkeleton/BridgeJSSkeleton.swift | 43 +--- .../NamedCodecHelperTests.swift | 105 --------- .../__Snapshots__/BridgeJSLinkTests/Alias.js | 34 +-- .../BridgeJSLinkTests/ArrayTypes.js | 86 ++++---- .../__Snapshots__/BridgeJSLinkTests/Async.js | 58 ++--- .../AsyncAssociatedValueEnum.js | 14 +- .../BridgeJSLinkTests/ClassWithNestedTypes.js | 14 +- .../BridgeJSLinkTests/DefaultParameters.js | 42 ++-- .../BridgeJSLinkTests/DictionaryTypes.js | 30 +-- .../BridgeJSLinkTests/DocComments.js | 10 +- .../BridgeJSLinkTests/EnumAssociatedValue.js | 180 +++++++-------- .../EnumAssociatedValueImport.js | 18 +- .../BridgeJSLinkTests/EnumRawType.js | 12 +- .../BridgeJSLinkTests/GenericImports.js | 45 ++-- .../ImportedTypeInExportedInterface.js | 34 +-- .../BridgeJSLinkTests/JSNameOverride.js | 16 +- .../BridgeJSLinkTests/Namespaces.Global.js | 6 +- .../BridgeJSLinkTests/Namespaces.js | 6 +- .../BridgeJSLinkTests/NestedType.js | 20 +- .../BridgeJSLinkTests/Optionals.js | 10 +- .../BridgeJSLinkTests/Protocol.js | 42 ++-- .../StaticFunctions.Global.js | 10 +- .../BridgeJSLinkTests/StaticFunctions.js | 10 +- .../StructWithNestedTypes.js | 48 ++-- .../BridgeJSLinkTests/SwiftClosure.js | 70 +++--- .../BridgeJSLinkTests/SwiftStruct.js | 112 +++++----- .../BridgeJSLinkTests/SwiftStructImports.js | 26 +-- .../BridgeJSLinkTests/UnsafePointer.js | 16 +- Plugins/PackageToJS/Templates/instantiate.js | 2 - .../JavaScriptKit/BridgeJSIntrinsics.swift | 37 +--- 34 files changed, 626 insertions(+), 864 deletions(-) delete mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/NamedCodecHelperTests.swift diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift index 1508363c2..55b5889fe 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ExportSwift.swift @@ -92,8 +92,6 @@ public class ExportSwift { } withSpan("Render Generic Bridgeable Conformances") { [self] in - // Emitted unconditionally: a module cannot know whether a dependent - // module passes its types to a generic imported function. let genericConformanceCodegen = GenericConformanceCodegen() for entry in skeleton.genericBridgeableTypeEntries { decls.append(contentsOf: genericConformanceCodegen.renderConformance(typeName: entry.swiftName)) @@ -886,8 +884,6 @@ public class ExportSwift { // MARK: - GenericConformanceCodegen -/// Renders `BridgedSwiftGenericBridgeable` conformances for `@JS` types so they -/// can be used as the generic argument of a generic imported `@JSFunction`. struct GenericConformanceCodegen { func renderConformance(typeName: String) -> [DeclSyntax] { let printer = CodeFragmentPrinter() @@ -904,14 +900,6 @@ struct GenericConformanceCodegen { // MARK: - GenericTypeRegistrationCodegen -/// Renders the `bjs__register_type_handles` wasm export: it lowers each -/// registered type's `bridgeJSTypeID` into a buffer, in the canonical order of -/// `BridgeJSSkeleton.typeRegistrationEntries`, and passes it to the JS import -/// hook of the same name, which pairs the IDs with its codec array by index. -/// -/// Only the module's own `@JS` types are listed; the core (primitive) handles are -/// registered once by the JavaScriptKit library itself -/// (`_bjs_core_register_type_handles`). public struct GenericTypeRegistrationCodegen { public init() {} diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index 5fd37437f..8b46af1b4 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -348,8 +348,6 @@ public struct BridgeJSLink { declarations.append(" return;") declarations.append(" }") declarations.append(" __bjs_typeHandlesRegistered = true;") - // The core (primitive) handles live in the JavaScriptKit library, so - // they are registered once here rather than by every module. declarations.append( " \(JSGlueVariableScope.reservedInstance).exports[\"\(ABINameGenerator.coreTypeRegistrationFunctionName)\"]();" ) @@ -403,7 +401,6 @@ public struct BridgeJSLink { printer.write(lines: lines) } - /// A print context detached from any thunk, used for codec literal emission. private func makeCodecPrintContext(printer: CodeFragmentPrinter) -> IntrinsicJSFragment.PrintCodeContext { IntrinsicJSFragment.PrintCodeContext( scope: JSGlueVariableScope(intrinsicRegistry: intrinsicRegistry), @@ -413,16 +410,10 @@ public struct BridgeJSLink { ) } - /// Returns the module-scope codec helper for one bridgeable type, declaring - /// it if this is the first reference. - /// - /// The registration table and the container combinators' element positions - /// go through the same helper, so a type's stack ABI is described once. private func genericCodecReference(type: BridgeType, into printer: CodeFragmentPrinter) throws -> String { try ContainerCodecJS.codecExpression(for: type, context: makeCodecPrintContext(printer: printer)) } - /// Pairs the type IDs Swift pushed with codecs in the matching skeleton order. private func writeTypeHandleRegistrationBody(into printer: CodeFragmentPrinter) { printer.write( "const typeIds = new Int32Array(\(JSGlueVariableScope.reservedMemory).buffer, base >>> 0, count >>> 0);" @@ -434,11 +425,6 @@ public struct BridgeJSLink { printer.write("}") } - /// Installs the `bjs_core_register_type_handles` hook. The core handles are - /// owned by the JavaScriptKit library rather than by generated code, so the - /// wasm import exists in every binary that links JavaScriptKit and the hook - /// is always installed; without generics anywhere in the build it is a no-op - /// and the registration export is never called. private func generateCoreTypeRegistrationHook(into printer: CodeFragmentPrinter) throws { let hookName = ABINameGenerator.coreTypeRegistrationFunctionName guard hasGenerics else { @@ -448,8 +434,6 @@ public struct BridgeJSLink { try ContainerCodecJS.registerPrimitiveCodecs(context: makeCodecPrintContext(printer: printer)) printer.write("bjs[\"\(hookName)\"] = function(base, count) {") printer.indent { - // Same canonical order as `_bjs_core_register_type_handles` in the - // JavaScriptKit library. printer.write("const codecs = [") printer.indent { for primitive in BridgeType.genericBridgeablePrimitives { @@ -462,10 +446,6 @@ public struct BridgeJSLink { printer.write("}") } - /// Installs the per-module `bjs__register_type_handles` import - /// hooks. A module with a registration function always carries the wasm - /// import, so a hook is always installed; without generics anywhere in the - /// build it is a no-op and the registration export is never called. private func generateTypeRegistrationHooks(into printer: CodeFragmentPrinter) throws { try generateCoreTypeRegistrationHook(into: printer) for skeleton in skeletons { @@ -477,7 +457,6 @@ public struct BridgeJSLink { } printer.write("bjs[\"\(hookName)\"] = function(base, count) {") try printer.indent { - // Same order as the module's Swift registration function. let codecNames = try moduleEntries.map { try genericCodecReference(type: $0.bridgeType, into: printer) } @@ -496,7 +475,9 @@ public struct BridgeJSLink { private func generateAddImports(needsImportsObject: Bool) throws -> CodeFragmentPrinter { let printer = CodeFragmentPrinter() - let allStructs = skeletons.compactMap { $0.exported?.structs }.flatMap { $0 } + let allStructs = skeletons.flatMap { unified in + (unified.exported?.structs ?? []).map { (moduleName: unified.moduleName, structDef: $0) } + } printer.write("return {") try printer.indent { printer.write(lines: [ @@ -644,11 +625,12 @@ public struct BridgeJSLink { } printer.write("}") if !allStructs.isEmpty { - for structDef in allStructs { + for (moduleName, structDef) in allStructs { + let key = HelperNaming.type(module: moduleName, swiftName: structDef.swiftCallName) printer.write("bjs[\"swift_js_struct_lower_\(structDef.abiName)\"] = function(objectId) {") printer.indent { printer.write( - "\(JSGlueVariableScope.reservedStructHelpers).\(structDef.abiName).lower(\(JSGlueVariableScope.reservedSwift).memory.getObject(objectId));" + "\(JSGlueVariableScope.reservedStructHelpers).\(key).lower(\(JSGlueVariableScope.reservedSwift).memory.getObject(objectId));" ) } printer.write("}") @@ -656,7 +638,7 @@ public struct BridgeJSLink { printer.write("bjs[\"swift_js_struct_lift_\(structDef.abiName)\"] = function() {") printer.indent { printer.write( - "const value = \(JSGlueVariableScope.reservedStructHelpers).\(structDef.abiName).lift();" + "const value = \(JSGlueVariableScope.reservedStructHelpers).\(key).lift();" ) printer.write("return \(JSGlueVariableScope.reservedSwift).memory.retain(value);") } @@ -1229,12 +1211,18 @@ public struct BridgeJSLink { let bodyPrinter = CodeFragmentPrinter() let allStructs = exportedSkeletons.flatMap { $0.structs } - for structDef in allStructs { + for (moduleName, structDef) in skeletons.flatMap({ unified in + (unified.exported?.structs ?? []).map { (unified.moduleName, $0) } + }) { let structPrinter = CodeFragmentPrinter() let structScope = JSGlueVariableScope(intrinsicRegistry: intrinsicRegistry) - let fragment = IntrinsicJSFragment.structHelper(structDefinition: structDef, allStructs: allStructs) + let fragment = IntrinsicJSFragment.structHelper( + structDefinition: structDef, + allStructs: allStructs, + moduleName: moduleName + ) _ = try fragment.printCode( - [structDef.abiName], + [], IntrinsicJSFragment.PrintCodeContext( scope: structScope, printer: structPrinter, @@ -1245,13 +1233,16 @@ public struct BridgeJSLink { bodyPrinter.write(lines: structPrinter.lines) } - let allAssocEnums = exportedSkeletons.flatMap { - $0.enums.filter { $0.enumType == .associatedValue } - } - for enumDef in allAssocEnums { + for (moduleName, enumDef) in skeletons.flatMap({ unified in + (unified.exported?.enums ?? []).filter { $0.enumType == .associatedValue } + .map { (unified.moduleName, $0) } + }) { let enumPrinter = CodeFragmentPrinter() let enumScope = JSGlueVariableScope(intrinsicRegistry: intrinsicRegistry) - let fragment = IntrinsicJSFragment.associatedValueEnumHelperFactory(enumDefinition: enumDef) + let fragment = IntrinsicJSFragment.associatedValueEnumHelperFactory( + enumDefinition: enumDef, + moduleName: moduleName + ) _ = try fragment.printCode( [enumDef.valuesName], IntrinsicJSFragment.PrintCodeContext( @@ -1271,13 +1262,6 @@ public struct BridgeJSLink { printer.nextLine() } - // The named codec helpers come after the intrinsics because they are - // built out of the combinators and the primitive codec table, and - // before everything that uses them: they are hoisted here so that no - // call site ever composes a codec. Helpers that delegate to the - // `structHelpers` / `enumHelpers` tables only read those tables when - // called, so declaring them ahead of the tables being populated is - // fine. if intrinsicRegistry.hasNamedCodecs { printer.write(lines: intrinsicRegistry.emitNamedCodecLines()) printer.nextLine() @@ -1380,12 +1364,6 @@ public struct BridgeJSLink { return (outputJs, outputDts) } - /// Maps every type name a `BridgeType` can carry to the module that declares - /// it, so identifiers minted from type names can be module-qualified. - /// - /// A name declared by two modules is a pre-existing ambiguity in the - /// skeleton format (`BridgeType` carries only the name), so the first - /// declaration wins, which keeps the output deterministic. private func collectTypeOwnerModules() -> [String: String] { var result: [String: String] = [:] func record(_ name: String, _ moduleName: String) { @@ -1399,6 +1377,7 @@ public struct BridgeJSLink { for structDef in skeleton.structs { record(structDef.name, moduleName) record(structDef.abiName, moduleName) + record(structDef.swiftCallName, moduleName) } for klass in skeleton.classes { record(klass.name, moduleName) @@ -1407,16 +1386,12 @@ public struct BridgeJSLink { for enumDef in skeleton.enums { record(enumDef.name, moduleName) record(enumDef.abiName, moduleName) + record(enumDef.swiftCallName, moduleName) } for protocolDef in skeleton.protocols { record(protocolDef.name, moduleName) } } - for file in unified.imported?.children ?? [] { - for type in file.types { - record(type.name, moduleName) - } - } } return result } @@ -1424,12 +1399,13 @@ public struct BridgeJSLink { private func enumHelperAssignments() -> CodeFragmentPrinter { let printer = CodeFragmentPrinter() - for skeleton in skeletons.compactMap(\.exported) { + for unified in skeletons { + guard let skeleton = unified.exported else { continue } for enumDef in skeleton.enums where enumDef.enumType == .associatedValue { - printer.write( - "const \(enumDef.name)Helpers = __bjs_create\(enumDef.valuesName)Helpers();" - ) - printer.write("\(JSGlueVariableScope.reservedEnumHelpers).\(enumDef.name) = \(enumDef.name)Helpers;") + let key = HelperNaming.type(module: unified.moduleName, swiftName: enumDef.swiftCallName) + let local = HelperNaming.helperConstant(key) + printer.write("const \(local) = \(HelperNaming.enumHelperFactory(key))();") + printer.write("\(JSGlueVariableScope.reservedEnumHelpers).\(key) = \(local);") printer.nextLine() } } @@ -1440,14 +1416,13 @@ public struct BridgeJSLink { private func structHelperAssignments() -> CodeFragmentPrinter { let printer = CodeFragmentPrinter() - for skeleton in skeletons.compactMap(\.exported) { + for unified in skeletons { + guard let skeleton = unified.exported else { continue } for structDef in skeleton.structs { - printer.write( - "const \(structDef.abiName)Helpers = __bjs_create\(structDef.abiName)Helpers();" - ) - printer.write( - "\(JSGlueVariableScope.reservedStructHelpers).\(structDef.abiName) = \(structDef.abiName)Helpers;" - ) + let key = HelperNaming.type(module: unified.moduleName, swiftName: structDef.swiftCallName) + let local = HelperNaming.helperConstant(key) + printer.write("const \(local) = \(HelperNaming.structHelperFactory(key))();") + printer.write("\(JSGlueVariableScope.reservedStructHelpers).\(key) = \(local);") printer.nextLine() } } @@ -2593,8 +2568,6 @@ extension BridgeJSLink { func declareGenericCodecs(genericParameters: [String]) { if !genericParameters.isEmpty { - // Generic call sites instantiate the shared container codec - // combinators with the codecs resolved from type IDs. ContainerCodecJS.registerCombinators(scope: scope) } for genericParam in genericParameters { diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift index 060f4f507..d35c1ed10 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift @@ -102,13 +102,10 @@ final class JSGlueVariableScope { try intrinsicRegistry.register(name: name, build: build) } - /// Registers a module-scope `{ lower, lift }` codec helper shared by every - /// site that needs a codec for the same type shape. func registerNamedCodec(_ name: String, build: (CodeFragmentPrinter) throws -> Void) rethrows { try intrinsicRegistry.registerNamedCodec(name: name, build: build) } - /// The module declaring `typeName`, when the link step knows it. func moduleName(declaringType typeName: String) -> String? { intrinsicRegistry.typeOwnerModules[typeName] } @@ -119,6 +116,48 @@ final class JSGlueVariableScope { } +extension JSGlueVariableScope { + func helperKey(forTypeNamed fullName: String) -> String { + HelperNaming.type( + module: moduleName(declaringType: fullName), + swiftName: fullName + ) + } +} + +enum HelperNaming { + static func identifierComponent(_ name: String) -> String { + name.utf8.map { byte in + switch byte { + case 48...57, 65...90, 97...122: + return String(UnicodeScalar(byte)) + default: + return "_\(String(byte, radix: 16))_" + } + }.joined() + } + + static func type(module: String?, swiftName: String) -> String { + let module = module.map { "M\($0.utf8.count)\(identifierComponent($0))" } ?? "" + let type = swiftName.split(separator: ".").map { component in + "T\(component.utf8.count)\(identifierComponent(String(component)))" + }.joined() + return module + type + } + + static func structHelperFactory(_ qualifiedKey: String) -> String { + "__bjs_createStructHelpers_\(qualifiedKey)" + } + + static func enumHelperFactory(_ qualifiedKey: String) -> String { + "__bjs_createEnumHelpers_\(qualifiedKey)" + } + + static func helperConstant(_ qualifiedKey: String) -> String { + "__bjs_helpers_\(qualifiedKey)" + } +} + extension JSGlueVariableScope { // MARK: Parameter @@ -160,9 +199,6 @@ extension JSGlueVariableScope { } enum GenericJSCodegen { - /// Wraps a bare element codec into the codec for the wrapped form (`[T]`, - /// `T?`, `[String: T]`) used at a generic call site, or `nil` when the type - /// is not a generic reference. static func genericCodecExpression(type: BridgeType, codec: String) -> String? { switch type { case .generic: return codec @@ -182,9 +218,6 @@ enum GenericJSCodegen { genericCodecExpression(type: type, codec: codec).map { "\($0).lift()" } } - /// Generic-only runtime: resolves a wasm-side type ID to the codec - /// registered for it. The container codec combinators themselves live in - /// `ContainerCodecJS` and are shared with the non-generic bridging paths. static func runtimeHelperDeclarations() -> [String] { let codecByTypeId = JSGlueVariableScope.reservedCodecByTypeId return [ @@ -200,28 +233,16 @@ enum GenericJSCodegen { } } -/// Shared `{ lower, lift }` codec codegen: each container's stack ABI is -/// described once by a combinator and instantiated with an element codec by -/// both the generic and non-generic paths. Emitted lazily via the intrinsic -/// registry, so builds that bridge no containers pay nothing. enum ContainerCodecJS { static let arrayCodec = "__bjs_arrayCodec" static let optionalCodec = "__bjs_optionalCodec" static let dictCodec = "__bjs_dictCodec" - /// Prefix of the module-scope codec helper `const`s. static let namedCodecPrefix = "__bjs_codec_" private static let combinatorIntrinsicName = "containerCodecCombinators" private static let primitiveCodecIntrinsicName = "containerPrimitiveCodecs" - /// The single description of each container shape's stack ABI. - /// - /// The combinators memoize per element codec object. Statically known - /// compositions are hoisted into module-scope `const`s and so instantiate a - /// combinator only once, but a generic call site resolves its element codec - /// from a runtime type ID and cannot be hoisted; memoizing keeps those call - /// sites from allocating a fresh codec on every call. static func combinatorDeclarations() -> [String] { let i32 = JSGlueVariableScope.reservedI32Stack let stringCodec = JSGlueVariableScope.reservedStringCodec @@ -254,10 +275,6 @@ enum ContainerCodecJS { " \(arrayCodec)Cache.set(elementCodec, codec);", " return codec;", "}", - // `isUndefinedOr` selects the `JSUndefinedOr` flavor: `null` is then a - // present value and absence surfaces as `undefined` instead of `null`. - // The two flavors are cached separately because they differ in - // behavior, not just in the element codec. "const \(optionalCodec)Cache = new WeakMap();", "const \(optionalCodec)UndefinedOrCache = new WeakMap();", "function \(optionalCodec)(elementCodec, isUndefinedOr = false) {", @@ -331,13 +348,9 @@ enum ContainerCodecJS { } } - /// Emits `__bjs_stringCodec` and the `__bjs_primitiveCodecs` table shared - /// by combinator instantiations and the generic type-handle registration. static func registerPrimitiveCodecs(context: IntrinsicJSFragment.PrintCodeContext) throws { try context.scope.registerIntrinsic(primitiveCodecIntrinsicName) { printer in let stringCodec = JSGlueVariableScope.reservedStringCodec - // The String codec is named so the dictionary codec combinator can - // lower/lift keys through it. try writeCodecLiteral( type: .string, into: printer, @@ -365,9 +378,6 @@ enum ContainerCodecJS { } } - /// Emits a `{ lower, lift }` codec literal for one bridgeable type. - /// `prefix` is prepended to the opening brace (e.g. an assignment) and - /// `suffix` is appended to the closing brace (e.g. `","` in an object). static func writeCodecLiteral( type: BridgeType, into printer: CodeFragmentPrinter, @@ -397,22 +407,11 @@ enum ContainerCodecJS { printer.write("}\(suffix)") } - /// A codec that is reachable by name from module scope. - /// - /// `token` is the stable, module-qualified spelling of the type shape; codec - /// names for compositions are derived from their elements' tokens, so the - /// whole naming scheme inherits module qualification from its leaves. struct NamedCodec { let expression: String let token: String } - /// Returns a JS expression evaluating to the `{ lower, lift }` codec for one - /// element type, registering the shared codec runtime as needed. - /// - /// Every codec is a module-scope `const`, so a call site never builds one: - /// the same type shape resolves to the same helper wherever it appears, - /// including the generic type-handle registration table. static func codecExpression( for elementType: BridgeType, context: IntrinsicJSFragment.PrintCodeContext @@ -451,7 +450,6 @@ enum ContainerCodecJS { context: context ) case .string, .rawValueEnum(_, .string): - // A string-backed raw value enum bridges exactly as its raw value. return NamedCodec(expression: JSGlueVariableScope.reservedStringCodec, token: "String") default: if let token = BridgeType.genericBridgeablePrimitives.first(where: { $0.type == type })?.token { @@ -464,8 +462,6 @@ enum ContainerCodecJS { } } - /// Declares (once) a module-scope `const` holding a container combinator - /// instantiated with an already-declared element codec. private static func composedCodec( token: String, factory: String, @@ -478,21 +474,12 @@ enum ContainerCodecJS { return NamedCodec(expression: name, token: token) } - /// Declares (once) a module-scope `const` holding the codec for a type that - /// is not a container: primitives are handled by the shared table, so this - /// covers `@JS` structs, enums, classes, `JSObject`, protocols and friends. - /// - /// The body comes from ``writeCodecLiteral``, the same emitter the generic - /// type-handle registration uses, so both reference one helper per type. private static func leafCodec( for type: BridgeType, context: IntrinsicJSFragment.PrintCodeContext ) throws -> NamedCodec { let token = leafToken(for: type, scope: context.scope) let name = "\(namedCodecPrefix)\(token)" - // The helper lives at module scope, outside `createExports`, so exported - // Swift classes are not in lexical scope here and must be reached - // through `_exports`. let hoistedContext = context.with(\.hasDirectAccessToSwiftClass, false) try context.scope.registerNamedCodec(name) { printer in try writeCodecLiteral( @@ -506,26 +493,18 @@ enum ContainerCodecJS { return NamedCodec(expression: name, token: token) } - /// The module-qualified token identifying a non-container type shape. - /// - /// Types declared by a `@JS` module are qualified with the declaring module - /// so two modules declaring the same type name do not mint the same helper. private static func leafToken(for type: BridgeType, scope: JSGlueVariableScope) -> String { - func sanitized(_ name: String) -> String { - String(name.map { $0.isLetter || $0.isNumber || $0 == "_" ? $0 : "_" }) + func identifierComponent(_ name: String) -> String { + HelperNaming.identifierComponent(name) } func qualified(_ name: String) -> String { - let base = sanitized(name) - guard let module = scope.moduleName(declaringType: name) ?? scope.moduleName(declaringType: base) else { - return base - } - return "\(sanitized(module))_\(base)" + scope.helperKey(forTypeNamed: name) } switch type { case .jsObject(nil): return "JSObject" case .jsObject(let name?): - return qualified(name) + return identifierComponent(name) case .swiftStruct(let name), .swiftHeapObject(let name), .swiftProtocol(let name), @@ -535,7 +514,7 @@ enum ContainerCodecJS { .namespaceEnum(let name): return qualified(name) default: - return sanitized(type.mangleTypeName) + return identifierComponent(type.mangleTypeName) } } } @@ -1017,12 +996,13 @@ struct IntrinsicJSFragment: Sendable { // MARK: - Associated Enum Fragments - static func associatedEnumLowerParameter(enumBase: String) -> IntrinsicJSFragment { + static func associatedEnumLowerParameter(enumName: String) -> IntrinsicJSFragment { IntrinsicJSFragment( parameters: ["value"], printCode: { arguments, context in let (scope, printer) = (context.scope, context.printer) let value = arguments[0] + let enumBase = scope.helperKey(forTypeNamed: enumName) let caseIdName = scope.variable("\(value)CaseId") printer.write( "const \(caseIdName) = \(JSGlueVariableScope.reservedEnumHelpers).\(enumBase).lower(\(value));" @@ -1032,11 +1012,12 @@ struct IntrinsicJSFragment: Sendable { ) } - static func associatedEnumLiftReturn(enumBase: String) -> IntrinsicJSFragment { + static func associatedEnumLiftReturn(enumName: String) -> IntrinsicJSFragment { IntrinsicJSFragment( parameters: [], printCode: { _, context in let (scope, printer) = (context.scope, context.printer) + let enumBase = scope.helperKey(forTypeNamed: enumName) let retName = scope.variable("ret") printer.write( "const \(retName) = \(JSGlueVariableScope.reservedEnumHelpers).\(enumBase).lift(\(scope.popI32()));" @@ -1298,12 +1279,12 @@ struct IntrinsicJSFragment: Sendable { fullName: String, kind: JSOptionalKind ) -> IntrinsicJSFragment { - let base = fullName.components(separatedBy: ".").last ?? fullName let absenceLiteral = kind.absenceLiteral return IntrinsicJSFragment( parameters: [], printCode: { _, context in let (scope, printer) = (context.scope, context.printer) + let base = scope.helperKey(forTypeNamed: fullName) let resultVar = scope.variable("optResult") let tagVar = scope.variable("tag") printer.write("const \(tagVar) = \(scope.popI32());") @@ -1648,11 +1629,9 @@ struct IntrinsicJSFragment: Sendable { return try .optionalLowerParameter(wrappedType: wrappedType, kind: kind) case .rawValueEnum(_, .string): return .stringLowerParameter case .associatedValueEnum(let fullName): - let base = fullName.components(separatedBy: ".").last ?? fullName - return .associatedEnumLowerParameter(enumBase: base) + return .associatedEnumLowerParameter(enumName: fullName) case .swiftStruct(let fullName): - let base = fullName.replacingOccurrences(of: ".", with: "_") - return swiftStructLowerParameter(structBase: base) + return swiftStructLowerParameter(structName: fullName) case .closure: return IntrinsicJSFragment( parameters: ["closure"], @@ -1708,11 +1687,9 @@ struct IntrinsicJSFragment: Sendable { return try .optionalLiftReturn(wrappedType: wrappedType, kind: kind) case .rawValueEnum(_, .string): return .stringLiftReturn case .associatedValueEnum(let fullName): - let base = fullName.components(separatedBy: ".").last ?? fullName - return .associatedEnumLiftReturn(enumBase: base) + return .associatedEnumLiftReturn(enumName: fullName) case .swiftStruct(let fullName): - let base = fullName.replacingOccurrences(of: ".", with: "_") - return swiftStructLiftReturn(structBase: base) + return swiftStructLiftReturn(structName: fullName) case .closure: return IntrinsicJSFragment( parameters: ["funcRef"], @@ -1771,11 +1748,11 @@ struct IntrinsicJSFragment: Sendable { return try .optionalLiftParameter(wrappedType: wrappedType, kind: kind, context: context) case .rawValueEnum(_, .string): return .stringLiftParameter case .associatedValueEnum(let fullName): - let base = fullName.components(separatedBy: ".").last ?? fullName return IntrinsicJSFragment( parameters: ["caseId"], printCode: { arguments, context in let (scope, printer) = (context.scope, context.printer) + let base = scope.helperKey(forTypeNamed: fullName) let caseId = arguments[0] let resultVar = scope.variable("enumValue") printer.write( @@ -1785,11 +1762,11 @@ struct IntrinsicJSFragment: Sendable { } ) case .swiftStruct(let fullName): - let base = fullName.replacingOccurrences(of: ".", with: "_") return IntrinsicJSFragment( parameters: [], printCode: { arguments, context in let (scope, printer) = (context.scope, context.printer) + let base = scope.helperKey(forTypeNamed: fullName) let resultVar = scope.variable("structValue") printer.write( "const \(resultVar) = \(JSGlueVariableScope.reservedStructHelpers).\(base).lift();" @@ -1871,11 +1848,11 @@ struct IntrinsicJSFragment: Sendable { // MARK: - Enums Payload Fragments static func associatedValueLowerReturn(fullName: String) -> IntrinsicJSFragment { - let base = fullName.components(separatedBy: ".").last ?? fullName return IntrinsicJSFragment( parameters: ["value"], printCode: { arguments, context in let (scope, printer) = (context.scope, context.printer) + let base = scope.helperKey(forTypeNamed: fullName) let value = arguments[0] let caseIdVar = scope.variable("caseId") printer.write( @@ -1914,17 +1891,20 @@ struct IntrinsicJSFragment: Sendable { ) } - /// Generates the enum helper factory function (lower/lift closures). - /// This is placed inside `createInstantiator` alongside struct helpers, - /// so it has access to `_exports` for class references. - static func associatedValueEnumHelperFactory(enumDefinition: ExportedEnum) -> IntrinsicJSFragment { + static func associatedValueEnumHelperFactory( + enumDefinition: ExportedEnum, + moduleName: String + ) -> IntrinsicJSFragment { + let factoryName = HelperNaming.enumHelperFactory( + HelperNaming.type(module: moduleName, swiftName: enumDefinition.swiftCallName) + ) return IntrinsicJSFragment( parameters: ["enumName"], printCode: { arguments, context in let (scope, printer) = (context.scope, context.printer) let enumName = arguments[0] - printer.write("const __bjs_create\(enumName)Helpers = () => ({") + printer.write("const \(factoryName) = () => ({") try printer.indent { printer.write("lower: (value) => {") try printer.indent { @@ -2117,11 +2097,12 @@ struct IntrinsicJSFragment: Sendable { } } - private static func swiftStructLower(structBase: String) -> IntrinsicJSFragment { + private static func swiftStructLower(structName: String) -> IntrinsicJSFragment { IntrinsicJSFragment( parameters: ["value"], printCode: { arguments, context in let printer = context.printer + let structBase = context.scope.helperKey(forTypeNamed: structName) let value = arguments[0] printer.write( "\(JSGlueVariableScope.reservedStructHelpers).\(structBase).lower(\(value));" @@ -2132,18 +2113,19 @@ struct IntrinsicJSFragment: Sendable { } static func swiftStructLowerReturn(fullName: String) -> IntrinsicJSFragment { - swiftStructLower(structBase: fullName.replacingOccurrences(of: ".", with: "_")) + swiftStructLower(structName: fullName) } - static func swiftStructLowerParameter(structBase: String) -> IntrinsicJSFragment { - swiftStructLower(structBase: structBase) + static func swiftStructLowerParameter(structName: String) -> IntrinsicJSFragment { + swiftStructLower(structName: structName) } - static func swiftStructLiftReturn(structBase: String) -> IntrinsicJSFragment { + static func swiftStructLiftReturn(structName: String) -> IntrinsicJSFragment { return IntrinsicJSFragment( parameters: [], printCode: { arguments, context in let (scope, printer) = (context.scope, context.printer) + let structBase = scope.helperKey(forTypeNamed: structName) let resultVar = scope.variable("structValue") printer.write( "const \(resultVar) = \(JSGlueVariableScope.reservedStructHelpers).\(structBase).lift();" @@ -2155,7 +2137,6 @@ struct IntrinsicJSFragment: Sendable { // MARK: - Array Helpers - /// Lowers an array from JS to Swift through the shared array codec combinator static func arrayLower(elementType: BridgeType) throws -> IntrinsicJSFragment { return IntrinsicJSFragment( parameters: ["arr"], @@ -2167,7 +2148,6 @@ struct IntrinsicJSFragment: Sendable { ) } - /// Lowers a dictionary from JS to Swift through the shared dictionary codec combinator static func dictionaryLower(valueType: BridgeType) throws -> IntrinsicJSFragment { return IntrinsicJSFragment( parameters: ["dict"], @@ -2179,7 +2159,6 @@ struct IntrinsicJSFragment: Sendable { ) } - /// Lifts an array from Swift to JS through the shared array codec combinator static func arrayLift(elementType: BridgeType) throws -> IntrinsicJSFragment { return IntrinsicJSFragment( parameters: [], @@ -2192,7 +2171,6 @@ struct IntrinsicJSFragment: Sendable { ) } - /// Lifts a dictionary from Swift to JS through the shared dictionary codec combinator static func dictionaryLift(valueType: BridgeType) throws -> IntrinsicJSFragment { return IntrinsicJSFragment( parameters: [], @@ -2270,11 +2248,11 @@ struct IntrinsicJSFragment: Sendable { } ) case .swiftStruct(let fullName): - let structBase = fullName.replacingOccurrences(of: ".", with: "_") return IntrinsicJSFragment( parameters: [], printCode: { arguments, context in let (scope, printer) = (context.scope, context.printer) + let structBase = scope.helperKey(forTypeNamed: fullName) let resultVar = scope.variable("struct") printer.write( "const \(resultVar) = \(JSGlueVariableScope.reservedStructHelpers).\(structBase).lift();" @@ -2283,11 +2261,11 @@ struct IntrinsicJSFragment: Sendable { } ) case .associatedValueEnum(let fullName): - let base = fullName.components(separatedBy: ".").last ?? fullName return IntrinsicJSFragment( parameters: [], printCode: { arguments, context in let (scope, printer) = (context.scope, context.printer) + let base = scope.helperKey(forTypeNamed: fullName) let resultVar = scope.variable("enumValue") printer.write( "const \(resultVar) = \(JSGlueVariableScope.reservedEnumHelpers).\(base).lift(\(scope.popI32()));" @@ -2392,11 +2370,11 @@ struct IntrinsicJSFragment: Sendable { } ) case .swiftStruct(let fullName): - let structBase = fullName.replacingOccurrences(of: ".", with: "_") return IntrinsicJSFragment( parameters: ["value"], printCode: { arguments, context in let printer = context.printer + let structBase = context.scope.helperKey(forTypeNamed: fullName) let value = arguments[0] printer.write( "\(JSGlueVariableScope.reservedStructHelpers).\(structBase).lower(\(value));" @@ -2406,11 +2384,11 @@ struct IntrinsicJSFragment: Sendable { ) case .associatedValueEnum(let fullName): - let base = fullName.components(separatedBy: ".").last ?? fullName return IntrinsicJSFragment( parameters: ["value"], printCode: { arguments, context in let (scope, printer) = (context.scope, context.printer) + let base = scope.helperKey(forTypeNamed: fullName) let value = arguments[0] let caseIdVar = scope.variable("caseId") printer.write( @@ -2453,8 +2431,6 @@ struct IntrinsicJSFragment: Sendable { } } - /// Lift an optional from the stack (isSome flag, then conditional payload) - /// through the shared optional codec combinator. private static func optionalElementRaiseFragment( wrappedType: BridgeType, kind: JSOptionalKind @@ -2473,9 +2449,6 @@ struct IntrinsicJSFragment: Sendable { ) } - /// Lower an optional value to the stack using the **conditional** protocol - /// (push isSome flag, then conditionally push the payload) through the - /// shared optional codec combinator. private static func optionalElementLowerFragment( wrappedType: BridgeType, kind: JSOptionalKind @@ -2495,16 +2468,22 @@ struct IntrinsicJSFragment: Sendable { // MARK: - Struct Helpers - static func structHelper(structDefinition: ExportedStruct, allStructs: [ExportedStruct]) -> IntrinsicJSFragment { + static func structHelper( + structDefinition: ExportedStruct, + allStructs: [ExportedStruct], + moduleName: String + ) -> IntrinsicJSFragment { + let factoryName = HelperNaming.structHelperFactory( + HelperNaming.type(module: moduleName, swiftName: structDefinition.swiftCallName) + ) return IntrinsicJSFragment( - parameters: ["structName"], + parameters: [], printCode: { arguments, context in let printer = context.printer - let structName = arguments[0] let capturedStructDef = structDefinition let capturedAllStructs = allStructs - printer.write("const __bjs_create\(structName)Helpers = () => ({") + printer.write("const \(factoryName) = () => ({") try printer.indent { printer.write("lower: (value) => {") try printer.indent { @@ -2603,7 +2582,7 @@ struct IntrinsicJSFragment: Sendable { ) try printer.indent { printer.write( - "\(JSGlueVariableScope.reservedStructHelpers).\(structDef.abiName).lower(this);" + "\(JSGlueVariableScope.reservedStructHelpers).\(context.scope.helperKey(forTypeNamed: structDef.swiftCallName)).lower(this);" ) var paramForwardings: [String] = [] @@ -2674,9 +2653,10 @@ struct IntrinsicJSFragment: Sendable { parameters: ["value"], printCode: { arguments, context in let printer = context.printer + let nestedBase = context.scope.helperKey(forTypeNamed: nestedName) let value = arguments[0] printer.write( - "\(JSGlueVariableScope.reservedStructHelpers).\(nestedName.replacingOccurrences(of: ".", with: "_")).lower(\(value));" + "\(JSGlueVariableScope.reservedStructHelpers).\(nestedBase).lower(\(value));" ) return [] } @@ -2713,9 +2693,10 @@ struct IntrinsicJSFragment: Sendable { parameters: [], printCode: { arguments, context in let (scope, printer) = (context.scope, context.printer) + let nestedBase = scope.helperKey(forTypeNamed: nestedName) let structVar = scope.variable("struct") printer.write( - "const \(structVar) = \(JSGlueVariableScope.reservedStructHelpers).\(nestedName.replacingOccurrences(of: ".", with: "_")).lift();" + "const \(structVar) = \(JSGlueVariableScope.reservedStructHelpers).\(nestedBase).lift();" ) return [structVar] } diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/JSIntrinsicRegistry.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/JSIntrinsicRegistry.swift index 5c6596bcf..d0bf2781f 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/JSIntrinsicRegistry.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/JSIntrinsicRegistry.swift @@ -7,17 +7,8 @@ final class JSIntrinsicRegistry { private var entries: [String: [String]] = [:] var classNamespaces: [String: [String]] = [:] - /// Maps a type name as carried by `BridgeType` (struct ABI name, class name, - /// enum name, ...) to the module that declares it, so generated identifiers - /// derived from type names can be module-qualified. - /// - /// The whole link output shares one JS scope, so two modules declaring a - /// same-named `@JS` type would otherwise mint the same identifier. var typeOwnerModules: [String: String] = [:] - /// Module-scope `{ lower, lift }` codec helpers, one per type shape, in - /// dependency order: a composed codec is appended after the codecs it is - /// built from, so the emitted `const`s can be evaluated top to bottom. private var codecNameOrder: [String] = [] private var codecBodies: [String: [String]] = [:] @@ -32,11 +23,6 @@ final class JSIntrinsicRegistry { entries[name] = printer.lines } - /// Registers a named codec helper once per name. - /// - /// `build` may itself register the codecs this one is composed from; those - /// are appended first, which is what keeps the emitted declarations in a - /// valid evaluation order. func registerNamedCodec(name: String, build: (CodeFragmentPrinter) throws -> Void) rethrows { guard codecBodies[name] == nil else { return } let printer = CodeFragmentPrinter() diff --git a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift index 641105d12..ed7dee420 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift @@ -22,21 +22,12 @@ extension NamespacedExportedType { public struct ABINameGenerator { static let prefixComponent = "bjs" - /// ABI parameter name carrying the runtime type ID for the generic parameter at `index`. public static func genericTypeIdParameterName(index: Int) -> String { "_generic\(index)TypeId" } - /// Name of the per-module type-handle registration function. The wasm module - /// exports it under this name, and it calls back into a JS import hook of the - /// same name (in the `bjs` import namespace) with a buffer of type IDs. public static func typeRegistrationFunctionName(moduleName: String) -> String { "bjs_\(moduleName)_register_type_handles" } - /// Name of the core type-handle registration function. Unlike the per-module - /// ones, this is defined once in the JavaScriptKit library (see - /// `_bjs_core_register_type_handles` in `BridgeJSIntrinsics.swift`) so the - /// primitive handles exist exactly once in the final binary and the JS glue - /// registers their codecs once per linked bundle. public static let coreTypeRegistrationFunctionName = "bjs_core_register_type_handles" /// Generates ABI name using standardized namespace + context pattern @@ -326,13 +317,6 @@ extension BridgeType { } -// MARK: - Generic type registration - -/// One `BridgedSwiftGenericBridgeable` type participating in generic bridging. -/// -/// `swiftName` is the Swift expression naming the type (used by Swift codegen to -/// read `.bridgeJSTypeID`); `bridgeType` describes the stack ABI (used -/// by the JS link layer to emit the matching codec). public struct GenericBridgeableTypeEntry: Sendable { public let swiftName: String public let bridgeType: BridgeType @@ -344,17 +328,15 @@ public struct GenericBridgeableTypeEntry: Sendable { } extension ExportedEnum { - /// The `BridgeType` an enum bridges as when used as a generic argument, or - /// `nil` when it can't be one (namespace enums). public var genericBridgeType: BridgeType? { switch enumType { case .simple: - return .caseEnum(name) + return .caseEnum(swiftCallName) case .rawValue: guard let rawType = rawType else { return nil } - return .rawValueEnum(name, rawType) + return .rawValueEnum(swiftCallName, rawType) case .associatedValue: - return .associatedValueEnum(name) + return .associatedValueEnum(swiftCallName) case .namespace: return nil } @@ -362,22 +344,23 @@ extension ExportedEnum { } extension ExportedSkeleton { - /// The module's `@JS` types that conform to `BridgedSwiftGenericBridgeable`. - /// The order is the contract between the Swift registration function and the - /// JS codec array; both derive it from this skeleton, so they line up. + /// Keep this order in sync with the generated registration codec array. public var genericBridgeableTypeEntries: [GenericBridgeableTypeEntry] { var entries: [GenericBridgeableTypeEntry] = [] for structDef in structs { entries.append( GenericBridgeableTypeEntry( swiftName: structDef.swiftCallName, - bridgeType: .swiftStruct(structDef.abiName) + bridgeType: .swiftStruct(structDef.swiftCallName) ) ) } for klass in classes where klass.isFinal == true { entries.append( - GenericBridgeableTypeEntry(swiftName: klass.swiftCallName, bridgeType: .swiftHeapObject(klass.name)) + GenericBridgeableTypeEntry( + swiftName: klass.swiftCallName, + bridgeType: .swiftHeapObject(klass.swiftCallName) + ) ) } for enumDef in enums { @@ -389,14 +372,6 @@ extension ExportedSkeleton { } extension BridgeJSSkeleton { - /// The ordered list of types this module registers type handles for, or - /// `nil` when it emits no registration function. - /// - /// Only the module's own `@JS` types appear here: the core (primitive) - /// handles are owned by the JavaScriptKit library, which registers them once - /// for the whole binary via ``ABINameGenerator/coreTypeRegistrationFunctionName``. - /// A module that only *uses* generics therefore needs no registration - /// function of its own. public var typeRegistrationEntries: [GenericBridgeableTypeEntry]? { let exportedEntries = exported?.genericBridgeableTypeEntries ?? [] guard !exportedEntries.isEmpty else { return nil } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/NamedCodecHelperTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/NamedCodecHelperTests.swift deleted file mode 100644 index 4e73e02d7..000000000 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/NamedCodecHelperTests.swift +++ /dev/null @@ -1,105 +0,0 @@ -import Testing - -@testable import BridgeJSLink -@testable import BridgeJSSkeleton - -/// Every type shape gets one module-scope `{ lower, lift }` helper, shared by the -/// container combinators' element positions and by the generic type-handle -/// registration table, and composed codecs are hoisted so that no call site -/// builds one. -@Suite struct NamedCodecHelperTests { - private func codecDeclarations(in js: String) -> [String] { - js.split(separator: "\n") - .map { $0.trimmingCharacters(in: .whitespaces) } - .filter { $0.hasPrefix("const \(ContainerCodecJS.namedCodecPrefix)") } - } - - @Test - func composedCodecsAreHoistedAndReusedByCallSites() throws { - let js = try linkSource( - """ - @JS func mirror(_ values: [String: Int?]) -> [String: Int?] { values } - @JS func mirrorAgain(_ values: [String: Int?]) -> [String: Int?] { values } - """ - ).js - - // Declared once, at module scope, out of the thunks. - #expect( - codecDeclarations(in: js) == [ - "const __bjs_codec_Optional_Int = __bjs_optionalCodec(__bjs_primitiveCodecs.Int);", - "const __bjs_codec_Dict_Optional_Int = __bjs_dictCodec(__bjs_codec_Optional_Int);", - ] - ) - // Call sites only read the helper; they never compose one. - #expect(js.contains("__bjs_codec_Dict_Optional_Int.lower(values);")) - #expect(js.contains("__bjs_codec_Dict_Optional_Int.lift();")) - let composedAtCallSite = js.contains("__bjs_dictCodec(__bjs_optionalCodec(") - #expect(!composedAtCallSite) - } - - @Test - func helperNamesAreQualifiedWithTheDeclaringModule() throws { - let js = try linkSource( - """ - @JS struct Point { - var x: Int - @JS init(x: Int) { self.x = x } - } - @JS func mirror(_ points: [Point]) -> [Point] { points } - """, - moduleName: "Core" - ).js - - #expect(js.contains("const __bjs_codec_Core_Point = {")) - #expect(js.contains("const __bjs_codec_Array_Core_Point = __bjs_arrayCodec(__bjs_codec_Core_Point);")) - } - - /// The type-table entry and the element position of a container must resolve - /// to the same helper, so a type's stack ABI is described exactly once. - @Test - func registrationTableReusesTheSameHelperAsElementPositions() throws { - let js = try linkSource( - """ - @JS struct Point { - var x: Int - @JS init(x: Int) { self.x = x } - } - @JS func mirror(_ points: [Point]) -> [Point] { points } - @JSClass struct Consumer { - @JSFunction func identity(_ value: T) throws(JSException) -> T - } - """, - moduleName: "Core" - ).js - - #expect(js.contains("const __bjs_codec_Core_Point = {")) - #expect(js.contains("const __bjs_codec_Array_Core_Point = __bjs_arrayCodec(__bjs_codec_Core_Point);")) - // One entry in the registration array, referencing the same helper. - let registrationArray = - js - .components(separatedBy: "bjs[\"bjs_Core_register_type_handles\"] = function(base, count) {") - .last - .map { $0.components(separatedBy: "];")[0] } - #expect(registrationArray?.contains("__bjs_codec_Core_Point,") == true) - // The struct's marshalling code is emitted once, in its helper factory. - #expect(js.components(separatedBy: "structHelpers.Point.lower(v);").count - 1 == 1) - } - - /// A string-backed raw value enum bridges exactly as `String`, so it shares - /// the string codec instead of minting a redundant helper. - @Test - func stringBackedRawValueEnumsShareTheStringCodec() throws { - let js = try linkSource( - """ - @JS enum Mode: String { - case light - case dark - } - @JS func mirror(_ modes: [Mode]) -> [Mode] { modes } - """ - ).js - - #expect(js.contains("const __bjs_codec_Array_String = __bjs_arrayCodec(__bjs_stringCodec);")) - #expect(!js.contains("__bjs_codec_TestModule_Mode")) - } -} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js index d70db0f42..b1cfb68aa 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Alias.js @@ -360,7 +360,7 @@ export async function createInstantiator(options, swift) { return jsValue; } - const __bjs_codec_TestModule_PolygonReference = { + const __bjs_codec_M10TestModuleT16PolygonReference = { lower: (v) => { ptrStack.push(v.pointer); }, @@ -370,20 +370,20 @@ export async function createInstantiator(options, swift) { return obj; }, }; - const __bjs_codec_Array_TestModule_PolygonReference = __bjs_arrayCodec(__bjs_codec_TestModule_PolygonReference); - const __bjs_codec_TestModule_InnerTag = { + const __bjs_codec_Array_M10TestModuleT16PolygonReference = __bjs_arrayCodec(__bjs_codec_M10TestModuleT16PolygonReference); + const __bjs_codec_M10TestModuleT8InnerTag = { lower: (v) => { - const caseId = enumHelpers.InnerTag.lower(v); + const caseId = enumHelpers.M10TestModuleT8InnerTag.lower(v); i32Stack.push(caseId); }, lift: () => { - const enumValue = enumHelpers.InnerTag.lift(i32Stack.pop()); + const enumValue = enumHelpers.M10TestModuleT8InnerTag.lift(i32Stack.pop()); return enumValue; }, }; - const __bjs_codec_Optional_TestModule_InnerTag = __bjs_optionalCodec(__bjs_codec_TestModule_InnerTag); - const __bjs_codec_Array_Optional_TestModule_InnerTag = __bjs_arrayCodec(__bjs_codec_Optional_TestModule_InnerTag); - const __bjs_codec_TestModule_Surface = { + const __bjs_codec_Optional_M10TestModuleT8InnerTag = __bjs_optionalCodec(__bjs_codec_M10TestModuleT8InnerTag); + const __bjs_codec_Array_Optional_M10TestModuleT8InnerTag = __bjs_arrayCodec(__bjs_codec_Optional_M10TestModuleT8InnerTag); + const __bjs_codec_Surface = { lower: (v) => { const objId = swift.memory.retain(v); i32Stack.push(objId); @@ -395,9 +395,9 @@ export async function createInstantiator(options, swift) { return obj; }, }; - const __bjs_codec_Optional_TestModule_Surface = __bjs_optionalCodec(__bjs_codec_TestModule_Surface); + const __bjs_codec_Optional_Surface = __bjs_optionalCodec(__bjs_codec_Surface); - const __bjs_createInnerTagValuesHelpers = () => ({ + const __bjs_createEnumHelpers_M10TestModuleT8InnerTag = () => ({ lower: (value) => { const enumTag = value.tag; switch (enumTag) { @@ -646,7 +646,7 @@ export async function createInstantiator(options, swift) { TestModule["bjs_produceOptionalCanvas"] = function bjs_produceOptionalCanvas() { try { let ret = imports.produceOptionalCanvas(); - __bjs_codec_Optional_TestModule_Surface.lower(ret); + __bjs_codec_Optional_Surface.lower(ret); } catch (error) { setException(error); } @@ -774,8 +774,8 @@ export async function createInstantiator(options, swift) { return TagReference.__construct(ret); } } - const InnerTagHelpers = __bjs_createInnerTagValuesHelpers(); - enumHelpers.InnerTag = InnerTagHelpers; + const __bjs_helpers_M10TestModuleT8InnerTag = __bjs_createEnumHelpers_M10TestModuleT8InnerTag(); + enumHelpers.M10TestModuleT8InnerTag = __bjs_helpers_M10TestModuleT8InnerTag; const exports = { roundtripPolygon: function bjs_roundtripPolygon(polygon) { @@ -797,9 +797,9 @@ export async function createInstantiator(options, swift) { return optResult; }, polygonArray: function bjs_polygonArray(polygons) { - __bjs_codec_Array_TestModule_PolygonReference.lower(polygons); + __bjs_codec_Array_M10TestModuleT16PolygonReference.lower(polygons); instance.exports.bjs_polygonArray(); - const arrayResult = __bjs_codec_Array_TestModule_PolygonReference.lift(); + const arrayResult = __bjs_codec_Array_M10TestModuleT16PolygonReference.lift(); return arrayResult; }, validatePolygon: function bjs_validatePolygon(polygon) { @@ -819,9 +819,9 @@ export async function createInstantiator(options, swift) { return TagReference.__construct(ret); }, roundtripTags: function bjs_roundtripTags(xs) { - __bjs_codec_Array_Optional_TestModule_InnerTag.lower(xs); + __bjs_codec_Array_Optional_M10TestModuleT8InnerTag.lower(xs); instance.exports.bjs_roundtripTags(); - const arrayResult = __bjs_codec_Array_Optional_TestModule_InnerTag.lift(); + const arrayResult = __bjs_codec_Array_Optional_M10TestModuleT8InnerTag.lift(); return arrayResult; }, describeUser: function bjs_describeUser(owner) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js index aaa9460c8..6d3992ce5 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ArrayTypes.js @@ -371,17 +371,17 @@ export async function createInstantiator(options, swift) { const __bjs_codec_Array_String = __bjs_arrayCodec(__bjs_stringCodec); const __bjs_codec_Array_Double = __bjs_arrayCodec(__bjs_primitiveCodecs.Double); const __bjs_codec_Array_Bool = __bjs_arrayCodec(__bjs_primitiveCodecs.Bool); - const __bjs_codec_TestModule_Point = { + const __bjs_codec_M10TestModuleT5Point = { lower: (v) => { - structHelpers.Point.lower(v); + structHelpers.M10TestModuleT5Point.lower(v); }, lift: () => { - const struct = structHelpers.Point.lift(); + const struct = structHelpers.M10TestModuleT5Point.lift(); return struct; }, }; - const __bjs_codec_Array_TestModule_Point = __bjs_arrayCodec(__bjs_codec_TestModule_Point); - const __bjs_codec_TestModule_Direction = { + const __bjs_codec_Array_M10TestModuleT5Point = __bjs_arrayCodec(__bjs_codec_M10TestModuleT5Point); + const __bjs_codec_M10TestModuleT9Direction = { lower: (v) => { i32Stack.push((v | 0)); }, @@ -390,8 +390,8 @@ export async function createInstantiator(options, swift) { return caseId; }, }; - const __bjs_codec_Array_TestModule_Direction = __bjs_arrayCodec(__bjs_codec_TestModule_Direction); - const __bjs_codec_TestModule_Status = { + const __bjs_codec_Array_M10TestModuleT9Direction = __bjs_arrayCodec(__bjs_codec_M10TestModuleT9Direction); + const __bjs_codec_M10TestModuleT6Status = { lower: (v) => { i32Stack.push((v | 0)); }, @@ -400,7 +400,7 @@ export async function createInstantiator(options, swift) { return rawValue; }, }; - const __bjs_codec_Array_TestModule_Status = __bjs_arrayCodec(__bjs_codec_TestModule_Status); + const __bjs_codec_Array_M10TestModuleT6Status = __bjs_arrayCodec(__bjs_codec_M10TestModuleT6Status); const __bjs_codec_Surp = { lower: (v) => { ptrStack.push((v | 0)); @@ -436,16 +436,16 @@ export async function createInstantiator(options, swift) { const __bjs_codec_Optional_String = __bjs_optionalCodec(__bjs_stringCodec); const __bjs_codec_Array_Optional_String = __bjs_arrayCodec(__bjs_codec_Optional_String); const __bjs_codec_Optional_Array_Int = __bjs_optionalCodec(__bjs_codec_Array_Int); - const __bjs_codec_Optional_TestModule_Point = __bjs_optionalCodec(__bjs_codec_TestModule_Point); - const __bjs_codec_Array_Optional_TestModule_Point = __bjs_arrayCodec(__bjs_codec_Optional_TestModule_Point); - const __bjs_codec_Optional_TestModule_Direction = __bjs_optionalCodec(__bjs_codec_TestModule_Direction); - const __bjs_codec_Array_Optional_TestModule_Direction = __bjs_arrayCodec(__bjs_codec_Optional_TestModule_Direction); - const __bjs_codec_Optional_TestModule_Status = __bjs_optionalCodec(__bjs_codec_TestModule_Status); - const __bjs_codec_Array_Optional_TestModule_Status = __bjs_arrayCodec(__bjs_codec_Optional_TestModule_Status); + const __bjs_codec_Optional_M10TestModuleT5Point = __bjs_optionalCodec(__bjs_codec_M10TestModuleT5Point); + const __bjs_codec_Array_Optional_M10TestModuleT5Point = __bjs_arrayCodec(__bjs_codec_Optional_M10TestModuleT5Point); + const __bjs_codec_Optional_M10TestModuleT9Direction = __bjs_optionalCodec(__bjs_codec_M10TestModuleT9Direction); + const __bjs_codec_Array_Optional_M10TestModuleT9Direction = __bjs_arrayCodec(__bjs_codec_Optional_M10TestModuleT9Direction); + const __bjs_codec_Optional_M10TestModuleT6Status = __bjs_optionalCodec(__bjs_codec_M10TestModuleT6Status); + const __bjs_codec_Array_Optional_M10TestModuleT6Status = __bjs_arrayCodec(__bjs_codec_Optional_M10TestModuleT6Status); const __bjs_codec_Array_Array_Int = __bjs_arrayCodec(__bjs_codec_Array_Int); const __bjs_codec_Array_Array_String = __bjs_arrayCodec(__bjs_codec_Array_String); - const __bjs_codec_Array_Array_TestModule_Point = __bjs_arrayCodec(__bjs_codec_Array_TestModule_Point); - const __bjs_codec_TestModule_Item = { + const __bjs_codec_Array_Array_M10TestModuleT5Point = __bjs_arrayCodec(__bjs_codec_Array_M10TestModuleT5Point); + const __bjs_codec_M10TestModuleT4Item = { lower: (v) => { ptrStack.push(v.pointer); }, @@ -455,8 +455,8 @@ export async function createInstantiator(options, swift) { return obj; }, }; - const __bjs_codec_Array_TestModule_Item = __bjs_arrayCodec(__bjs_codec_TestModule_Item); - const __bjs_codec_Array_Array_TestModule_Item = __bjs_arrayCodec(__bjs_codec_Array_TestModule_Item); + const __bjs_codec_Array_M10TestModuleT4Item = __bjs_arrayCodec(__bjs_codec_M10TestModuleT4Item); + const __bjs_codec_Array_Array_M10TestModuleT4Item = __bjs_arrayCodec(__bjs_codec_Array_M10TestModuleT4Item); const __bjs_codec_JSObject = { lower: (v) => { const objId = swift.memory.retain(v); @@ -475,7 +475,7 @@ export async function createInstantiator(options, swift) { const __bjs_codec_Array_Array_JSObject = __bjs_arrayCodec(__bjs_codec_Array_JSObject); const __bjs_codec_Optional_Array_String = __bjs_optionalCodec(__bjs_codec_Array_String); - const __bjs_createPointHelpers = () => ({ + const __bjs_createStructHelpers_M10TestModuleT5Point = () => ({ lower: (value) => { f64Stack.push(value.x); f64Stack.push(value.y); @@ -563,10 +563,10 @@ export async function createInstantiator(options, swift) { taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_Point"] = function(objectId) { - structHelpers.Point.lower(swift.memory.getObject(objectId)); + structHelpers.M10TestModuleT5Point.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_Point"] = function() { - const value = structHelpers.Point.lift(); + const value = structHelpers.M10TestModuleT5Point.lift(); return swift.memory.retain(value); } bjs["bjs_core_register_type_handles"] = function() {}; @@ -832,8 +832,8 @@ export async function createInstantiator(options, swift) { return arrayResult; } } - const PointHelpers = __bjs_createPointHelpers(); - structHelpers.Point = PointHelpers; + const __bjs_helpers_M10TestModuleT5Point = __bjs_createStructHelpers_M10TestModuleT5Point(); + structHelpers.M10TestModuleT5Point = __bjs_helpers_M10TestModuleT5Point; const exports = { processIntArray: function bjs_processIntArray(values) { @@ -861,21 +861,21 @@ export async function createInstantiator(options, swift) { return arrayResult; }, processPointArray: function bjs_processPointArray(points) { - __bjs_codec_Array_TestModule_Point.lower(points); + __bjs_codec_Array_M10TestModuleT5Point.lower(points); instance.exports.bjs_processPointArray(); - const arrayResult = __bjs_codec_Array_TestModule_Point.lift(); + const arrayResult = __bjs_codec_Array_M10TestModuleT5Point.lift(); return arrayResult; }, processDirectionArray: function bjs_processDirectionArray(directions) { - __bjs_codec_Array_TestModule_Direction.lower(directions); + __bjs_codec_Array_M10TestModuleT9Direction.lower(directions); instance.exports.bjs_processDirectionArray(); - const arrayResult = __bjs_codec_Array_TestModule_Direction.lift(); + const arrayResult = __bjs_codec_Array_M10TestModuleT9Direction.lift(); return arrayResult; }, processStatusArray: function bjs_processStatusArray(statuses) { - __bjs_codec_Array_TestModule_Status.lower(statuses); + __bjs_codec_Array_M10TestModuleT6Status.lower(statuses); instance.exports.bjs_processStatusArray(); - const arrayResult = __bjs_codec_Array_TestModule_Status.lift(); + const arrayResult = __bjs_codec_Array_M10TestModuleT6Status.lift(); return arrayResult; }, sumIntArray: function bjs_sumIntArray(values) { @@ -884,11 +884,11 @@ export async function createInstantiator(options, swift) { return ret; }, findFirstPoint: function bjs_findFirstPoint(points, matching) { - __bjs_codec_Array_TestModule_Point.lower(points); + __bjs_codec_Array_M10TestModuleT5Point.lower(points); const matchingBytes = textEncoder.encode(matching); const matchingId = swift.memory.retain(matchingBytes); instance.exports.bjs_findFirstPoint(matchingId, matchingBytes.length); - const structValue = structHelpers.Point.lift(); + const structValue = structHelpers.M10TestModuleT5Point.lift(); return structValue; }, processUnsafeRawPointerArray: function bjs_processUnsafeRawPointerArray(values) { @@ -928,21 +928,21 @@ export async function createInstantiator(options, swift) { return optValue; }, processOptionalPointArray: function bjs_processOptionalPointArray(points) { - __bjs_codec_Array_Optional_TestModule_Point.lower(points); + __bjs_codec_Array_Optional_M10TestModuleT5Point.lower(points); instance.exports.bjs_processOptionalPointArray(); - const arrayResult = __bjs_codec_Array_Optional_TestModule_Point.lift(); + const arrayResult = __bjs_codec_Array_Optional_M10TestModuleT5Point.lift(); return arrayResult; }, processOptionalDirectionArray: function bjs_processOptionalDirectionArray(directions) { - __bjs_codec_Array_Optional_TestModule_Direction.lower(directions); + __bjs_codec_Array_Optional_M10TestModuleT9Direction.lower(directions); instance.exports.bjs_processOptionalDirectionArray(); - const arrayResult = __bjs_codec_Array_Optional_TestModule_Direction.lift(); + const arrayResult = __bjs_codec_Array_Optional_M10TestModuleT9Direction.lift(); return arrayResult; }, processOptionalStatusArray: function bjs_processOptionalStatusArray(statuses) { - __bjs_codec_Array_Optional_TestModule_Status.lower(statuses); + __bjs_codec_Array_Optional_M10TestModuleT6Status.lower(statuses); instance.exports.bjs_processOptionalStatusArray(); - const arrayResult = __bjs_codec_Array_Optional_TestModule_Status.lift(); + const arrayResult = __bjs_codec_Array_Optional_M10TestModuleT6Status.lift(); return arrayResult; }, processNestedIntArray: function bjs_processNestedIntArray(values) { @@ -958,21 +958,21 @@ export async function createInstantiator(options, swift) { return arrayResult; }, processNestedPointArray: function bjs_processNestedPointArray(points) { - __bjs_codec_Array_Array_TestModule_Point.lower(points); + __bjs_codec_Array_Array_M10TestModuleT5Point.lower(points); instance.exports.bjs_processNestedPointArray(); - const arrayResult = __bjs_codec_Array_Array_TestModule_Point.lift(); + const arrayResult = __bjs_codec_Array_Array_M10TestModuleT5Point.lift(); return arrayResult; }, processItemArray: function bjs_processItemArray(items) { - __bjs_codec_Array_TestModule_Item.lower(items); + __bjs_codec_Array_M10TestModuleT4Item.lower(items); instance.exports.bjs_processItemArray(); - const arrayResult = __bjs_codec_Array_TestModule_Item.lift(); + const arrayResult = __bjs_codec_Array_M10TestModuleT4Item.lift(); return arrayResult; }, processNestedItemArray: function bjs_processNestedItemArray(items) { - __bjs_codec_Array_Array_TestModule_Item.lower(items); + __bjs_codec_Array_Array_M10TestModuleT4Item.lower(items); instance.exports.bjs_processNestedItemArray(); - const arrayResult = __bjs_codec_Array_Array_TestModule_Item.lift(); + const arrayResult = __bjs_codec_Array_Array_M10TestModuleT4Item.lift(); return arrayResult; }, processJSObjectArray: function bjs_processJSObjectArray(objects) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js index 2b667aefa..6f2a21501 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js @@ -364,18 +364,18 @@ export async function createInstantiator(options, swift) { return jsValue; } - const __bjs_codec_TestModule_AsyncPoint = { + const __bjs_codec_M10TestModuleT10AsyncPoint = { lower: (v) => { - structHelpers.AsyncPoint.lower(v); + structHelpers.M10TestModuleT10AsyncPoint.lower(v); }, lift: () => { - const struct = structHelpers.AsyncPoint.lift(); + const struct = structHelpers.M10TestModuleT10AsyncPoint.lift(); return struct; }, }; - const __bjs_codec_Optional_TestModule_AsyncPoint = __bjs_optionalCodec(__bjs_codec_TestModule_AsyncPoint); - const __bjs_codec_Array_TestModule_AsyncPoint = __bjs_arrayCodec(__bjs_codec_TestModule_AsyncPoint); - const __bjs_codec_TestModule_AsyncDirection = { + const __bjs_codec_Optional_M10TestModuleT10AsyncPoint = __bjs_optionalCodec(__bjs_codec_M10TestModuleT10AsyncPoint); + const __bjs_codec_Array_M10TestModuleT10AsyncPoint = __bjs_arrayCodec(__bjs_codec_M10TestModuleT10AsyncPoint); + const __bjs_codec_M10TestModuleT14AsyncDirection = { lower: (v) => { i32Stack.push((v | 0)); }, @@ -384,11 +384,11 @@ export async function createInstantiator(options, swift) { return caseId; }, }; - const __bjs_codec_Array_TestModule_AsyncDirection = __bjs_arrayCodec(__bjs_codec_TestModule_AsyncDirection); - const __bjs_codec_Dict_TestModule_AsyncPoint = __bjs_dictCodec(__bjs_codec_TestModule_AsyncPoint); - const __bjs_codec_Dict_TestModule_AsyncDirection = __bjs_dictCodec(__bjs_codec_TestModule_AsyncDirection); + const __bjs_codec_Array_M10TestModuleT14AsyncDirection = __bjs_arrayCodec(__bjs_codec_M10TestModuleT14AsyncDirection); + const __bjs_codec_Dict_M10TestModuleT10AsyncPoint = __bjs_dictCodec(__bjs_codec_M10TestModuleT10AsyncPoint); + const __bjs_codec_Dict_M10TestModuleT14AsyncDirection = __bjs_dictCodec(__bjs_codec_M10TestModuleT14AsyncDirection); - const __bjs_createAsyncPointHelpers = () => ({ + const __bjs_createStructHelpers_M10TestModuleT10AsyncPoint = () => ({ lower: (value) => { i32Stack.push((value.x | 0)); i32Stack.push((value.y | 0)); @@ -475,10 +475,10 @@ export async function createInstantiator(options, swift) { taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_AsyncPoint"] = function(objectId) { - structHelpers.AsyncPoint.lower(swift.memory.getObject(objectId)); + structHelpers.M10TestModuleT10AsyncPoint.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_AsyncPoint"] = function() { - const value = structHelpers.AsyncPoint.lift(); + const value = structHelpers.M10TestModuleT10AsyncPoint.lift(); return swift.memory.retain(value); } bjs["bjs_core_register_type_handles"] = function() {}; @@ -542,7 +542,7 @@ export async function createInstantiator(options, swift) { } bjs["promise_resolve_TestModule_10AsyncPointV"] = function(promise) { try { - const structValue = structHelpers.AsyncPoint.lift(); + const structValue = structHelpers.M10TestModuleT10AsyncPoint.lift(); swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(structValue); } catch (error) { setException(error); @@ -588,7 +588,7 @@ export async function createInstantiator(options, swift) { try { let optResult; if (value) { - const struct = structHelpers.AsyncPoint.lift(); + const struct = structHelpers.M10TestModuleT10AsyncPoint.lift(); optResult = struct; } else { optResult = null; @@ -600,7 +600,7 @@ export async function createInstantiator(options, swift) { } bjs["promise_resolve_TestModule_Sa10AsyncPointV"] = function(promise) { try { - const arrayResult = __bjs_codec_Array_TestModule_AsyncPoint.lift(); + const arrayResult = __bjs_codec_Array_M10TestModuleT10AsyncPoint.lift(); swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(arrayResult); } catch (error) { setException(error); @@ -608,7 +608,7 @@ export async function createInstantiator(options, swift) { } bjs["promise_resolve_TestModule_Sa14AsyncDirectionO"] = function(promise) { try { - const arrayResult = __bjs_codec_Array_TestModule_AsyncDirection.lift(); + const arrayResult = __bjs_codec_Array_M10TestModuleT14AsyncDirection.lift(); swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(arrayResult); } catch (error) { setException(error); @@ -616,7 +616,7 @@ export async function createInstantiator(options, swift) { } bjs["promise_resolve_TestModule_SD10AsyncPointV"] = function(promise) { try { - const dictResult = __bjs_codec_Dict_TestModule_AsyncPoint.lift(); + const dictResult = __bjs_codec_Dict_M10TestModuleT10AsyncPoint.lift(); swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(dictResult); } catch (error) { setException(error); @@ -624,7 +624,7 @@ export async function createInstantiator(options, swift) { } bjs["promise_resolve_TestModule_SD14AsyncDirectionO"] = function(promise) { try { - const dictResult = __bjs_codec_Dict_TestModule_AsyncDirection.lift(); + const dictResult = __bjs_codec_Dict_M10TestModuleT14AsyncDirection.lift(); swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(dictResult); } catch (error) { setException(error); @@ -742,8 +742,8 @@ export async function createInstantiator(options, swift) { /** @param {WebAssembly.Instance} instance */ createExports: (instance) => { const js = swift.memory.heap; - const AsyncPointHelpers = __bjs_createAsyncPointHelpers(); - structHelpers.AsyncPoint = AsyncPointHelpers; + const __bjs_helpers_M10TestModuleT10AsyncPoint = __bjs_createStructHelpers_M10TestModuleT10AsyncPoint(); + structHelpers.M10TestModuleT10AsyncPoint = __bjs_helpers_M10TestModuleT10AsyncPoint; const exports = { asyncReturnVoid: function bjs_asyncReturnVoid() { @@ -791,14 +791,14 @@ export async function createInstantiator(options, swift) { return ret1; }, asyncRoundTripStruct: function bjs_asyncRoundTripStruct(v) { - structHelpers.AsyncPoint.lower(v); + structHelpers.M10TestModuleT10AsyncPoint.lower(v); const ret = instance.exports.bjs_asyncRoundTripStruct(); const ret1 = swift.memory.getObject(ret); swift.memory.release(ret); return ret1; }, asyncRoundTripStructThrows: function bjs_asyncRoundTripStructThrows(v) { - structHelpers.AsyncPoint.lower(v); + structHelpers.M10TestModuleT10AsyncPoint.lower(v); const ret = instance.exports.bjs_asyncRoundTripStructThrows(); const ret1 = swift.memory.getObject(ret); swift.memory.release(ret); @@ -823,8 +823,8 @@ export async function createInstantiator(options, swift) { return ret1; }, asyncCombineStructs: function bjs_asyncCombineStructs(a, b) { - structHelpers.AsyncPoint.lower(a); - structHelpers.AsyncPoint.lower(b); + structHelpers.M10TestModuleT10AsyncPoint.lower(a); + structHelpers.M10TestModuleT10AsyncPoint.lower(b); const ret = instance.exports.bjs_asyncCombineStructs(); const ret1 = swift.memory.getObject(ret); swift.memory.release(ret); @@ -869,35 +869,35 @@ export async function createInstantiator(options, swift) { return ret1; }, asyncRoundTripOptionalStruct: function bjs_asyncRoundTripOptionalStruct(v) { - __bjs_codec_Optional_TestModule_AsyncPoint.lower(v); + __bjs_codec_Optional_M10TestModuleT10AsyncPoint.lower(v); const ret = instance.exports.bjs_asyncRoundTripOptionalStruct(); const ret1 = swift.memory.getObject(ret); swift.memory.release(ret); return ret1; }, asyncRoundTripStructArray: function bjs_asyncRoundTripStructArray(v) { - __bjs_codec_Array_TestModule_AsyncPoint.lower(v); + __bjs_codec_Array_M10TestModuleT10AsyncPoint.lower(v); const ret = instance.exports.bjs_asyncRoundTripStructArray(); const ret1 = swift.memory.getObject(ret); swift.memory.release(ret); return ret1; }, asyncRoundTripEnumArray: function bjs_asyncRoundTripEnumArray(v) { - __bjs_codec_Array_TestModule_AsyncDirection.lower(v); + __bjs_codec_Array_M10TestModuleT14AsyncDirection.lower(v); const ret = instance.exports.bjs_asyncRoundTripEnumArray(); const ret1 = swift.memory.getObject(ret); swift.memory.release(ret); return ret1; }, asyncRoundTripStructDictionary: function bjs_asyncRoundTripStructDictionary(v) { - __bjs_codec_Dict_TestModule_AsyncPoint.lower(v); + __bjs_codec_Dict_M10TestModuleT10AsyncPoint.lower(v); const ret = instance.exports.bjs_asyncRoundTripStructDictionary(); const ret1 = swift.memory.getObject(ret); swift.memory.release(ret); return ret1; }, asyncRoundTripEnumDictionary: function bjs_asyncRoundTripEnumDictionary(v) { - __bjs_codec_Dict_TestModule_AsyncDirection.lower(v); + __bjs_codec_Dict_M10TestModuleT14AsyncDirection.lower(v); const ret = instance.exports.bjs_asyncRoundTripEnumDictionary(); const ret1 = swift.memory.getObject(ret); swift.memory.release(ret); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js index 5671e4898..49b2ff88b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncAssociatedValueEnum.js @@ -127,7 +127,7 @@ export async function createInstantiator(options, swift) { return jsValue; } - const __bjs_createAsyncPayloadResultValuesHelpers = () => ({ + const __bjs_createEnumHelpers_M10TestModuleT18AsyncPayloadResult = () => ({ lower: (value) => { const enumTag = value.tag; switch (enumTag) { @@ -250,7 +250,7 @@ export async function createInstantiator(options, swift) { } bjs["promise_resolve_TestModule_18AsyncPayloadResultO"] = function(promise, value) { try { - const enumValue = enumHelpers.AsyncPayloadResult.lift(value); + const enumValue = enumHelpers.M10TestModuleT18AsyncPayloadResult.lift(value); swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(enumValue); } catch (error) { setException(error); @@ -260,7 +260,7 @@ export async function createInstantiator(options, swift) { try { let optResult; if (valueIsSome) { - const enumValue = enumHelpers.AsyncPayloadResult.lift(valueCaseId); + const enumValue = enumHelpers.M10TestModuleT18AsyncPayloadResult.lift(valueCaseId); optResult = enumValue; } else { optResult = null; @@ -382,12 +382,12 @@ export async function createInstantiator(options, swift) { /** @param {WebAssembly.Instance} instance */ createExports: (instance) => { const js = swift.memory.heap; - const AsyncPayloadResultHelpers = __bjs_createAsyncPayloadResultValuesHelpers(); - enumHelpers.AsyncPayloadResult = AsyncPayloadResultHelpers; + const __bjs_helpers_M10TestModuleT18AsyncPayloadResult = __bjs_createEnumHelpers_M10TestModuleT18AsyncPayloadResult(); + enumHelpers.M10TestModuleT18AsyncPayloadResult = __bjs_helpers_M10TestModuleT18AsyncPayloadResult; const exports = { asyncRoundTripAssociatedValueEnum: function bjs_asyncRoundTripAssociatedValueEnum(value) { - const valueCaseId = enumHelpers.AsyncPayloadResult.lower(value); + const valueCaseId = enumHelpers.M10TestModuleT18AsyncPayloadResult.lower(value); const ret = instance.exports.bjs_asyncRoundTripAssociatedValueEnum(valueCaseId); const ret1 = swift.memory.getObject(ret); swift.memory.release(ret); @@ -397,7 +397,7 @@ export async function createInstantiator(options, swift) { const isSome = value != null; let result; if (isSome) { - const valueCaseId = enumHelpers.AsyncPayloadResult.lower(value); + const valueCaseId = enumHelpers.M10TestModuleT18AsyncPayloadResult.lower(value); result = valueCaseId; } else { result = 0; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.js index 30d0522c0..ecdb0b059 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ClassWithNestedTypes.js @@ -36,7 +36,7 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; - const __bjs_createAccount_CredentialsHelpers = () => ({ + const __bjs_createStructHelpers_M10TestModuleT7AccountT11Credentials = () => ({ lower: (value) => { const bytes = textEncoder.encode(value.token); const id = swift.memory.retain(bytes); @@ -124,10 +124,10 @@ export async function createInstantiator(options, swift) { taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_Account_Credentials"] = function(objectId) { - structHelpers.Account_Credentials.lower(swift.memory.getObject(objectId)); + structHelpers.M10TestModuleT7AccountT11Credentials.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_Account_Credentials"] = function() { - const value = structHelpers.Account_Credentials.lift(); + const value = structHelpers.M10TestModuleT7AccountT11Credentials.lift(); return swift.memory.retain(value); } bjs["bjs_core_register_type_handles"] = function() {}; @@ -344,8 +344,8 @@ export async function createInstantiator(options, swift) { return ret; } } - const Account_CredentialsHelpers = __bjs_createAccount_CredentialsHelpers(); - structHelpers.Account_Credentials = Account_CredentialsHelpers; + const __bjs_helpers_M10TestModuleT7AccountT11Credentials = __bjs_createStructHelpers_M10TestModuleT7AccountT11Credentials(); + structHelpers.M10TestModuleT7AccountT11Credentials = __bjs_helpers_M10TestModuleT7AccountT11Credentials; const exports = { Account: Object.assign(Account, { @@ -355,7 +355,7 @@ export async function createInstantiator(options, swift) { const tokenBytes = textEncoder.encode(token); const tokenId = swift.memory.retain(tokenBytes); instance.exports.bjs_Account_Credentials_init(tokenId, tokenBytes.length); - const structValue = structHelpers.Account_Credentials.lift(); + const structValue = structHelpers.M10TestModuleT7AccountT11Credentials.lift(); return structValue; }, get maxLength() { @@ -364,7 +364,7 @@ export async function createInstantiator(options, swift) { }, empty: function() { instance.exports.bjs_Account_Credentials_static_empty(); - const structValue = structHelpers.Account_Credentials.lift(); + const structValue = structHelpers.M10TestModuleT7AccountT11Credentials.lift(); return structValue; }, }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js index 3dc39e445..fe1fa7b54 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DefaultParameters.js @@ -360,22 +360,22 @@ export async function createInstantiator(options, swift) { return jsValue; } - const __bjs_codec_TestModule_Config = { + const __bjs_codec_M10TestModuleT6Config = { lower: (v) => { - structHelpers.Config.lower(v); + structHelpers.M10TestModuleT6Config.lower(v); }, lift: () => { - const struct = structHelpers.Config.lift(); + const struct = structHelpers.M10TestModuleT6Config.lift(); return struct; }, }; - const __bjs_codec_Optional_TestModule_Config = __bjs_optionalCodec(__bjs_codec_TestModule_Config); + const __bjs_codec_Optional_M10TestModuleT6Config = __bjs_optionalCodec(__bjs_codec_M10TestModuleT6Config); const __bjs_codec_Array_Int = __bjs_arrayCodec(__bjs_primitiveCodecs.Int); const __bjs_codec_Array_String = __bjs_arrayCodec(__bjs_stringCodec); const __bjs_codec_Array_Double = __bjs_arrayCodec(__bjs_primitiveCodecs.Double); const __bjs_codec_Array_Bool = __bjs_arrayCodec(__bjs_primitiveCodecs.Bool); - const __bjs_createConfigHelpers = () => ({ + const __bjs_createStructHelpers_M10TestModuleT6Config = () => ({ lower: (value) => { const bytes = textEncoder.encode(value.name); const id = swift.memory.retain(bytes); @@ -391,7 +391,7 @@ export async function createInstantiator(options, swift) { return { name: string, value: int, enabled: bool }; } }); - const __bjs_createMathOperationsHelpers = () => ({ + const __bjs_createStructHelpers_M10TestModuleT14MathOperations = () => ({ lower: (value) => { f64Stack.push(value.baseValue); }, @@ -399,12 +399,12 @@ export async function createInstantiator(options, swift) { const f64 = f64Stack.pop(); const instance1 = { baseValue: f64 }; instance1.add = function(a, b = 10.0) { - structHelpers.MathOperations.lower(this); + structHelpers.M10TestModuleT14MathOperations.lower(this); const ret = instance.exports.bjs_MathOperations_add(a, b); return ret; }.bind(instance1); instance1.multiply = function(a, b) { - structHelpers.MathOperations.lower(this); + structHelpers.M10TestModuleT14MathOperations.lower(this); const ret1 = instance.exports.bjs_MathOperations_multiply(a, b); return ret1; }.bind(instance1); @@ -487,17 +487,17 @@ export async function createInstantiator(options, swift) { taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_Config"] = function(objectId) { - structHelpers.Config.lower(swift.memory.getObject(objectId)); + structHelpers.M10TestModuleT6Config.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_Config"] = function() { - const value = structHelpers.Config.lift(); + const value = structHelpers.M10TestModuleT6Config.lift(); return swift.memory.retain(value); } bjs["swift_js_struct_lower_MathOperations"] = function(objectId) { - structHelpers.MathOperations.lower(swift.memory.getObject(objectId)); + structHelpers.M10TestModuleT14MathOperations.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_MathOperations"] = function() { - const value = structHelpers.MathOperations.lift(); + const value = structHelpers.M10TestModuleT14MathOperations.lift(); return swift.memory.retain(value); } bjs["bjs_core_register_type_handles"] = function() {}; @@ -789,11 +789,11 @@ export async function createInstantiator(options, swift) { instance.exports.bjs_ConstructorDefaults_tag_set(this.pointer, +isSome, result, result1); } } - const ConfigHelpers = __bjs_createConfigHelpers(); - structHelpers.Config = ConfigHelpers; + const __bjs_helpers_M10TestModuleT6Config = __bjs_createStructHelpers_M10TestModuleT6Config(); + structHelpers.M10TestModuleT6Config = __bjs_helpers_M10TestModuleT6Config; - const MathOperationsHelpers = __bjs_createMathOperationsHelpers(); - structHelpers.MathOperations = MathOperationsHelpers; + const __bjs_helpers_M10TestModuleT14MathOperations = __bjs_createStructHelpers_M10TestModuleT14MathOperations(); + structHelpers.M10TestModuleT14MathOperations = __bjs_helpers_M10TestModuleT14MathOperations; const exports = { testStringDefault: function bjs_testStringDefault(message = "Hello World") { @@ -875,15 +875,15 @@ export async function createInstantiator(options, swift) { return EmptyGreeter.__construct(ret); }, testOptionalStructDefault: function bjs_testOptionalStructDefault(point = null) { - __bjs_codec_Optional_TestModule_Config.lower(point); + __bjs_codec_Optional_M10TestModuleT6Config.lower(point); instance.exports.bjs_testOptionalStructDefault(); - const optValue = __bjs_codec_Optional_TestModule_Config.lift(); + const optValue = __bjs_codec_Optional_M10TestModuleT6Config.lift(); return optValue; }, testOptionalStructWithValueDefault: function bjs_testOptionalStructWithValueDefault(point = { name: "default", value: 42, enabled: true }) { - __bjs_codec_Optional_TestModule_Config.lower(point); + __bjs_codec_Optional_M10TestModuleT6Config.lower(point); instance.exports.bjs_testOptionalStructWithValueDefault(); - const optValue = __bjs_codec_Optional_TestModule_Config.lift(); + const optValue = __bjs_codec_Optional_M10TestModuleT6Config.lift(); return optValue; }, testIntArrayDefault: function bjs_testIntArrayDefault(values = [1, 2, 3]) { @@ -932,7 +932,7 @@ export async function createInstantiator(options, swift) { MathOperations: { init: function(baseValue = 0.0) { instance.exports.bjs_MathOperations_init(baseValue); - const structValue = structHelpers.MathOperations.lift(); + const structValue = structHelpers.M10TestModuleT14MathOperations.lift(); return structValue; }, subtract: function(a, b = 5.0) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js index 6d8ea7392..8ccda3c19 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DictionaryTypes.js @@ -359,7 +359,7 @@ export async function createInstantiator(options, swift) { const __bjs_codec_Optional_Dict_String = __bjs_optionalCodec(__bjs_codec_Dict_String); const __bjs_codec_Array_Int = __bjs_arrayCodec(__bjs_primitiveCodecs.Int); const __bjs_codec_Dict_Array_Int = __bjs_dictCodec(__bjs_codec_Array_Int); - const __bjs_codec_TestModule_Box = { + const __bjs_codec_M10TestModuleT3Box = { lower: (v) => { ptrStack.push(v.pointer); }, @@ -369,14 +369,14 @@ export async function createInstantiator(options, swift) { return obj; }, }; - const __bjs_codec_Dict_TestModule_Box = __bjs_dictCodec(__bjs_codec_TestModule_Box); - const __bjs_codec_Optional_TestModule_Box = __bjs_optionalCodec(__bjs_codec_TestModule_Box); - const __bjs_codec_Dict_Optional_TestModule_Box = __bjs_dictCodec(__bjs_codec_Optional_TestModule_Box); + const __bjs_codec_Dict_M10TestModuleT3Box = __bjs_dictCodec(__bjs_codec_M10TestModuleT3Box); + const __bjs_codec_Optional_M10TestModuleT3Box = __bjs_optionalCodec(__bjs_codec_M10TestModuleT3Box); + const __bjs_codec_Dict_Optional_M10TestModuleT3Box = __bjs_dictCodec(__bjs_codec_Optional_M10TestModuleT3Box); const __bjs_codec_Dict_Double = __bjs_dictCodec(__bjs_primitiveCodecs.Double); const __bjs_codec_Optional_Int = __bjs_optionalCodec(__bjs_primitiveCodecs.Int); const __bjs_codec_Dict_Optional_Int = __bjs_dictCodec(__bjs_codec_Optional_Int); - const __bjs_createCountersHelpers = () => ({ + const __bjs_createStructHelpers_M10TestModuleT8Counters = () => ({ lower: (value) => { const bytes = textEncoder.encode(value.name); const id = swift.memory.retain(bytes); @@ -467,10 +467,10 @@ export async function createInstantiator(options, swift) { taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_Counters"] = function(objectId) { - structHelpers.Counters.lower(swift.memory.getObject(objectId)); + structHelpers.M10TestModuleT8Counters.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_Counters"] = function() { - const value = structHelpers.Counters.lift(); + const value = structHelpers.M10TestModuleT8Counters.lift(); return swift.memory.retain(value); } bjs["bjs_core_register_type_handles"] = function() {}; @@ -662,8 +662,8 @@ export async function createInstantiator(options, swift) { } } - const CountersHelpers = __bjs_createCountersHelpers(); - structHelpers.Counters = CountersHelpers; + const __bjs_helpers_M10TestModuleT8Counters = __bjs_createStructHelpers_M10TestModuleT8Counters(); + structHelpers.M10TestModuleT8Counters = __bjs_helpers_M10TestModuleT8Counters; const exports = { mirrorDictionary: function bjs_mirrorDictionary(values) { @@ -685,21 +685,21 @@ export async function createInstantiator(options, swift) { return dictResult; }, boxDictionary: function bjs_boxDictionary(boxes) { - __bjs_codec_Dict_TestModule_Box.lower(boxes); + __bjs_codec_Dict_M10TestModuleT3Box.lower(boxes); instance.exports.bjs_boxDictionary(); - const dictResult = __bjs_codec_Dict_TestModule_Box.lift(); + const dictResult = __bjs_codec_Dict_M10TestModuleT3Box.lift(); return dictResult; }, optionalBoxDictionary: function bjs_optionalBoxDictionary(boxes) { - __bjs_codec_Dict_Optional_TestModule_Box.lower(boxes); + __bjs_codec_Dict_Optional_M10TestModuleT3Box.lower(boxes); instance.exports.bjs_optionalBoxDictionary(); - const dictResult = __bjs_codec_Dict_Optional_TestModule_Box.lift(); + const dictResult = __bjs_codec_Dict_Optional_M10TestModuleT3Box.lift(); return dictResult; }, roundtripCounters: function bjs_roundtripCounters(counters) { - structHelpers.Counters.lower(counters); + structHelpers.M10TestModuleT8Counters.lower(counters); instance.exports.bjs_roundtripCounters(); - const structValue = structHelpers.Counters.lift(); + const structValue = structHelpers.M10TestModuleT8Counters.lift(); return structValue; }, Box, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.js index 65323aace..6d23d394f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/DocComments.js @@ -37,7 +37,7 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; - const __bjs_createPointHelpers = () => ({ + const __bjs_createStructHelpers_M10TestModuleT5Point = () => ({ lower: (value) => { f64Stack.push(value.x); f64Stack.push(value.y); @@ -124,10 +124,10 @@ export async function createInstantiator(options, swift) { taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_Point"] = function(objectId) { - structHelpers.Point.lower(swift.memory.getObject(objectId)); + structHelpers.M10TestModuleT5Point.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_Point"] = function() { - const value = structHelpers.Point.lift(); + const value = structHelpers.M10TestModuleT5Point.lift(); return swift.memory.retain(value); } bjs["bjs_core_register_type_handles"] = function() {}; @@ -349,8 +349,8 @@ export async function createInstantiator(options, swift) { instance.exports.bjs_Greeter_name_set(this.pointer, valueId, valueBytes.length); } } - const PointHelpers = __bjs_createPointHelpers(); - structHelpers.Point = PointHelpers; + const __bjs_helpers_M10TestModuleT5Point = __bjs_createStructHelpers_M10TestModuleT5Point(); + structHelpers.M10TestModuleT5Point = __bjs_helpers_M10TestModuleT5Point; const exports = { greet: function bjs_greet(name, greeting = "Hello") { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js index 2a8ed684c..66f85760c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValue.js @@ -438,7 +438,7 @@ export async function createInstantiator(options, swift) { const __bjs_codec_Optional_String = __bjs_optionalCodec(__bjs_stringCodec); const __bjs_codec_Optional_Bool = __bjs_optionalCodec(__bjs_primitiveCodecs.Bool); const __bjs_codec_Optional_Int = __bjs_optionalCodec(__bjs_primitiveCodecs.Int); - const __bjs_codec_TestModule_Precision = { + const __bjs_codec_M10TestModuleT9Precision = { lower: (v) => { f32Stack.push(Math.fround(v)); }, @@ -447,8 +447,8 @@ export async function createInstantiator(options, swift) { return rawValue; }, }; - const __bjs_codec_Optional_TestModule_Precision = __bjs_optionalCodec(__bjs_codec_TestModule_Precision); - const __bjs_codec_TestModule_CardinalDirection = { + const __bjs_codec_Optional_M10TestModuleT9Precision = __bjs_optionalCodec(__bjs_codec_M10TestModuleT9Precision); + const __bjs_codec_M10TestModuleT17CardinalDirection = { lower: (v) => { i32Stack.push((v | 0)); }, @@ -457,19 +457,19 @@ export async function createInstantiator(options, swift) { return caseId; }, }; - const __bjs_codec_Optional_TestModule_CardinalDirection = __bjs_optionalCodec(__bjs_codec_TestModule_CardinalDirection); + const __bjs_codec_Optional_M10TestModuleT17CardinalDirection = __bjs_optionalCodec(__bjs_codec_M10TestModuleT17CardinalDirection); const __bjs_codec_Array_Int = __bjs_arrayCodec(__bjs_primitiveCodecs.Int); - const __bjs_codec_TestModule_Point = { + const __bjs_codec_M10TestModuleT5Point = { lower: (v) => { - structHelpers.Point.lower(v); + structHelpers.M10TestModuleT5Point.lower(v); }, lift: () => { - const struct = structHelpers.Point.lift(); + const struct = structHelpers.M10TestModuleT5Point.lift(); return struct; }, }; - const __bjs_codec_Optional_TestModule_Point = __bjs_optionalCodec(__bjs_codec_TestModule_Point); - const __bjs_codec_TestModule_User = { + const __bjs_codec_Optional_M10TestModuleT5Point = __bjs_optionalCodec(__bjs_codec_M10TestModuleT5Point); + const __bjs_codec_M10TestModuleT4User = { lower: (v) => { ptrStack.push(v.pointer); }, @@ -479,7 +479,7 @@ export async function createInstantiator(options, swift) { return obj; }, }; - const __bjs_codec_Optional_TestModule_User = __bjs_optionalCodec(__bjs_codec_TestModule_User); + const __bjs_codec_Optional_M10TestModuleT4User = __bjs_optionalCodec(__bjs_codec_M10TestModuleT4User); const __bjs_codec_JSObject = { lower: (v) => { const objId = swift.memory.retain(v); @@ -493,20 +493,20 @@ export async function createInstantiator(options, swift) { }, }; const __bjs_codec_Optional_JSObject = __bjs_optionalCodec(__bjs_codec_JSObject); - const __bjs_codec_TestModule_APIResult = { + const __bjs_codec_M10TestModuleT9APIResult = { lower: (v) => { - const caseId = enumHelpers.APIResult.lower(v); + const caseId = enumHelpers.M10TestModuleT9APIResult.lower(v); i32Stack.push(caseId); }, lift: () => { - const enumValue = enumHelpers.APIResult.lift(i32Stack.pop()); + const enumValue = enumHelpers.M10TestModuleT9APIResult.lift(i32Stack.pop()); return enumValue; }, }; - const __bjs_codec_Optional_TestModule_APIResult = __bjs_optionalCodec(__bjs_codec_TestModule_APIResult); + const __bjs_codec_Optional_M10TestModuleT9APIResult = __bjs_optionalCodec(__bjs_codec_M10TestModuleT9APIResult); const __bjs_codec_Optional_Array_Int = __bjs_optionalCodec(__bjs_codec_Array_Int); - const __bjs_createPointHelpers = () => ({ + const __bjs_createStructHelpers_M10TestModuleT5Point = () => ({ lower: (value) => { f64Stack.push(value.x); f64Stack.push(value.y); @@ -517,7 +517,7 @@ export async function createInstantiator(options, swift) { return { x: f641, y: f64 }; } }); - const __bjs_createAPIResultValuesHelpers = () => ({ + const __bjs_createEnumHelpers_M10TestModuleT9APIResult = () => ({ lower: (value) => { const enumTag = value.tag; switch (enumTag) { @@ -578,7 +578,7 @@ export async function createInstantiator(options, swift) { } } }); - const __bjs_createComplexResultValuesHelpers = () => ({ + const __bjs_createEnumHelpers_M10TestModuleT13ComplexResult = () => ({ lower: (value) => { const enumTag = value.tag; switch (enumTag) { @@ -680,7 +680,7 @@ export async function createInstantiator(options, swift) { } } }); - const __bjs_createResultValuesHelpers = () => ({ + const __bjs_createEnumHelpers_M10TestModuleT9UtilitiesT6Result = () => ({ lower: (value) => { const enumTag = value.tag; switch (enumTag) { @@ -733,7 +733,7 @@ export async function createInstantiator(options, swift) { } } }); - const __bjs_createNetworkingResultValuesHelpers = () => ({ + const __bjs_createEnumHelpers_M10TestModuleT16NetworkingResult = () => ({ lower: (value) => { const enumTag = value.tag; switch (enumTag) { @@ -771,7 +771,7 @@ export async function createInstantiator(options, swift) { } } }); - const __bjs_createAPIOptionalResultValuesHelpers = () => ({ + const __bjs_createEnumHelpers_M10TestModuleT17APIOptionalResult = () => ({ lower: (value) => { const enumTag = value.tag; switch (enumTag) { @@ -815,7 +815,7 @@ export async function createInstantiator(options, swift) { } } }); - const __bjs_createTypedPayloadResultValuesHelpers = () => ({ + const __bjs_createEnumHelpers_M10TestModuleT18TypedPayloadResult = () => ({ lower: (value) => { const enumTag = value.tag; switch (enumTag) { @@ -828,11 +828,11 @@ export async function createInstantiator(options, swift) { return TypedPayloadResultValues.Tag.Direction; } case TypedPayloadResultValues.Tag.OptPrecision: { - __bjs_codec_Optional_TestModule_Precision.lower(value.param0); + __bjs_codec_Optional_M10TestModuleT9Precision.lower(value.param0); return TypedPayloadResultValues.Tag.OptPrecision; } case TypedPayloadResultValues.Tag.OptDirection: { - __bjs_codec_Optional_TestModule_CardinalDirection.lower(value.param0); + __bjs_codec_Optional_M10TestModuleT17CardinalDirection.lower(value.param0); return TypedPayloadResultValues.Tag.OptDirection; } case TypedPayloadResultValues.Tag.Empty: { @@ -853,11 +853,11 @@ export async function createInstantiator(options, swift) { return { tag: TypedPayloadResultValues.Tag.Direction, param0: caseId }; } case TypedPayloadResultValues.Tag.OptPrecision: { - const optValue = __bjs_codec_Optional_TestModule_Precision.lift(); + const optValue = __bjs_codec_Optional_M10TestModuleT9Precision.lift(); return { tag: TypedPayloadResultValues.Tag.OptPrecision, param0: optValue }; } case TypedPayloadResultValues.Tag.OptDirection: { - const optValue = __bjs_codec_Optional_TestModule_CardinalDirection.lift(); + const optValue = __bjs_codec_Optional_M10TestModuleT17CardinalDirection.lift(); return { tag: TypedPayloadResultValues.Tag.OptDirection, param0: optValue }; } case TypedPayloadResultValues.Tag.Empty: return { tag: TypedPayloadResultValues.Tag.Empty }; @@ -865,12 +865,12 @@ export async function createInstantiator(options, swift) { } } }); - const __bjs_createAllTypesResultValuesHelpers = () => ({ + const __bjs_createEnumHelpers_M10TestModuleT14AllTypesResult = () => ({ lower: (value) => { const enumTag = value.tag; switch (enumTag) { case AllTypesResultValues.Tag.StructPayload: { - structHelpers.Point.lower(value.param0); + structHelpers.M10TestModuleT5Point.lower(value.param0); return AllTypesResultValues.Tag.StructPayload; } case AllTypesResultValues.Tag.ClassPayload: { @@ -883,7 +883,7 @@ export async function createInstantiator(options, swift) { return AllTypesResultValues.Tag.JsObjectPayload; } case AllTypesResultValues.Tag.NestedEnum: { - const caseId = enumHelpers.APIResult.lower(value.param0); + const caseId = enumHelpers.M10TestModuleT9APIResult.lower(value.param0); i32Stack.push(caseId); return AllTypesResultValues.Tag.NestedEnum; } @@ -901,7 +901,7 @@ export async function createInstantiator(options, swift) { tag = tag | 0; switch (tag) { case AllTypesResultValues.Tag.StructPayload: { - const struct = structHelpers.Point.lift(); + const struct = structHelpers.M10TestModuleT5Point.lift(); return { tag: AllTypesResultValues.Tag.StructPayload, param0: struct }; } case AllTypesResultValues.Tag.ClassPayload: { @@ -916,7 +916,7 @@ export async function createInstantiator(options, swift) { return { tag: AllTypesResultValues.Tag.JsObjectPayload, param0: obj }; } case AllTypesResultValues.Tag.NestedEnum: { - const enumValue = enumHelpers.APIResult.lift(i32Stack.pop()); + const enumValue = enumHelpers.M10TestModuleT9APIResult.lift(i32Stack.pop()); return { tag: AllTypesResultValues.Tag.NestedEnum, param0: enumValue }; } case AllTypesResultValues.Tag.ArrayPayload: { @@ -928,16 +928,16 @@ export async function createInstantiator(options, swift) { } } }); - const __bjs_createOptionalAllTypesResultValuesHelpers = () => ({ + const __bjs_createEnumHelpers_M10TestModuleT22OptionalAllTypesResult = () => ({ lower: (value) => { const enumTag = value.tag; switch (enumTag) { case OptionalAllTypesResultValues.Tag.OptStruct: { - __bjs_codec_Optional_TestModule_Point.lower(value.param0); + __bjs_codec_Optional_M10TestModuleT5Point.lower(value.param0); return OptionalAllTypesResultValues.Tag.OptStruct; } case OptionalAllTypesResultValues.Tag.OptClass: { - __bjs_codec_Optional_TestModule_User.lower(value.param0); + __bjs_codec_Optional_M10TestModuleT4User.lower(value.param0); return OptionalAllTypesResultValues.Tag.OptClass; } case OptionalAllTypesResultValues.Tag.OptJSObject: { @@ -945,7 +945,7 @@ export async function createInstantiator(options, swift) { return OptionalAllTypesResultValues.Tag.OptJSObject; } case OptionalAllTypesResultValues.Tag.OptNestedEnum: { - __bjs_codec_Optional_TestModule_APIResult.lower(value.param0); + __bjs_codec_Optional_M10TestModuleT9APIResult.lower(value.param0); return OptionalAllTypesResultValues.Tag.OptNestedEnum; } case OptionalAllTypesResultValues.Tag.OptArray: { @@ -962,11 +962,11 @@ export async function createInstantiator(options, swift) { tag = tag | 0; switch (tag) { case OptionalAllTypesResultValues.Tag.OptStruct: { - const optValue = __bjs_codec_Optional_TestModule_Point.lift(); + const optValue = __bjs_codec_Optional_M10TestModuleT5Point.lift(); return { tag: OptionalAllTypesResultValues.Tag.OptStruct, param0: optValue }; } case OptionalAllTypesResultValues.Tag.OptClass: { - const optValue = __bjs_codec_Optional_TestModule_User.lift(); + const optValue = __bjs_codec_Optional_M10TestModuleT4User.lift(); return { tag: OptionalAllTypesResultValues.Tag.OptClass, param0: optValue }; } case OptionalAllTypesResultValues.Tag.OptJSObject: { @@ -974,7 +974,7 @@ export async function createInstantiator(options, swift) { return { tag: OptionalAllTypesResultValues.Tag.OptJSObject, param0: optValue }; } case OptionalAllTypesResultValues.Tag.OptNestedEnum: { - const optValue = __bjs_codec_Optional_TestModule_APIResult.lift(); + const optValue = __bjs_codec_Optional_M10TestModuleT9APIResult.lift(); return { tag: OptionalAllTypesResultValues.Tag.OptNestedEnum, param0: optValue }; } case OptionalAllTypesResultValues.Tag.OptArray: { @@ -1062,10 +1062,10 @@ export async function createInstantiator(options, swift) { taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_Point"] = function(objectId) { - structHelpers.Point.lower(swift.memory.getObject(objectId)); + structHelpers.M10TestModuleT5Point.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_Point"] = function() { - const value = structHelpers.Point.lift(); + const value = structHelpers.M10TestModuleT5Point.lift(); return swift.memory.retain(value); } bjs["bjs_core_register_type_handles"] = function() {}; @@ -1247,139 +1247,139 @@ export async function createInstantiator(options, swift) { } } - const PointHelpers = __bjs_createPointHelpers(); - structHelpers.Point = PointHelpers; + const __bjs_helpers_M10TestModuleT5Point = __bjs_createStructHelpers_M10TestModuleT5Point(); + structHelpers.M10TestModuleT5Point = __bjs_helpers_M10TestModuleT5Point; - const APIResultHelpers = __bjs_createAPIResultValuesHelpers(); - enumHelpers.APIResult = APIResultHelpers; + const __bjs_helpers_M10TestModuleT9APIResult = __bjs_createEnumHelpers_M10TestModuleT9APIResult(); + enumHelpers.M10TestModuleT9APIResult = __bjs_helpers_M10TestModuleT9APIResult; - const ComplexResultHelpers = __bjs_createComplexResultValuesHelpers(); - enumHelpers.ComplexResult = ComplexResultHelpers; + const __bjs_helpers_M10TestModuleT13ComplexResult = __bjs_createEnumHelpers_M10TestModuleT13ComplexResult(); + enumHelpers.M10TestModuleT13ComplexResult = __bjs_helpers_M10TestModuleT13ComplexResult; - const ResultHelpers = __bjs_createResultValuesHelpers(); - enumHelpers.Result = ResultHelpers; + const __bjs_helpers_M10TestModuleT9UtilitiesT6Result = __bjs_createEnumHelpers_M10TestModuleT9UtilitiesT6Result(); + enumHelpers.M10TestModuleT9UtilitiesT6Result = __bjs_helpers_M10TestModuleT9UtilitiesT6Result; - const NetworkingResultHelpers = __bjs_createNetworkingResultValuesHelpers(); - enumHelpers.NetworkingResult = NetworkingResultHelpers; + const __bjs_helpers_M10TestModuleT16NetworkingResult = __bjs_createEnumHelpers_M10TestModuleT16NetworkingResult(); + enumHelpers.M10TestModuleT16NetworkingResult = __bjs_helpers_M10TestModuleT16NetworkingResult; - const APIOptionalResultHelpers = __bjs_createAPIOptionalResultValuesHelpers(); - enumHelpers.APIOptionalResult = APIOptionalResultHelpers; + const __bjs_helpers_M10TestModuleT17APIOptionalResult = __bjs_createEnumHelpers_M10TestModuleT17APIOptionalResult(); + enumHelpers.M10TestModuleT17APIOptionalResult = __bjs_helpers_M10TestModuleT17APIOptionalResult; - const TypedPayloadResultHelpers = __bjs_createTypedPayloadResultValuesHelpers(); - enumHelpers.TypedPayloadResult = TypedPayloadResultHelpers; + const __bjs_helpers_M10TestModuleT18TypedPayloadResult = __bjs_createEnumHelpers_M10TestModuleT18TypedPayloadResult(); + enumHelpers.M10TestModuleT18TypedPayloadResult = __bjs_helpers_M10TestModuleT18TypedPayloadResult; - const AllTypesResultHelpers = __bjs_createAllTypesResultValuesHelpers(); - enumHelpers.AllTypesResult = AllTypesResultHelpers; + const __bjs_helpers_M10TestModuleT14AllTypesResult = __bjs_createEnumHelpers_M10TestModuleT14AllTypesResult(); + enumHelpers.M10TestModuleT14AllTypesResult = __bjs_helpers_M10TestModuleT14AllTypesResult; - const OptionalAllTypesResultHelpers = __bjs_createOptionalAllTypesResultValuesHelpers(); - enumHelpers.OptionalAllTypesResult = OptionalAllTypesResultHelpers; + const __bjs_helpers_M10TestModuleT22OptionalAllTypesResult = __bjs_createEnumHelpers_M10TestModuleT22OptionalAllTypesResult(); + enumHelpers.M10TestModuleT22OptionalAllTypesResult = __bjs_helpers_M10TestModuleT22OptionalAllTypesResult; const exports = { handle: function bjs_handle(result) { - const resultCaseId = enumHelpers.APIResult.lower(result); + const resultCaseId = enumHelpers.M10TestModuleT9APIResult.lower(result); instance.exports.bjs_handle(resultCaseId); }, getResult: function bjs_getResult() { instance.exports.bjs_getResult(); - const ret = enumHelpers.APIResult.lift(i32Stack.pop()); + const ret = enumHelpers.M10TestModuleT9APIResult.lift(i32Stack.pop()); return ret; }, roundtripAPIResult: function bjs_roundtripAPIResult(result) { - const resultCaseId = enumHelpers.APIResult.lower(result); + const resultCaseId = enumHelpers.M10TestModuleT9APIResult.lower(result); instance.exports.bjs_roundtripAPIResult(resultCaseId); - const ret = enumHelpers.APIResult.lift(i32Stack.pop()); + const ret = enumHelpers.M10TestModuleT9APIResult.lift(i32Stack.pop()); return ret; }, roundTripOptionalAPIResult: function bjs_roundTripOptionalAPIResult(result) { const isSome = result != null; let result1; if (isSome) { - const resultCaseId = enumHelpers.APIResult.lower(result); + const resultCaseId = enumHelpers.M10TestModuleT9APIResult.lower(result); result1 = resultCaseId; } else { result1 = 0; } instance.exports.bjs_roundTripOptionalAPIResult(+isSome, result1); const tag = i32Stack.pop(); - const optResult = tag === -1 ? null : enumHelpers.APIResult.lift(tag); + const optResult = tag === -1 ? null : enumHelpers.M10TestModuleT9APIResult.lift(tag); return optResult; }, handleComplex: function bjs_handleComplex(result) { - const resultCaseId = enumHelpers.ComplexResult.lower(result); + const resultCaseId = enumHelpers.M10TestModuleT13ComplexResult.lower(result); instance.exports.bjs_handleComplex(resultCaseId); }, getComplexResult: function bjs_getComplexResult() { instance.exports.bjs_getComplexResult(); - const ret = enumHelpers.ComplexResult.lift(i32Stack.pop()); + const ret = enumHelpers.M10TestModuleT13ComplexResult.lift(i32Stack.pop()); return ret; }, roundtripComplexResult: function bjs_roundtripComplexResult(result) { - const resultCaseId = enumHelpers.ComplexResult.lower(result); + const resultCaseId = enumHelpers.M10TestModuleT13ComplexResult.lower(result); instance.exports.bjs_roundtripComplexResult(resultCaseId); - const ret = enumHelpers.ComplexResult.lift(i32Stack.pop()); + const ret = enumHelpers.M10TestModuleT13ComplexResult.lift(i32Stack.pop()); return ret; }, roundTripOptionalComplexResult: function bjs_roundTripOptionalComplexResult(result) { const isSome = result != null; let result1; if (isSome) { - const resultCaseId = enumHelpers.ComplexResult.lower(result); + const resultCaseId = enumHelpers.M10TestModuleT13ComplexResult.lower(result); result1 = resultCaseId; } else { result1 = 0; } instance.exports.bjs_roundTripOptionalComplexResult(+isSome, result1); const tag = i32Stack.pop(); - const optResult = tag === -1 ? null : enumHelpers.ComplexResult.lift(tag); + const optResult = tag === -1 ? null : enumHelpers.M10TestModuleT13ComplexResult.lift(tag); return optResult; }, roundTripOptionalUtilitiesResult: function bjs_roundTripOptionalUtilitiesResult(result) { const isSome = result != null; let result1; if (isSome) { - const resultCaseId = enumHelpers.Result.lower(result); + const resultCaseId = enumHelpers.M10TestModuleT9UtilitiesT6Result.lower(result); result1 = resultCaseId; } else { result1 = 0; } instance.exports.bjs_roundTripOptionalUtilitiesResult(+isSome, result1); const tag = i32Stack.pop(); - const optResult = tag === -1 ? null : enumHelpers.Result.lift(tag); + const optResult = tag === -1 ? null : enumHelpers.M10TestModuleT9UtilitiesT6Result.lift(tag); return optResult; }, roundTripOptionalNetworkingResult: function bjs_roundTripOptionalNetworkingResult(result) { const isSome = result != null; let result1; if (isSome) { - const resultCaseId = enumHelpers.NetworkingResult.lower(result); + const resultCaseId = enumHelpers.M10TestModuleT16NetworkingResult.lower(result); result1 = resultCaseId; } else { result1 = 0; } instance.exports.bjs_roundTripOptionalNetworkingResult(+isSome, result1); const tag = i32Stack.pop(); - const optResult = tag === -1 ? null : enumHelpers.NetworkingResult.lift(tag); + const optResult = tag === -1 ? null : enumHelpers.M10TestModuleT16NetworkingResult.lift(tag); return optResult; }, roundTripOptionalAPIOptionalResult: function bjs_roundTripOptionalAPIOptionalResult(result) { const isSome = result != null; let result1; if (isSome) { - const resultCaseId = enumHelpers.APIOptionalResult.lower(result); + const resultCaseId = enumHelpers.M10TestModuleT17APIOptionalResult.lower(result); result1 = resultCaseId; } else { result1 = 0; } instance.exports.bjs_roundTripOptionalAPIOptionalResult(+isSome, result1); const tag = i32Stack.pop(); - const optResult = tag === -1 ? null : enumHelpers.APIOptionalResult.lift(tag); + const optResult = tag === -1 ? null : enumHelpers.M10TestModuleT17APIOptionalResult.lift(tag); return optResult; }, compareAPIResults: function bjs_compareAPIResults(result1, result2) { const isSome = result1 != null; let result; if (isSome) { - const result1CaseId = enumHelpers.APIOptionalResult.lower(result1); + const result1CaseId = enumHelpers.M10TestModuleT17APIOptionalResult.lower(result1); result = result1CaseId; } else { result = 0; @@ -1387,74 +1387,74 @@ export async function createInstantiator(options, swift) { const isSome1 = result2 != null; let result3; if (isSome1) { - const result2CaseId = enumHelpers.APIOptionalResult.lower(result2); + const result2CaseId = enumHelpers.M10TestModuleT17APIOptionalResult.lower(result2); result3 = result2CaseId; } else { result3 = 0; } instance.exports.bjs_compareAPIResults(+isSome, result, +isSome1, result3); const tag = i32Stack.pop(); - const optResult = tag === -1 ? null : enumHelpers.APIOptionalResult.lift(tag); + const optResult = tag === -1 ? null : enumHelpers.M10TestModuleT17APIOptionalResult.lift(tag); return optResult; }, roundTripTypedPayloadResult: function bjs_roundTripTypedPayloadResult(result) { - const resultCaseId = enumHelpers.TypedPayloadResult.lower(result); + const resultCaseId = enumHelpers.M10TestModuleT18TypedPayloadResult.lower(result); instance.exports.bjs_roundTripTypedPayloadResult(resultCaseId); - const ret = enumHelpers.TypedPayloadResult.lift(i32Stack.pop()); + const ret = enumHelpers.M10TestModuleT18TypedPayloadResult.lift(i32Stack.pop()); return ret; }, roundTripOptionalTypedPayloadResult: function bjs_roundTripOptionalTypedPayloadResult(result) { const isSome = result != null; let result1; if (isSome) { - const resultCaseId = enumHelpers.TypedPayloadResult.lower(result); + const resultCaseId = enumHelpers.M10TestModuleT18TypedPayloadResult.lower(result); result1 = resultCaseId; } else { result1 = 0; } instance.exports.bjs_roundTripOptionalTypedPayloadResult(+isSome, result1); const tag = i32Stack.pop(); - const optResult = tag === -1 ? null : enumHelpers.TypedPayloadResult.lift(tag); + const optResult = tag === -1 ? null : enumHelpers.M10TestModuleT18TypedPayloadResult.lift(tag); return optResult; }, roundTripAllTypesResult: function bjs_roundTripAllTypesResult(result) { - const resultCaseId = enumHelpers.AllTypesResult.lower(result); + const resultCaseId = enumHelpers.M10TestModuleT14AllTypesResult.lower(result); instance.exports.bjs_roundTripAllTypesResult(resultCaseId); - const ret = enumHelpers.AllTypesResult.lift(i32Stack.pop()); + const ret = enumHelpers.M10TestModuleT14AllTypesResult.lift(i32Stack.pop()); return ret; }, roundTripOptionalAllTypesResult: function bjs_roundTripOptionalAllTypesResult(result) { const isSome = result != null; let result1; if (isSome) { - const resultCaseId = enumHelpers.AllTypesResult.lower(result); + const resultCaseId = enumHelpers.M10TestModuleT14AllTypesResult.lower(result); result1 = resultCaseId; } else { result1 = 0; } instance.exports.bjs_roundTripOptionalAllTypesResult(+isSome, result1); const tag = i32Stack.pop(); - const optResult = tag === -1 ? null : enumHelpers.AllTypesResult.lift(tag); + const optResult = tag === -1 ? null : enumHelpers.M10TestModuleT14AllTypesResult.lift(tag); return optResult; }, roundTripOptionalPayloadResult: function bjs_roundTripOptionalPayloadResult(result) { - const resultCaseId = enumHelpers.OptionalAllTypesResult.lower(result); + const resultCaseId = enumHelpers.M10TestModuleT22OptionalAllTypesResult.lower(result); instance.exports.bjs_roundTripOptionalPayloadResult(resultCaseId); - const ret = enumHelpers.OptionalAllTypesResult.lift(i32Stack.pop()); + const ret = enumHelpers.M10TestModuleT22OptionalAllTypesResult.lift(i32Stack.pop()); return ret; }, roundTripOptionalPayloadResultOpt: function bjs_roundTripOptionalPayloadResultOpt(result) { const isSome = result != null; let result1; if (isSome) { - const resultCaseId = enumHelpers.OptionalAllTypesResult.lower(result); + const resultCaseId = enumHelpers.M10TestModuleT22OptionalAllTypesResult.lower(result); result1 = resultCaseId; } else { result1 = 0; } instance.exports.bjs_roundTripOptionalPayloadResultOpt(+isSome, result1); const tag = i32Stack.pop(); - const optResult = tag === -1 ? null : enumHelpers.OptionalAllTypesResult.lift(tag); + const optResult = tag === -1 ? null : enumHelpers.M10TestModuleT22OptionalAllTypesResult.lift(tag); return optResult; }, APIResult: APIResultValues, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js index bc0df916b..07fe91654 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js @@ -38,7 +38,7 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; - const __bjs_createPayloadSignalValuesHelpers = () => ({ + const __bjs_createEnumHelpers_M10TestModuleT13PayloadSignal = () => ({ lower: (value) => { const enumTag = value.tag; switch (enumTag) { @@ -252,9 +252,9 @@ export async function createInstantiator(options, swift) { const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; TestModule["bjs_PayloadSignalControls_roundTrip_static"] = function bjs_PayloadSignalControls_roundTrip_static(signal) { try { - const enumValue = enumHelpers.PayloadSignal.lift(signal); + const enumValue = enumHelpers.M10TestModuleT13PayloadSignal.lift(signal); let ret = imports.PayloadSignalControls.roundTrip(enumValue); - const caseId = enumHelpers.PayloadSignal.lower(ret); + const caseId = enumHelpers.M10TestModuleT13PayloadSignal.lower(ret); return caseId; } catch (error) { setException(error); @@ -262,7 +262,7 @@ export async function createInstantiator(options, swift) { } TestModule["bjs_PayloadSignalControls_send"] = function bjs_PayloadSignalControls_send(self, signal) { try { - const enumValue = enumHelpers.PayloadSignal.lift(signal); + const enumValue = enumHelpers.M10TestModuleT13PayloadSignal.lift(signal); swift.memory.getObject(self).send(enumValue); } catch (error) { setException(error); @@ -271,7 +271,7 @@ export async function createInstantiator(options, swift) { TestModule["bjs_PayloadSignalControls_current"] = function bjs_PayloadSignalControls_current(self) { try { let ret = swift.memory.getObject(self).current(); - const caseId = enumHelpers.PayloadSignal.lower(ret); + const caseId = enumHelpers.M10TestModuleT13PayloadSignal.lower(ret); return caseId; } catch (error) { setException(error); @@ -281,7 +281,7 @@ export async function createInstantiator(options, swift) { try { let optResult; if (signalIsSome) { - const enumValue = enumHelpers.PayloadSignal.lift(signalCaseId); + const enumValue = enumHelpers.M10TestModuleT13PayloadSignal.lift(signalCaseId); optResult = enumValue; } else { optResult = null; @@ -289,7 +289,7 @@ export async function createInstantiator(options, swift) { let ret = swift.memory.getObject(self).roundTripOptional(optResult); const isSome = ret != null; if (isSome) { - const caseId = enumHelpers.PayloadSignal.lower(ret); + const caseId = enumHelpers.M10TestModuleT13PayloadSignal.lower(ret); return caseId; } else { return -1; @@ -312,8 +312,8 @@ export async function createInstantiator(options, swift) { /** @param {WebAssembly.Instance} instance */ createExports: (instance) => { const js = swift.memory.heap; - const PayloadSignalHelpers = __bjs_createPayloadSignalValuesHelpers(); - enumHelpers.PayloadSignal = PayloadSignalHelpers; + const __bjs_helpers_M10TestModuleT13PayloadSignal = __bjs_createEnumHelpers_M10TestModuleT13PayloadSignal(); + enumHelpers.M10TestModuleT13PayloadSignal = __bjs_helpers_M10TestModuleT13PayloadSignal; const exports = { PayloadSignal: PayloadSignalValues, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js index 082aa6c38..09e03e44a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumRawType.js @@ -429,7 +429,7 @@ export async function createInstantiator(options, swift) { return jsValue; } - const __bjs_codec_TestModule_FileSize = { + const __bjs_codec_M10TestModuleT8FileSize = { lower: (v) => { i64Stack.push(v); }, @@ -438,8 +438,8 @@ export async function createInstantiator(options, swift) { return rawValue; }, }; - const __bjs_codec_Optional_TestModule_FileSize = __bjs_optionalCodec(__bjs_codec_TestModule_FileSize); - const __bjs_codec_TestModule_SessionId = { + const __bjs_codec_Optional_M10TestModuleT8FileSize = __bjs_optionalCodec(__bjs_codec_M10TestModuleT8FileSize); + const __bjs_codec_M10TestModuleT9SessionId = { lower: (v) => { i64Stack.push(v); }, @@ -448,7 +448,7 @@ export async function createInstantiator(options, swift) { return rawValue; }, }; - const __bjs_codec_Optional_TestModule_SessionId = __bjs_optionalCodec(__bjs_codec_TestModule_SessionId); + const __bjs_codec_Optional_M10TestModuleT9SessionId = __bjs_optionalCodec(__bjs_codec_M10TestModuleT9SessionId); return { @@ -794,7 +794,7 @@ export async function createInstantiator(options, swift) { roundTripOptionalFileSize: function bjs_roundTripOptionalFileSize(input) { const isSome = input != null; instance.exports.bjs_roundTripOptionalFileSize(+isSome, isSome ? input : 0n); - const optValue = __bjs_codec_Optional_TestModule_FileSize.lift(); + const optValue = __bjs_codec_Optional_M10TestModuleT8FileSize.lift(); return optValue; }, setUserId: function bjs_setUserId(id) { @@ -835,7 +835,7 @@ export async function createInstantiator(options, swift) { roundTripOptionalSessionId: function bjs_roundTripOptionalSessionId(input) { const isSome = input != null; instance.exports.bjs_roundTripOptionalSessionId(+isSome, isSome ? input : 0n); - const optValue = __bjs_codec_Optional_TestModule_SessionId.lift(); + const optValue = __bjs_codec_Optional_M10TestModuleT9SessionId.lift(); return optValue; }, setPrecision: function bjs_setPrecision(precision) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js index 7a91ef9d7..d120c255e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js @@ -389,16 +389,16 @@ export async function createInstantiator(options, swift) { } const __bjs_codec_Array_Int = __bjs_arrayCodec(__bjs_primitiveCodecs.Int); - const __bjs_codec_TestModule_GenericPoint = { + const __bjs_codec_M10TestModuleT12GenericPoint = { lower: (v) => { - structHelpers.GenericPoint.lower(v); + structHelpers.M10TestModuleT12GenericPoint.lower(v); }, lift: () => { - const struct = structHelpers.GenericPoint.lift(); + const struct = structHelpers.M10TestModuleT12GenericPoint.lift(); return struct; }, }; - const __bjs_codec_TestModule_GenericImportBox = { + const __bjs_codec_M10TestModuleT16GenericImportBox = { lower: (v) => { ptrStack.push(v.pointer); }, @@ -408,7 +408,7 @@ export async function createInstantiator(options, swift) { return obj; }, }; - const __bjs_codec_TestModule_GenericColor = { + const __bjs_codec_M10TestModuleT12GenericColor = { lower: (v) => { i32Stack.push((v | 0)); }, @@ -417,18 +417,18 @@ export async function createInstantiator(options, swift) { return caseId; }, }; - const __bjs_codec_TestModule_GenericTagged = { + const __bjs_codec_M10TestModuleT13GenericTagged = { lower: (v) => { - const caseId = enumHelpers.GenericTagged.lower(v); + const caseId = enumHelpers.M10TestModuleT13GenericTagged.lower(v); i32Stack.push(caseId); }, lift: () => { - const enumValue = enumHelpers.GenericTagged.lift(i32Stack.pop()); + const enumValue = enumHelpers.M10TestModuleT13GenericTagged.lift(i32Stack.pop()); return enumValue; }, }; - const __bjs_createGenericPointHelpers = () => ({ + const __bjs_createStructHelpers_M10TestModuleT12GenericPoint = () => ({ lower: (value) => { i32Stack.push((value.x | 0)); i32Stack.push((value.y | 0)); @@ -439,7 +439,7 @@ export async function createInstantiator(options, swift) { return { x: int1, y: int }; } }); - const __bjs_createGenericTaggedValuesHelpers = () => ({ + const __bjs_createEnumHelpers_M10TestModuleT13GenericTagged = () => ({ lower: (value) => { const enumTag = value.tag; switch (enumTag) { @@ -549,10 +549,10 @@ export async function createInstantiator(options, swift) { taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_GenericPoint"] = function(objectId) { - structHelpers.GenericPoint.lower(swift.memory.getObject(objectId)); + structHelpers.M10TestModuleT12GenericPoint.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_GenericPoint"] = function() { - const value = structHelpers.GenericPoint.lift(); + const value = structHelpers.M10TestModuleT12GenericPoint.lift(); return swift.memory.retain(value); } bjs["bjs_core_register_type_handles"] = function(base, count) { @@ -573,9 +573,6 @@ export async function createInstantiator(options, swift) { __bjs_primitiveCodecs.String, __bjs_primitiveCodecs.JSValue, ]; - if (count !== codecs.length) { - throw new Error("BridgeJS: type handle registration mismatch for core types"); - } const typeIds = new Int32Array(memory.buffer, base >>> 0, count >>> 0); for (let i = 0; i < count; i++) { __bjs_codecByTypeId.set(typeIds[i], codecs[i]); @@ -583,11 +580,11 @@ export async function createInstantiator(options, swift) { } bjs["bjs_TestModule_register_type_handles"] = function(base, count) { const codecs = [ - __bjs_codec_TestModule_GenericPoint, - __bjs_codec_TestModule_GenericImportBox, - __bjs_codec_TestModule_GenericColor, + __bjs_codec_M10TestModuleT12GenericPoint, + __bjs_codec_M10TestModuleT16GenericImportBox, + __bjs_codec_M10TestModuleT12GenericColor, __bjs_stringCodec, - __bjs_codec_TestModule_GenericTagged, + __bjs_codec_M10TestModuleT13GenericTagged, ]; const typeIds = new Int32Array(memory.buffer, base >>> 0, count >>> 0); for (let i = 0; i < count; i++) { @@ -930,11 +927,11 @@ export async function createInstantiator(options, swift) { instance.exports.bjs_GenericImportBox_value_set(this.pointer, value); } } - const GenericPointHelpers = __bjs_createGenericPointHelpers(); - structHelpers.GenericPoint = GenericPointHelpers; + const __bjs_helpers_M10TestModuleT12GenericPoint = __bjs_createStructHelpers_M10TestModuleT12GenericPoint(); + structHelpers.M10TestModuleT12GenericPoint = __bjs_helpers_M10TestModuleT12GenericPoint; - const GenericTaggedHelpers = __bjs_createGenericTaggedValuesHelpers(); - enumHelpers.GenericTagged = GenericTaggedHelpers; + const __bjs_helpers_M10TestModuleT13GenericTagged = __bjs_createEnumHelpers_M10TestModuleT13GenericTagged(); + enumHelpers.M10TestModuleT13GenericTagged = __bjs_helpers_M10TestModuleT13GenericTagged; const exports = { GenericColor: GenericColorValues, @@ -946,4 +943,4 @@ export async function createInstantiator(options, swift) { return exports; }, } -} +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js index 1a95bcb6e..363f6c595 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportedTypeInExportedInterface.js @@ -354,7 +354,7 @@ export async function createInstantiator(options, swift) { return jsValue; } - const __bjs_codec_TestModule_Foo = { + const __bjs_codec_Foo = { lower: (v) => { const objId = swift.memory.retain(v); i32Stack.push(objId); @@ -366,11 +366,11 @@ export async function createInstantiator(options, swift) { return obj; }, }; - const __bjs_codec_Array_TestModule_Foo = __bjs_arrayCodec(__bjs_codec_TestModule_Foo); - const __bjs_codec_Optional_TestModule_Foo = __bjs_optionalCodec(__bjs_codec_TestModule_Foo); - const __bjs_codec_Array_Optional_TestModule_Foo = __bjs_arrayCodec(__bjs_codec_Optional_TestModule_Foo); + const __bjs_codec_Array_Foo = __bjs_arrayCodec(__bjs_codec_Foo); + const __bjs_codec_Optional_Foo = __bjs_optionalCodec(__bjs_codec_Foo); + const __bjs_codec_Array_Optional_Foo = __bjs_arrayCodec(__bjs_codec_Optional_Foo); - const __bjs_createFooContainerHelpers = () => ({ + const __bjs_createStructHelpers_M10TestModuleT12FooContainer = () => ({ lower: (value) => { let id; if (value.foo != null) { @@ -379,10 +379,10 @@ export async function createInstantiator(options, swift) { id = undefined; } i32Stack.push(id !== undefined ? id : 0); - __bjs_codec_Optional_TestModule_Foo.lower(value.optionalFoo); + __bjs_codec_Optional_Foo.lower(value.optionalFoo); }, lift: () => { - const optValue = __bjs_codec_Optional_TestModule_Foo.lift(); + const optValue = __bjs_codec_Optional_Foo.lift(); const objectId = i32Stack.pop(); let value; if (objectId !== 0) { @@ -471,10 +471,10 @@ export async function createInstantiator(options, swift) { taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_FooContainer"] = function(objectId) { - structHelpers.FooContainer.lower(swift.memory.getObject(objectId)); + structHelpers.M10TestModuleT12FooContainer.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_FooContainer"] = function() { - const value = structHelpers.FooContainer.lift(); + const value = structHelpers.M10TestModuleT12FooContainer.lift(); return swift.memory.retain(value); } bjs["bjs_core_register_type_handles"] = function() {}; @@ -599,8 +599,8 @@ export async function createInstantiator(options, swift) { /** @param {WebAssembly.Instance} instance */ createExports: (instance) => { const js = swift.memory.heap; - const FooContainerHelpers = __bjs_createFooContainerHelpers(); - structHelpers.FooContainer = FooContainerHelpers; + const __bjs_helpers_M10TestModuleT12FooContainer = __bjs_createStructHelpers_M10TestModuleT12FooContainer(); + structHelpers.M10TestModuleT12FooContainer = __bjs_helpers_M10TestModuleT12FooContainer; const exports = { makeFoo: function bjs_makeFoo() { @@ -616,21 +616,21 @@ export async function createInstantiator(options, swift) { return ret1; }, processFooArray: function bjs_processFooArray(foos) { - __bjs_codec_Array_TestModule_Foo.lower(foos); + __bjs_codec_Array_Foo.lower(foos); instance.exports.bjs_processFooArray(); - const arrayResult = __bjs_codec_Array_TestModule_Foo.lift(); + const arrayResult = __bjs_codec_Array_Foo.lift(); return arrayResult; }, processOptionalFooArray: function bjs_processOptionalFooArray(foos) { - __bjs_codec_Array_Optional_TestModule_Foo.lower(foos); + __bjs_codec_Array_Optional_Foo.lower(foos); instance.exports.bjs_processOptionalFooArray(); - const arrayResult = __bjs_codec_Array_Optional_TestModule_Foo.lift(); + const arrayResult = __bjs_codec_Array_Optional_Foo.lift(); return arrayResult; }, roundtripFooContainer: function bjs_roundtripFooContainer(container) { - structHelpers.FooContainer.lower(container); + structHelpers.M10TestModuleT12FooContainer.lower(container); instance.exports.bjs_roundtripFooContainer(); - const structValue = structHelpers.FooContainer.lift(); + const structValue = structHelpers.M10TestModuleT12FooContainer.lift(); return structValue; }, }; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.js index 7d11a24ff..68ac11976 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/JSNameOverride.js @@ -36,7 +36,7 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; - const __bjs_createRenamedVectorHelpers = () => ({ + const __bjs_createStructHelpers_M10TestModuleT13RenamedVector = () => ({ lower: (value) => { f64Stack.push(value.dx); f64Stack.push(value.dy); @@ -46,7 +46,7 @@ export async function createInstantiator(options, swift) { const f641 = f64Stack.pop(); const instance1 = { dx: f641, dy: f64 }; instance1.magnitude = function() { - structHelpers.RenamedVector.lower(this); + structHelpers.M10TestModuleT13RenamedVector.lower(this); const ret = instance.exports.bjs_RenamedVector_magnitude(); return ret; }.bind(instance1); @@ -129,10 +129,10 @@ export async function createInstantiator(options, swift) { taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_RenamedVector"] = function(objectId) { - structHelpers.RenamedVector.lower(swift.memory.getObject(objectId)); + structHelpers.M10TestModuleT13RenamedVector.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_RenamedVector"] = function() { - const value = structHelpers.RenamedVector.lift(); + const value = structHelpers.M10TestModuleT13RenamedVector.lift(); return swift.memory.retain(value); } bjs["bjs_core_register_type_handles"] = function() {}; @@ -356,8 +356,8 @@ export async function createInstantiator(options, swift) { return ret; } } - const RenamedVectorHelpers = __bjs_createRenamedVectorHelpers(); - structHelpers.RenamedVector = RenamedVectorHelpers; + const __bjs_helpers_M10TestModuleT13RenamedVector = __bjs_createStructHelpers_M10TestModuleT13RenamedVector(); + structHelpers.M10TestModuleT13RenamedVector = __bjs_helpers_M10TestModuleT13RenamedVector; const exports = { makeGreeting: function bjs_makeGreeting(name) { @@ -419,12 +419,12 @@ export async function createInstantiator(options, swift) { RenamedVector: { get originVector() { instance.exports.bjs_RenamedVector_static_origin_get(); - const structValue = structHelpers.RenamedVector.lift(); + const structValue = structHelpers.M10TestModuleT13RenamedVector.lift(); return structValue; }, fromPolar: function(radius, angle) { instance.exports.bjs_RenamedVector_static_fromPolar(radius, angle); - const structValue = structHelpers.RenamedVector.lift(); + const structValue = structHelpers.M10TestModuleT13RenamedVector.lift(); return structValue; }, }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js index 024ef49c1..ea49220de 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.Global.js @@ -354,7 +354,7 @@ export async function createInstantiator(options, swift) { return jsValue; } - const __bjs_codec_TestModule_Greeter = { + const __bjs_codec_M10TestModuleT7Greeter = { lower: (v) => { ptrStack.push(v.pointer); }, @@ -364,7 +364,7 @@ export async function createInstantiator(options, swift) { return obj; }, }; - const __bjs_codec_Array_TestModule_Greeter = __bjs_arrayCodec(__bjs_codec_TestModule_Greeter); + const __bjs_codec_Array_M10TestModuleT7Greeter = __bjs_arrayCodec(__bjs_codec_M10TestModuleT7Greeter); return { @@ -692,7 +692,7 @@ export async function createInstantiator(options, swift) { } getItems() { instance.exports.bjs_Collections_Container_getItems(this.pointer); - const arrayResult = __bjs_codec_Array_TestModule_Greeter.lift(); + const arrayResult = __bjs_codec_Array_M10TestModuleT7Greeter.lift(); return arrayResult; } addItem(item) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js index 7da962422..25bd44d05 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Namespaces.js @@ -354,7 +354,7 @@ export async function createInstantiator(options, swift) { return jsValue; } - const __bjs_codec_TestModule_Greeter = { + const __bjs_codec_M10TestModuleT7Greeter = { lower: (v) => { ptrStack.push(v.pointer); }, @@ -364,7 +364,7 @@ export async function createInstantiator(options, swift) { return obj; }, }; - const __bjs_codec_Array_TestModule_Greeter = __bjs_arrayCodec(__bjs_codec_TestModule_Greeter); + const __bjs_codec_Array_M10TestModuleT7Greeter = __bjs_arrayCodec(__bjs_codec_M10TestModuleT7Greeter); return { @@ -692,7 +692,7 @@ export async function createInstantiator(options, swift) { } getItems() { instance.exports.bjs_Collections_Container_getItems(this.pointer); - const arrayResult = __bjs_codec_Array_TestModule_Greeter.lift(); + const arrayResult = __bjs_codec_Array_M10TestModuleT7Greeter.lift(); return arrayResult; } addItem(item) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js index ad0c75942..f57c4007b 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedType.js @@ -31,7 +31,7 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; - const __bjs_createUser_StatsHelpers = () => ({ + const __bjs_createStructHelpers_M10TestModuleT4UserT5Stats = () => ({ lower: (value) => { i32Stack.push((value.health | 0)); f64Stack.push(value.score); @@ -42,7 +42,7 @@ export async function createInstantiator(options, swift) { return { health: int, score: f64 }; } }); - const __bjs_createPlayer_StatsHelpers = () => ({ + const __bjs_createStructHelpers_M10TestModuleT6PlayerT5Stats = () => ({ lower: (value) => { i32Stack.push((value.level | 0)); const bytes = textEncoder.encode(value.rating); @@ -132,17 +132,17 @@ export async function createInstantiator(options, swift) { taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_User_Stats"] = function(objectId) { - structHelpers.User_Stats.lower(swift.memory.getObject(objectId)); + structHelpers.M10TestModuleT4UserT5Stats.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_User_Stats"] = function() { - const value = structHelpers.User_Stats.lift(); + const value = structHelpers.M10TestModuleT4UserT5Stats.lift(); return swift.memory.retain(value); } bjs["swift_js_struct_lower_Player_Stats"] = function(objectId) { - structHelpers.Player_Stats.lower(swift.memory.getObject(objectId)); + structHelpers.M10TestModuleT6PlayerT5Stats.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_Player_Stats"] = function() { - const value = structHelpers.Player_Stats.lift(); + const value = structHelpers.M10TestModuleT6PlayerT5Stats.lift(); return swift.memory.retain(value); } bjs["bjs_core_register_type_handles"] = function() {}; @@ -346,11 +346,11 @@ export async function createInstantiator(options, swift) { return ret; } } - const User_StatsHelpers = __bjs_createUser_StatsHelpers(); - structHelpers.User_Stats = User_StatsHelpers; + const __bjs_helpers_M10TestModuleT4UserT5Stats = __bjs_createStructHelpers_M10TestModuleT4UserT5Stats(); + structHelpers.M10TestModuleT4UserT5Stats = __bjs_helpers_M10TestModuleT4UserT5Stats; - const Player_StatsHelpers = __bjs_createPlayer_StatsHelpers(); - structHelpers.Player_Stats = Player_StatsHelpers; + const __bjs_helpers_M10TestModuleT6PlayerT5Stats = __bjs_createStructHelpers_M10TestModuleT6PlayerT5Stats(); + structHelpers.M10TestModuleT6PlayerT5Stats = __bjs_helpers_M10TestModuleT6PlayerT5Stats; const exports = { Player, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js index f9761419b..b63f360e9 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Optionals.js @@ -367,7 +367,7 @@ export async function createInstantiator(options, swift) { }, }; const __bjs_codec_Optional_JSObject = __bjs_optionalCodec(__bjs_codec_JSObject); - const __bjs_codec_TestModule_WithOptionalJSClass = { + const __bjs_codec_WithOptionalJSClass = { lower: (v) => { const objId = swift.memory.retain(v); i32Stack.push(objId); @@ -379,7 +379,7 @@ export async function createInstantiator(options, swift) { return obj; }, }; - const __bjs_codec_Optional_TestModule_WithOptionalJSClass = __bjs_optionalCodec(__bjs_codec_TestModule_WithOptionalJSClass); + const __bjs_codec_Optional_WithOptionalJSClass = __bjs_optionalCodec(__bjs_codec_WithOptionalJSClass); return { @@ -665,7 +665,7 @@ export async function createInstantiator(options, swift) { TestModule["bjs_WithOptionalJSClass_childOrNull_get"] = function bjs_WithOptionalJSClass_childOrNull_get(self) { try { let ret = swift.memory.getObject(self).childOrNull; - __bjs_codec_Optional_TestModule_WithOptionalJSClass.lower(ret); + __bjs_codec_Optional_WithOptionalJSClass.lower(ret); } catch (error) { setException(error); } @@ -836,7 +836,7 @@ export async function createInstantiator(options, swift) { TestModule["bjs_WithOptionalJSClass_roundTripChildOrNull"] = function bjs_WithOptionalJSClass_roundTripChildOrNull(self, valueIsSome, valueObjectId) { try { let ret = swift.memory.getObject(self).roundTripChildOrNull(valueIsSome ? swift.memory.getObject(valueObjectId) : null); - __bjs_codec_Optional_TestModule_WithOptionalJSClass.lower(ret); + __bjs_codec_Optional_WithOptionalJSClass.lower(ret); } catch (error) { setException(error); } @@ -1075,7 +1075,7 @@ export async function createInstantiator(options, swift) { result = 0; } instance.exports.bjs_roundTripExportedOptionalJSClass(+isSome, result); - const optValue = __bjs_codec_Optional_TestModule_WithOptionalJSClass.lift(); + const optValue = __bjs_codec_Optional_WithOptionalJSClass.lift(); return optValue; }, roundTripString: function bjs_roundTripString(name) { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js index 73c93c039..f0c2d3fae 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Protocol.js @@ -378,7 +378,7 @@ export async function createInstantiator(options, swift) { return jsValue; } - const __bjs_codec_TestModule_MyViewControllerDelegate = { + const __bjs_codec_M10TestModuleT24MyViewControllerDelegate = { lower: (v) => { const objId = swift.memory.retain(v); i32Stack.push(objId); @@ -390,10 +390,10 @@ export async function createInstantiator(options, swift) { return obj; }, }; - const __bjs_codec_Array_TestModule_MyViewControllerDelegate = __bjs_arrayCodec(__bjs_codec_TestModule_MyViewControllerDelegate); - const __bjs_codec_Dict_TestModule_MyViewControllerDelegate = __bjs_dictCodec(__bjs_codec_TestModule_MyViewControllerDelegate); + const __bjs_codec_Array_M10TestModuleT24MyViewControllerDelegate = __bjs_arrayCodec(__bjs_codec_M10TestModuleT24MyViewControllerDelegate); + const __bjs_codec_Dict_M10TestModuleT24MyViewControllerDelegate = __bjs_dictCodec(__bjs_codec_M10TestModuleT24MyViewControllerDelegate); - const __bjs_createResultValuesHelpers = () => ({ + const __bjs_createEnumHelpers_M10TestModuleT6Result = () => ({ lower: (value) => { const enumTag = value.tag; switch (enumTag) { @@ -706,7 +706,7 @@ export async function createInstantiator(options, swift) { TestModule["bjs_MyViewControllerDelegate_result_get"] = function bjs_MyViewControllerDelegate_result_get(self) { try { let ret = swift.memory.getObject(self).result; - const caseId = enumHelpers.Result.lower(ret); + const caseId = enumHelpers.M10TestModuleT6Result.lower(ret); return caseId; } catch (error) { setException(error); @@ -714,7 +714,7 @@ export async function createInstantiator(options, swift) { } TestModule["bjs_MyViewControllerDelegate_result_set"] = function bjs_MyViewControllerDelegate_result_set(self, value) { try { - const enumValue = enumHelpers.Result.lift(value); + const enumValue = enumHelpers.M10TestModuleT6Result.lift(value); swift.memory.getObject(self).result = enumValue; } catch (error) { setException(error); @@ -725,7 +725,7 @@ export async function createInstantiator(options, swift) { let ret = swift.memory.getObject(self).optionalResult; const isSome = ret != null; if (isSome) { - const caseId = enumHelpers.Result.lower(ret); + const caseId = enumHelpers.M10TestModuleT6Result.lower(ret); return caseId; } else { return -1; @@ -738,7 +738,7 @@ export async function createInstantiator(options, swift) { try { let optResult; if (valueIsSome) { - const enumValue = enumHelpers.Result.lift(valueCaseId); + const enumValue = enumHelpers.M10TestModuleT6Result.lift(valueCaseId); optResult = enumValue; } else { optResult = null; @@ -896,7 +896,7 @@ export async function createInstantiator(options, swift) { } TestModule["bjs_MyViewControllerDelegate_handleResult"] = function bjs_MyViewControllerDelegate_handleResult(self, result) { try { - const enumValue = enumHelpers.Result.lift(result); + const enumValue = enumHelpers.M10TestModuleT6Result.lift(result); swift.memory.getObject(self).handleResult(enumValue); } catch (error) { setException(error); @@ -905,7 +905,7 @@ export async function createInstantiator(options, swift) { TestModule["bjs_MyViewControllerDelegate_getResult"] = function bjs_MyViewControllerDelegate_getResult(self) { try { let ret = swift.memory.getObject(self).getResult(); - const caseId = enumHelpers.Result.lower(ret); + const caseId = enumHelpers.M10TestModuleT6Result.lower(ret); return caseId; } catch (error) { setException(error); @@ -1064,7 +1064,7 @@ export async function createInstantiator(options, swift) { } constructor(delegates) { - __bjs_codec_Array_TestModule_MyViewControllerDelegate.lower(delegates); + __bjs_codec_Array_M10TestModuleT24MyViewControllerDelegate.lower(delegates); const ret = instance.exports.bjs_DelegateManager_init(); return DelegateManager.__construct(ret); } @@ -1073,37 +1073,37 @@ export async function createInstantiator(options, swift) { } get delegates() { instance.exports.bjs_DelegateManager_delegates_get(this.pointer); - const arrayResult = __bjs_codec_Array_TestModule_MyViewControllerDelegate.lift(); + const arrayResult = __bjs_codec_Array_M10TestModuleT24MyViewControllerDelegate.lift(); return arrayResult; } set delegates(value) { - __bjs_codec_Array_TestModule_MyViewControllerDelegate.lower(value); + __bjs_codec_Array_M10TestModuleT24MyViewControllerDelegate.lower(value); instance.exports.bjs_DelegateManager_delegates_set(this.pointer); } get delegatesByName() { instance.exports.bjs_DelegateManager_delegatesByName_get(this.pointer); - const dictResult = __bjs_codec_Dict_TestModule_MyViewControllerDelegate.lift(); + const dictResult = __bjs_codec_Dict_M10TestModuleT24MyViewControllerDelegate.lift(); return dictResult; } set delegatesByName(value) { - __bjs_codec_Dict_TestModule_MyViewControllerDelegate.lower(value); + __bjs_codec_Dict_M10TestModuleT24MyViewControllerDelegate.lower(value); instance.exports.bjs_DelegateManager_delegatesByName_set(this.pointer); } } - const ResultHelpers = __bjs_createResultValuesHelpers(); - enumHelpers.Result = ResultHelpers; + const __bjs_helpers_M10TestModuleT6Result = __bjs_createEnumHelpers_M10TestModuleT6Result(); + enumHelpers.M10TestModuleT6Result = __bjs_helpers_M10TestModuleT6Result; const exports = { processDelegates: function bjs_processDelegates(delegates) { - __bjs_codec_Array_TestModule_MyViewControllerDelegate.lower(delegates); + __bjs_codec_Array_M10TestModuleT24MyViewControllerDelegate.lower(delegates); instance.exports.bjs_processDelegates(); - const arrayResult = __bjs_codec_Array_TestModule_MyViewControllerDelegate.lift(); + const arrayResult = __bjs_codec_Array_M10TestModuleT24MyViewControllerDelegate.lift(); return arrayResult; }, processDelegatesByName: function bjs_processDelegatesByName(delegates) { - __bjs_codec_Dict_TestModule_MyViewControllerDelegate.lower(delegates); + __bjs_codec_Dict_M10TestModuleT24MyViewControllerDelegate.lower(delegates); instance.exports.bjs_processDelegatesByName(); - const dictResult = __bjs_codec_Dict_TestModule_MyViewControllerDelegate.lift(); + const dictResult = __bjs_codec_Dict_M10TestModuleT24MyViewControllerDelegate.lift(); return dictResult; }, Direction: DirectionValues, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js index 88fb0c321..f46f42d10 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.Global.js @@ -42,7 +42,7 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; - const __bjs_createAPIResultValuesHelpers = () => ({ + const __bjs_createEnumHelpers_M10TestModuleT9APIResult = () => ({ lower: (value) => { const enumTag = value.tag; switch (enumTag) { @@ -353,8 +353,8 @@ export async function createInstantiator(options, swift) { return ret; } } - const APIResultHelpers = __bjs_createAPIResultValuesHelpers(); - enumHelpers.APIResult = APIResultHelpers; + const __bjs_helpers_M10TestModuleT9APIResult = __bjs_createEnumHelpers_M10TestModuleT9APIResult(); + enumHelpers.M10TestModuleT9APIResult = __bjs_helpers_M10TestModuleT9APIResult; if (typeof globalThis.Utils === 'undefined') { globalThis.Utils = {}; @@ -383,9 +383,9 @@ export async function createInstantiator(options, swift) { APIResult: { ...APIResultValues, roundtrip: function(value) { - const valueCaseId = enumHelpers.APIResult.lower(value); + const valueCaseId = enumHelpers.M10TestModuleT9APIResult.lower(value); instance.exports.bjs_APIResult_static_roundtrip(valueCaseId); - const ret = enumHelpers.APIResult.lift(i32Stack.pop()); + const ret = enumHelpers.M10TestModuleT9APIResult.lift(i32Stack.pop()); return ret; } }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js index 7c614f070..37d3415a4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StaticFunctions.js @@ -42,7 +42,7 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; - const __bjs_createAPIResultValuesHelpers = () => ({ + const __bjs_createEnumHelpers_M10TestModuleT9APIResult = () => ({ lower: (value) => { const enumTag = value.tag; switch (enumTag) { @@ -353,8 +353,8 @@ export async function createInstantiator(options, swift) { return ret; } } - const APIResultHelpers = __bjs_createAPIResultValuesHelpers(); - enumHelpers.APIResult = APIResultHelpers; + const __bjs_helpers_M10TestModuleT9APIResult = __bjs_createEnumHelpers_M10TestModuleT9APIResult(); + enumHelpers.M10TestModuleT9APIResult = __bjs_helpers_M10TestModuleT9APIResult; const exports = { Calculator: { @@ -377,9 +377,9 @@ export async function createInstantiator(options, swift) { APIResult: { ...APIResultValues, roundtrip: function(value) { - const valueCaseId = enumHelpers.APIResult.lower(value); + const valueCaseId = enumHelpers.M10TestModuleT9APIResult.lower(value); instance.exports.bjs_APIResult_static_roundtrip(valueCaseId); - const ret = enumHelpers.APIResult.lift(i32Stack.pop()); + const ret = enumHelpers.M10TestModuleT9APIResult.lift(i32Stack.pop()); return ret; } }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.js index 06873bf26..9104e2084 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/StructWithNestedTypes.js @@ -46,7 +46,7 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; - const __bjs_createShapeHelpers = () => ({ + const __bjs_createStructHelpers_M10TestModuleT5Shape = () => ({ lower: (value) => { const bytes = textEncoder.encode(value.label); const id = swift.memory.retain(bytes); @@ -58,7 +58,7 @@ export async function createInstantiator(options, swift) { return { label: string }; } }); - const __bjs_createWidgetHelpers = () => ({ + const __bjs_createStructHelpers_M10TestModuleT6Widget = () => ({ lower: (value) => { const bytes = textEncoder.encode(value.name); const id = swift.memory.retain(bytes); @@ -70,7 +70,7 @@ export async function createInstantiator(options, swift) { return { name: string }; } }); - const __bjs_createWidget_LayoutHelpers = () => ({ + const __bjs_createStructHelpers_M10TestModuleT6WidgetT6Layout = () => ({ lower: (value) => { i32Stack.push((value.padding | 0)); }, @@ -79,7 +79,7 @@ export async function createInstantiator(options, swift) { return { padding: int }; } }); - const __bjs_createWidget_BoundsHelpers = () => ({ + const __bjs_createStructHelpers_M10TestModuleT6WidgetT6Bounds = () => ({ lower: (value) => { i32Stack.push((value.width | 0)); i32Stack.push((value.height | 0)); @@ -166,31 +166,31 @@ export async function createInstantiator(options, swift) { taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_Shape"] = function(objectId) { - structHelpers.Shape.lower(swift.memory.getObject(objectId)); + structHelpers.M10TestModuleT5Shape.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_Shape"] = function() { - const value = structHelpers.Shape.lift(); + const value = structHelpers.M10TestModuleT5Shape.lift(); return swift.memory.retain(value); } bjs["swift_js_struct_lower_Widget"] = function(objectId) { - structHelpers.Widget.lower(swift.memory.getObject(objectId)); + structHelpers.M10TestModuleT6Widget.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_Widget"] = function() { - const value = structHelpers.Widget.lift(); + const value = structHelpers.M10TestModuleT6Widget.lift(); return swift.memory.retain(value); } bjs["swift_js_struct_lower_Widget_Layout"] = function(objectId) { - structHelpers.Widget_Layout.lower(swift.memory.getObject(objectId)); + structHelpers.M10TestModuleT6WidgetT6Layout.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_Widget_Layout"] = function() { - const value = structHelpers.Widget_Layout.lift(); + const value = structHelpers.M10TestModuleT6WidgetT6Layout.lift(); return swift.memory.retain(value); } bjs["swift_js_struct_lower_Widget_Bounds"] = function(objectId) { - structHelpers.Widget_Bounds.lower(swift.memory.getObject(objectId)); + structHelpers.M10TestModuleT6WidgetT6Bounds.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_Widget_Bounds"] = function() { - const value = structHelpers.Widget_Bounds.lift(); + const value = structHelpers.M10TestModuleT6WidgetT6Bounds.lift(); return swift.memory.retain(value); } bjs["bjs_core_register_type_handles"] = function() {}; @@ -306,17 +306,17 @@ export async function createInstantiator(options, swift) { /** @param {WebAssembly.Instance} instance */ createExports: (instance) => { const js = swift.memory.heap; - const ShapeHelpers = __bjs_createShapeHelpers(); - structHelpers.Shape = ShapeHelpers; + const __bjs_helpers_M10TestModuleT5Shape = __bjs_createStructHelpers_M10TestModuleT5Shape(); + structHelpers.M10TestModuleT5Shape = __bjs_helpers_M10TestModuleT5Shape; - const WidgetHelpers = __bjs_createWidgetHelpers(); - structHelpers.Widget = WidgetHelpers; + const __bjs_helpers_M10TestModuleT6Widget = __bjs_createStructHelpers_M10TestModuleT6Widget(); + structHelpers.M10TestModuleT6Widget = __bjs_helpers_M10TestModuleT6Widget; - const Widget_LayoutHelpers = __bjs_createWidget_LayoutHelpers(); - structHelpers.Widget_Layout = Widget_LayoutHelpers; + const __bjs_helpers_M10TestModuleT6WidgetT6Layout = __bjs_createStructHelpers_M10TestModuleT6WidgetT6Layout(); + structHelpers.M10TestModuleT6WidgetT6Layout = __bjs_helpers_M10TestModuleT6WidgetT6Layout; - const Widget_BoundsHelpers = __bjs_createWidget_BoundsHelpers(); - structHelpers.Widget_Bounds = Widget_BoundsHelpers; + const __bjs_helpers_M10TestModuleT6WidgetT6Bounds = __bjs_createStructHelpers_M10TestModuleT6WidgetT6Bounds(); + structHelpers.M10TestModuleT6WidgetT6Bounds = __bjs_helpers_M10TestModuleT6WidgetT6Bounds; const exports = { Shape: { @@ -324,7 +324,7 @@ export async function createInstantiator(options, swift) { const labelBytes = textEncoder.encode(label); const labelId = swift.memory.retain(labelBytes); instance.exports.bjs_Shape_init(labelId, labelBytes.length); - const structValue = structHelpers.Shape.lift(); + const structValue = structHelpers.M10TestModuleT5Shape.lift(); return structValue; }, Kind: KindValues, @@ -334,14 +334,14 @@ export async function createInstantiator(options, swift) { const nameBytes = textEncoder.encode(name); const nameId = swift.memory.retain(nameBytes); instance.exports.bjs_Widget_init(nameId, nameBytes.length); - const structValue = structHelpers.Widget.lift(); + const structValue = structHelpers.M10TestModuleT6Widget.lift(); return structValue; }, Variant: VariantValues, Bounds: { init: function(width, height) { instance.exports.bjs_Widget_Bounds_init(width, height); - const structValue = structHelpers.Widget_Bounds.lift(); + const structValue = structHelpers.M10TestModuleT6WidgetT6Bounds.lift(); return structValue; }, get dimensions() { @@ -350,7 +350,7 @@ export async function createInstantiator(options, swift) { }, zero: function() { instance.exports.bjs_Widget_Bounds_static_zero(); - const structValue = structHelpers.Widget_Bounds.lift(); + const structValue = structHelpers.M10TestModuleT6WidgetT6Bounds.lift(); return structValue; }, }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js index 24f037350..40fc1ba4f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js @@ -409,18 +409,18 @@ export async function createInstantiator(options, swift) { return swift.memory.retain(real); }; - const __bjs_codec_TestModule_Animal = { + const __bjs_codec_M10TestModuleT6Animal = { lower: (v) => { - structHelpers.Animal.lower(v); + structHelpers.M10TestModuleT6Animal.lower(v); }, lift: () => { - const struct = structHelpers.Animal.lift(); + const struct = structHelpers.M10TestModuleT6Animal.lift(); return struct; }, }; - const __bjs_codec_Optional_TestModule_Animal = __bjs_optionalCodec(__bjs_codec_TestModule_Animal); + const __bjs_codec_Optional_M10TestModuleT6Animal = __bjs_optionalCodec(__bjs_codec_M10TestModuleT6Animal); - const __bjs_createAnimalHelpers = () => ({ + const __bjs_createStructHelpers_M10TestModuleT6Animal = () => ({ lower: (value) => { const bytes = textEncoder.encode(value.type); const id = swift.memory.retain(bytes); @@ -432,7 +432,7 @@ export async function createInstantiator(options, swift) { return { type: string }; } }); - const __bjs_createAPIResultValuesHelpers = () => ({ + const __bjs_createEnumHelpers_M10TestModuleT9APIResult = () => ({ lower: (value) => { const enumTag = value.tag; switch (enumTag) { @@ -569,10 +569,10 @@ export async function createInstantiator(options, swift) { taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_Animal"] = function(objectId) { - structHelpers.Animal.lower(swift.memory.getObject(objectId)); + structHelpers.M10TestModuleT6Animal.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_Animal"] = function() { - const value = structHelpers.Animal.lift(); + const value = structHelpers.M10TestModuleT6Animal.lift(); return swift.memory.retain(value); } bjs["bjs_core_register_type_handles"] = function() {}; @@ -594,7 +594,7 @@ export async function createInstantiator(options, swift) { } bjs["promise_resolve_TestModule_6AnimalV"] = function(promise) { try { - const structValue = structHelpers.Animal.lift(); + const structValue = structHelpers.M10TestModuleT6Animal.lift(); swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(structValue); } catch (error) { setException(error); @@ -602,7 +602,7 @@ export async function createInstantiator(options, swift) { } bjs["promise_resolve_TestModule_9APIResultO"] = function(promise, value) { try { - const enumValue = enumHelpers.APIResult.lift(value); + const enumValue = enumHelpers.M10TestModuleT9APIResult.lift(value); swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(enumValue); } catch (error) { setException(error); @@ -764,18 +764,18 @@ export async function createInstantiator(options, swift) { bjs["invoke_js_callback_TestModule_10TestModule6AnimalV_6AnimalV"] = function(callbackId) { try { const callback = swift.memory.getObject(callbackId); - const structValue = structHelpers.Animal.lift(); + const structValue = structHelpers.M10TestModuleT6Animal.lift(); let ret = callback(structValue); - structHelpers.Animal.lower(ret); + structHelpers.M10TestModuleT6Animal.lower(ret); } catch (error) { setException(error); } } bjs["make_swift_closure_TestModule_10TestModule6AnimalV_6AnimalV"] = function(boxPtr, file, line) { const lower_closure_TestModule_10TestModule6AnimalV_6AnimalV = function(param0) { - structHelpers.Animal.lower(param0); + structHelpers.M10TestModuleT6Animal.lower(param0); instance.exports.invoke_swift_closure_TestModule_10TestModule6AnimalV_6AnimalV(boxPtr); - const structValue = structHelpers.Animal.lift(); + const structValue = structHelpers.M10TestModuleT6Animal.lift(); if (tmpRetException) { const error = swift.memory.getObject(tmpRetException); swift.memory.release(tmpRetException); @@ -812,9 +812,9 @@ export async function createInstantiator(options, swift) { bjs["invoke_js_callback_TestModule_10TestModule9APIResultO_9APIResultO"] = function(callbackId, param0) { try { const callback = swift.memory.getObject(callbackId); - const enumValue = enumHelpers.APIResult.lift(param0); + const enumValue = enumHelpers.M10TestModuleT9APIResult.lift(param0); let ret = callback(enumValue); - const caseId = enumHelpers.APIResult.lower(ret); + const caseId = enumHelpers.M10TestModuleT9APIResult.lower(ret); return caseId; } catch (error) { setException(error); @@ -822,9 +822,9 @@ export async function createInstantiator(options, swift) { } bjs["make_swift_closure_TestModule_10TestModule9APIResultO_9APIResultO"] = function(boxPtr, file, line) { const lower_closure_TestModule_10TestModule9APIResultO_9APIResultO = function(param0) { - const param0CaseId = enumHelpers.APIResult.lower(param0); + const param0CaseId = enumHelpers.M10TestModuleT9APIResult.lower(param0); instance.exports.invoke_swift_closure_TestModule_10TestModule9APIResultO_9APIResultO(boxPtr, param0CaseId); - const ret = enumHelpers.APIResult.lift(i32Stack.pop()); + const ret = enumHelpers.M10TestModuleT9APIResult.lift(i32Stack.pop()); if (tmpRetException) { const error = swift.memory.getObject(tmpRetException); swift.memory.release(tmpRetException); @@ -1104,22 +1104,22 @@ export async function createInstantiator(options, swift) { const callback = swift.memory.getObject(callbackId); let optResult; if (param0) { - const struct = structHelpers.Animal.lift(); + const struct = structHelpers.M10TestModuleT6Animal.lift(); optResult = struct; } else { optResult = null; } let ret = callback(optResult); - __bjs_codec_Optional_TestModule_Animal.lower(ret); + __bjs_codec_Optional_M10TestModuleT6Animal.lower(ret); } catch (error) { setException(error); } } bjs["make_swift_closure_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV"] = function(boxPtr, file, line) { const lower_closure_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV = function(param0) { - __bjs_codec_Optional_TestModule_Animal.lower(param0); + __bjs_codec_Optional_M10TestModuleT6Animal.lower(param0); instance.exports.invoke_swift_closure_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV(boxPtr); - const optValue = __bjs_codec_Optional_TestModule_Animal.lift(); + const optValue = __bjs_codec_Optional_M10TestModuleT6Animal.lift(); if (tmpRetException) { const error = swift.memory.getObject(tmpRetException); swift.memory.release(tmpRetException); @@ -1168,7 +1168,7 @@ export async function createInstantiator(options, swift) { const callback = swift.memory.getObject(callbackId); let optResult; if (param0IsSome) { - const enumValue = enumHelpers.APIResult.lift(param0CaseId); + const enumValue = enumHelpers.M10TestModuleT9APIResult.lift(param0CaseId); optResult = enumValue; } else { optResult = null; @@ -1176,7 +1176,7 @@ export async function createInstantiator(options, swift) { let ret = callback(optResult); const isSome = ret != null; if (isSome) { - const caseId = enumHelpers.APIResult.lower(ret); + const caseId = enumHelpers.M10TestModuleT9APIResult.lower(ret); return caseId; } else { return -1; @@ -1190,14 +1190,14 @@ export async function createInstantiator(options, swift) { const isSome = param0 != null; let result; if (isSome) { - const param0CaseId = enumHelpers.APIResult.lower(param0); + const param0CaseId = enumHelpers.M10TestModuleT9APIResult.lower(param0); result = param0CaseId; } else { result = 0; } instance.exports.invoke_swift_closure_TestModule_10TestModuleSq9APIResultO_Sq9APIResultO(boxPtr, +isSome, result); const tag = i32Stack.pop(); - const optResult = tag === -1 ? null : enumHelpers.APIResult.lift(tag); + const optResult = tag === -1 ? null : enumHelpers.M10TestModuleT9APIResult.lift(tag); if (tmpRetException) { const error = swift.memory.getObject(tmpRetException); swift.memory.release(tmpRetException); @@ -1465,7 +1465,7 @@ export async function createInstantiator(options, swift) { bjs["invoke_js_callback_TestModule_10TestModules6AnimalV_y"] = function(callbackId) { try { const callback = swift.memory.getObject(callbackId); - const structValue = structHelpers.Animal.lift(); + const structValue = structHelpers.M10TestModuleT6Animal.lift(); callback(structValue); } catch (error) { setException(error); @@ -1473,7 +1473,7 @@ export async function createInstantiator(options, swift) { } bjs["make_swift_closure_TestModule_10TestModules6AnimalV_y"] = function(boxPtr, file, line) { const lower_closure_TestModule_10TestModules6AnimalV_y = function(param0) { - structHelpers.Animal.lower(param0); + structHelpers.M10TestModuleT6Animal.lower(param0); instance.exports.invoke_swift_closure_TestModule_10TestModules6AnimalV_y(boxPtr); if (tmpRetException) { const error = swift.memory.getObject(tmpRetException); @@ -1509,7 +1509,7 @@ export async function createInstantiator(options, swift) { bjs["invoke_js_callback_TestModule_10TestModules9APIResultO_y"] = function(callbackId, param0) { try { const callback = swift.memory.getObject(callbackId); - const enumValue = enumHelpers.APIResult.lift(param0); + const enumValue = enumHelpers.M10TestModuleT9APIResult.lift(param0); callback(enumValue); } catch (error) { setException(error); @@ -1517,7 +1517,7 @@ export async function createInstantiator(options, swift) { } bjs["make_swift_closure_TestModule_10TestModules9APIResultO_y"] = function(boxPtr, file, line) { const lower_closure_TestModule_10TestModules9APIResultO_y = function(param0) { - const param0CaseId = enumHelpers.APIResult.lower(param0); + const param0CaseId = enumHelpers.M10TestModuleT9APIResult.lower(param0); instance.exports.invoke_swift_closure_TestModule_10TestModules9APIResultO_y(boxPtr, param0CaseId); if (tmpRetException) { const error = swift.memory.getObject(tmpRetException); @@ -1652,11 +1652,11 @@ export async function createInstantiator(options, swift) { return TestProcessor.__construct(ret); } } - const AnimalHelpers = __bjs_createAnimalHelpers(); - structHelpers.Animal = AnimalHelpers; + const __bjs_helpers_M10TestModuleT6Animal = __bjs_createStructHelpers_M10TestModuleT6Animal(); + structHelpers.M10TestModuleT6Animal = __bjs_helpers_M10TestModuleT6Animal; - const APIResultHelpers = __bjs_createAPIResultValuesHelpers(); - enumHelpers.APIResult = APIResultHelpers; + const __bjs_helpers_M10TestModuleT9APIResult = __bjs_createEnumHelpers_M10TestModuleT9APIResult(); + enumHelpers.M10TestModuleT9APIResult = __bjs_helpers_M10TestModuleT9APIResult; const exports = { roundtripAnimal: function bjs_roundtripAnimal(animalClosure) { @@ -1807,7 +1807,7 @@ export async function createInstantiator(options, swift) { const typeBytes = textEncoder.encode(type); const typeId = swift.memory.retain(typeBytes); instance.exports.bjs_Animal_init(typeId, typeBytes.length); - const structValue = structHelpers.Animal.lift(); + const structValue = structHelpers.M10TestModuleT6Animal.lift(); return structValue; }, }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js index bb0de3d03..fc3d9ddbb 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStruct.js @@ -362,7 +362,7 @@ export async function createInstantiator(options, swift) { const __bjs_codec_Optional_Int = __bjs_optionalCodec(__bjs_primitiveCodecs.Int); const __bjs_codec_Optional_Bool = __bjs_optionalCodec(__bjs_primitiveCodecs.Bool); const __bjs_codec_Optional_String = __bjs_optionalCodec(__bjs_stringCodec); - const __bjs_codec_TestModule_Precision = { + const __bjs_codec_M10TestModuleT9Precision = { lower: (v) => { f32Stack.push(Math.fround(v)); }, @@ -371,7 +371,7 @@ export async function createInstantiator(options, swift) { return rawValue; }, }; - const __bjs_codec_Optional_TestModule_Precision = __bjs_optionalCodec(__bjs_codec_TestModule_Precision); + const __bjs_codec_Optional_M10TestModuleT9Precision = __bjs_optionalCodec(__bjs_codec_M10TestModuleT9Precision); const __bjs_codec_JSObject = { lower: (v) => { const objId = swift.memory.retain(v); @@ -386,7 +386,7 @@ export async function createInstantiator(options, swift) { }; const __bjs_codec_Optional_JSObject = __bjs_optionalCodec(__bjs_codec_JSObject); - const __bjs_createDataPointHelpers = () => ({ + const __bjs_createStructHelpers_M10TestModuleT9DataPoint = () => ({ lower: (value) => { f64Stack.push(value.x); f64Stack.push(value.y); @@ -406,7 +406,7 @@ export async function createInstantiator(options, swift) { return { x: f641, y: f64, label: string, optCount: optValue1, optFlag: optValue }; } }); - const __bjs_createAddressHelpers = () => ({ + const __bjs_createStructHelpers_M10TestModuleT7Address = () => ({ lower: (value) => { const bytes = textEncoder.encode(value.street); const id = swift.memory.retain(bytes); @@ -425,25 +425,25 @@ export async function createInstantiator(options, swift) { return { street: string1, city: string, zipCode: optValue }; } }); - const __bjs_createPersonHelpers = () => ({ + const __bjs_createStructHelpers_M10TestModuleT6Person = () => ({ lower: (value) => { const bytes = textEncoder.encode(value.name); const id = swift.memory.retain(bytes); i32Stack.push(bytes.length); i32Stack.push(id); i32Stack.push((value.age | 0)); - structHelpers.Address.lower(value.address); + structHelpers.M10TestModuleT7Address.lower(value.address); __bjs_codec_Optional_String.lower(value.email); }, lift: () => { const optValue = __bjs_codec_Optional_String.lift(); - const struct = structHelpers.Address.lift(); + const struct = structHelpers.M10TestModuleT7Address.lift(); const int = i32Stack.pop(); const string = strStack.pop(); return { name: string, age: int, address: struct, email: optValue }; } }); - const __bjs_createSessionHelpers = () => ({ + const __bjs_createStructHelpers_M10TestModuleT7Session = () => ({ lower: (value) => { i32Stack.push((value.id | 0)); ptrStack.push(value.owner.pointer); @@ -455,27 +455,27 @@ export async function createInstantiator(options, swift) { return { id: int, owner: obj }; } }); - const __bjs_createMeasurementHelpers = () => ({ + const __bjs_createStructHelpers_M10TestModuleT11Measurement = () => ({ lower: (value) => { f64Stack.push(value.value); f32Stack.push(Math.fround(value.precision)); - __bjs_codec_Optional_TestModule_Precision.lower(value.optionalPrecision); + __bjs_codec_Optional_M10TestModuleT9Precision.lower(value.optionalPrecision); }, lift: () => { - const optValue = __bjs_codec_Optional_TestModule_Precision.lift(); + const optValue = __bjs_codec_Optional_M10TestModuleT9Precision.lift(); const rawValue = f32Stack.pop(); const f64 = f64Stack.pop(); return { value: f64, precision: rawValue, optionalPrecision: optValue }; } }); - const __bjs_createConfigStructHelpers = () => ({ + const __bjs_createStructHelpers_M10TestModuleT12ConfigStruct = () => ({ lower: (value) => { }, lift: () => { return { }; } }); - const __bjs_createContainerHelpers = () => ({ + const __bjs_createStructHelpers_M10TestModuleT9Container = () => ({ lower: (value) => { let id; if (value.object != null) { @@ -499,7 +499,7 @@ export async function createInstantiator(options, swift) { return { object: value, optionalObject: optValue }; } }); - const __bjs_createVector2DHelpers = () => ({ + const __bjs_createStructHelpers_M10TestModuleT8Vector2D = () => ({ lower: (value) => { f64Stack.push(value.dx); f64Stack.push(value.dy); @@ -509,18 +509,18 @@ export async function createInstantiator(options, swift) { const f641 = f64Stack.pop(); const instance1 = { dx: f641, dy: f64 }; instance1.magnitude = function() { - structHelpers.Vector2D.lower(this); + structHelpers.M10TestModuleT8Vector2D.lower(this); const ret = instance.exports.bjs_Vector2D_magnitude(); return ret; }.bind(instance1); instance1.scaled = function(factor) { - structHelpers.Vector2D.lower(this); + structHelpers.M10TestModuleT8Vector2D.lower(this); const ret1 = instance.exports.bjs_Vector2D_scaled(factor); - const structValue = structHelpers.Vector2D.lift(); + const structValue = structHelpers.M10TestModuleT8Vector2D.lift(); return structValue; }.bind(instance1); instance1.describe = function() { - structHelpers.Vector2D.lower(this); + structHelpers.M10TestModuleT8Vector2D.lower(this); const ret2 = instance.exports.bjs_Vector2D_describe(); const ret3 = tmpRetString; tmpRetString = undefined; @@ -605,59 +605,59 @@ export async function createInstantiator(options, swift) { taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_DataPoint"] = function(objectId) { - structHelpers.DataPoint.lower(swift.memory.getObject(objectId)); + structHelpers.M10TestModuleT9DataPoint.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_DataPoint"] = function() { - const value = structHelpers.DataPoint.lift(); + const value = structHelpers.M10TestModuleT9DataPoint.lift(); return swift.memory.retain(value); } bjs["swift_js_struct_lower_Address"] = function(objectId) { - structHelpers.Address.lower(swift.memory.getObject(objectId)); + structHelpers.M10TestModuleT7Address.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_Address"] = function() { - const value = structHelpers.Address.lift(); + const value = structHelpers.M10TestModuleT7Address.lift(); return swift.memory.retain(value); } bjs["swift_js_struct_lower_Person"] = function(objectId) { - structHelpers.Person.lower(swift.memory.getObject(objectId)); + structHelpers.M10TestModuleT6Person.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_Person"] = function() { - const value = structHelpers.Person.lift(); + const value = structHelpers.M10TestModuleT6Person.lift(); return swift.memory.retain(value); } bjs["swift_js_struct_lower_Session"] = function(objectId) { - structHelpers.Session.lower(swift.memory.getObject(objectId)); + structHelpers.M10TestModuleT7Session.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_Session"] = function() { - const value = structHelpers.Session.lift(); + const value = structHelpers.M10TestModuleT7Session.lift(); return swift.memory.retain(value); } bjs["swift_js_struct_lower_Measurement"] = function(objectId) { - structHelpers.Measurement.lower(swift.memory.getObject(objectId)); + structHelpers.M10TestModuleT11Measurement.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_Measurement"] = function() { - const value = structHelpers.Measurement.lift(); + const value = structHelpers.M10TestModuleT11Measurement.lift(); return swift.memory.retain(value); } bjs["swift_js_struct_lower_ConfigStruct"] = function(objectId) { - structHelpers.ConfigStruct.lower(swift.memory.getObject(objectId)); + structHelpers.M10TestModuleT12ConfigStruct.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_ConfigStruct"] = function() { - const value = structHelpers.ConfigStruct.lift(); + const value = structHelpers.M10TestModuleT12ConfigStruct.lift(); return swift.memory.retain(value); } bjs["swift_js_struct_lower_Container"] = function(objectId) { - structHelpers.Container.lower(swift.memory.getObject(objectId)); + structHelpers.M10TestModuleT9Container.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_Container"] = function() { - const value = structHelpers.Container.lift(); + const value = structHelpers.M10TestModuleT9Container.lift(); return swift.memory.retain(value); } bjs["swift_js_struct_lower_Vector2D"] = function(objectId) { - structHelpers.Vector2D.lower(swift.memory.getObject(objectId)); + structHelpers.M10TestModuleT8Vector2D.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_Vector2D"] = function() { - const value = structHelpers.Vector2D.lift(); + const value = structHelpers.M10TestModuleT8Vector2D.lift(); return swift.memory.retain(value); } bjs["bjs_core_register_type_handles"] = function() {}; @@ -862,41 +862,41 @@ export async function createInstantiator(options, swift) { instance.exports.bjs_Greeter_name_set(this.pointer, valueId, valueBytes.length); } } - const DataPointHelpers = __bjs_createDataPointHelpers(); - structHelpers.DataPoint = DataPointHelpers; + const __bjs_helpers_M10TestModuleT9DataPoint = __bjs_createStructHelpers_M10TestModuleT9DataPoint(); + structHelpers.M10TestModuleT9DataPoint = __bjs_helpers_M10TestModuleT9DataPoint; - const AddressHelpers = __bjs_createAddressHelpers(); - structHelpers.Address = AddressHelpers; + const __bjs_helpers_M10TestModuleT7Address = __bjs_createStructHelpers_M10TestModuleT7Address(); + structHelpers.M10TestModuleT7Address = __bjs_helpers_M10TestModuleT7Address; - const PersonHelpers = __bjs_createPersonHelpers(); - structHelpers.Person = PersonHelpers; + const __bjs_helpers_M10TestModuleT6Person = __bjs_createStructHelpers_M10TestModuleT6Person(); + structHelpers.M10TestModuleT6Person = __bjs_helpers_M10TestModuleT6Person; - const SessionHelpers = __bjs_createSessionHelpers(); - structHelpers.Session = SessionHelpers; + const __bjs_helpers_M10TestModuleT7Session = __bjs_createStructHelpers_M10TestModuleT7Session(); + structHelpers.M10TestModuleT7Session = __bjs_helpers_M10TestModuleT7Session; - const MeasurementHelpers = __bjs_createMeasurementHelpers(); - structHelpers.Measurement = MeasurementHelpers; + const __bjs_helpers_M10TestModuleT11Measurement = __bjs_createStructHelpers_M10TestModuleT11Measurement(); + structHelpers.M10TestModuleT11Measurement = __bjs_helpers_M10TestModuleT11Measurement; - const ConfigStructHelpers = __bjs_createConfigStructHelpers(); - structHelpers.ConfigStruct = ConfigStructHelpers; + const __bjs_helpers_M10TestModuleT12ConfigStruct = __bjs_createStructHelpers_M10TestModuleT12ConfigStruct(); + structHelpers.M10TestModuleT12ConfigStruct = __bjs_helpers_M10TestModuleT12ConfigStruct; - const ContainerHelpers = __bjs_createContainerHelpers(); - structHelpers.Container = ContainerHelpers; + const __bjs_helpers_M10TestModuleT9Container = __bjs_createStructHelpers_M10TestModuleT9Container(); + structHelpers.M10TestModuleT9Container = __bjs_helpers_M10TestModuleT9Container; - const Vector2DHelpers = __bjs_createVector2DHelpers(); - structHelpers.Vector2D = Vector2DHelpers; + const __bjs_helpers_M10TestModuleT8Vector2D = __bjs_createStructHelpers_M10TestModuleT8Vector2D(); + structHelpers.M10TestModuleT8Vector2D = __bjs_helpers_M10TestModuleT8Vector2D; const exports = { roundtrip: function bjs_roundtrip(session) { - structHelpers.Person.lower(session); + structHelpers.M10TestModuleT6Person.lower(session); instance.exports.bjs_roundtrip(); - const structValue = structHelpers.Person.lift(); + const structValue = structHelpers.M10TestModuleT6Person.lift(); return structValue; }, roundtripContainer: function bjs_roundtripContainer(container) { - structHelpers.Container.lower(container); + structHelpers.M10TestModuleT9Container.lower(container); instance.exports.bjs_roundtripContainer(); - const structValue = structHelpers.Container.lift(); + const structValue = structHelpers.M10TestModuleT9Container.lift(); return structValue; }, Precision: PrecisionValues, @@ -941,7 +941,7 @@ export async function createInstantiator(options, swift) { const isSome = optCount != null; const isSome1 = optFlag != null; instance.exports.bjs_DataPoint_init(x, y, labelId, labelBytes.length, +isSome, isSome ? optCount : 0, +isSome1, isSome1 ? optFlag ? 1 : 0 : 0); - const structValue = structHelpers.DataPoint.lift(); + const structValue = structHelpers.M10TestModuleT9DataPoint.lift(); return structValue; }, get dimensions() { @@ -950,7 +950,7 @@ export async function createInstantiator(options, swift) { }, origin: function() { instance.exports.bjs_DataPoint_static_origin(); - const structValue = structHelpers.DataPoint.lift(); + const structValue = structHelpers.M10TestModuleT9DataPoint.lift(); return structValue; }, }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js index f603bee2e..4b5252483 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js @@ -354,18 +354,18 @@ export async function createInstantiator(options, swift) { return jsValue; } - const __bjs_codec_TestModule_Point = { + const __bjs_codec_M10TestModuleT5Point = { lower: (v) => { - structHelpers.Point.lower(v); + structHelpers.M10TestModuleT5Point.lower(v); }, lift: () => { - const struct = structHelpers.Point.lift(); + const struct = structHelpers.M10TestModuleT5Point.lift(); return struct; }, }; - const __bjs_codec_Optional_TestModule_Point = __bjs_optionalCodec(__bjs_codec_TestModule_Point); + const __bjs_codec_Optional_M10TestModuleT5Point = __bjs_optionalCodec(__bjs_codec_M10TestModuleT5Point); - const __bjs_createPointHelpers = () => ({ + const __bjs_createStructHelpers_M10TestModuleT5Point = () => ({ lower: (value) => { i32Stack.push((value.x | 0)); i32Stack.push((value.y | 0)); @@ -453,10 +453,10 @@ export async function createInstantiator(options, swift) { taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_Point"] = function(objectId) { - structHelpers.Point.lower(swift.memory.getObject(objectId)); + structHelpers.M10TestModuleT5Point.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_Point"] = function() { - const value = structHelpers.Point.lift(); + const value = structHelpers.M10TestModuleT5Point.lift(); return swift.memory.retain(value); } bjs["bjs_core_register_type_handles"] = function() {}; @@ -561,9 +561,9 @@ export async function createInstantiator(options, swift) { const TestModule = importObject["TestModule"] = importObject["TestModule"] || {}; TestModule["bjs_translate"] = function bjs_translate(dx, dy) { try { - const structValue = structHelpers.Point.lift(); + const structValue = structHelpers.M10TestModuleT5Point.lift(); let ret = imports.translate(structValue, dx, dy); - structHelpers.Point.lower(ret); + structHelpers.M10TestModuleT5Point.lower(ret); } catch (error) { setException(error); } @@ -572,13 +572,13 @@ export async function createInstantiator(options, swift) { try { let optResult; if (point) { - const struct = structHelpers.Point.lift(); + const struct = structHelpers.M10TestModuleT5Point.lift(); optResult = struct; } else { optResult = null; } let ret = imports.roundTripOptional(optResult); - __bjs_codec_Optional_TestModule_Point.lower(ret); + __bjs_codec_Optional_M10TestModuleT5Point.lower(ret); } catch (error) { setException(error); } @@ -597,8 +597,8 @@ export async function createInstantiator(options, swift) { /** @param {WebAssembly.Instance} instance */ createExports: (instance) => { const js = swift.memory.heap; - const PointHelpers = __bjs_createPointHelpers(); - structHelpers.Point = PointHelpers; + const __bjs_helpers_M10TestModuleT5Point = __bjs_createStructHelpers_M10TestModuleT5Point(); + structHelpers.M10TestModuleT5Point = __bjs_helpers_M10TestModuleT5Point; const exports = { }; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js index ecc14e5ae..416e5c281 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/UnsafePointer.js @@ -31,7 +31,7 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; - const __bjs_createPointerFieldsHelpers = () => ({ + const __bjs_createStructHelpers_M10TestModuleT13PointerFields = () => ({ lower: (value) => { ptrStack.push((value.raw | 0)); ptrStack.push((value.mutRaw | 0)); @@ -124,10 +124,10 @@ export async function createInstantiator(options, swift) { taStack.push(Array.from(new Ctor(copy))); } bjs["swift_js_struct_lower_PointerFields"] = function(objectId) { - structHelpers.PointerFields.lower(swift.memory.getObject(objectId)); + structHelpers.M10TestModuleT13PointerFields.lower(swift.memory.getObject(objectId)); } bjs["swift_js_struct_lift_PointerFields"] = function() { - const value = structHelpers.PointerFields.lift(); + const value = structHelpers.M10TestModuleT13PointerFields.lift(); return swift.memory.retain(value); } bjs["bjs_core_register_type_handles"] = function() {}; @@ -243,8 +243,8 @@ export async function createInstantiator(options, swift) { /** @param {WebAssembly.Instance} instance */ createExports: (instance) => { const js = swift.memory.heap; - const PointerFieldsHelpers = __bjs_createPointerFieldsHelpers(); - structHelpers.PointerFields = PointerFieldsHelpers; + const __bjs_helpers_M10TestModuleT13PointerFields = __bjs_createStructHelpers_M10TestModuleT13PointerFields(); + structHelpers.M10TestModuleT13PointerFields = __bjs_helpers_M10TestModuleT13PointerFields; const exports = { takeUnsafeRawPointer: function bjs_takeUnsafeRawPointer(p) { @@ -283,15 +283,15 @@ export async function createInstantiator(options, swift) { return ret; }, roundTripPointerFields: function bjs_roundTripPointerFields(value) { - structHelpers.PointerFields.lower(value); + structHelpers.M10TestModuleT13PointerFields.lower(value); instance.exports.bjs_roundTripPointerFields(); - const structValue = structHelpers.PointerFields.lift(); + const structValue = structHelpers.M10TestModuleT13PointerFields.lift(); return structValue; }, PointerFields: { init: function(raw, mutRaw, opaque, ptr, mutPtr) { instance.exports.bjs_PointerFields_init(raw, mutRaw, opaque, ptr, mutPtr); - const structValue = structHelpers.PointerFields.lift(); + const structValue = structHelpers.M10TestModuleT13PointerFields.lift(); return structValue; }, }, diff --git a/Plugins/PackageToJS/Templates/instantiate.js b/Plugins/PackageToJS/Templates/instantiate.js index 3bb1c67af..7ceafe715 100644 --- a/Plugins/PackageToJS/Templates/instantiate.js +++ b/Plugins/PackageToJS/Templates/instantiate.js @@ -70,8 +70,6 @@ async function createInstantiator(options, swift) { swift_js_closure_unregister: unexpectedBjsCall, swift_js_push_typed_array: unexpectedBjsCall, swift_js_make_promise: unexpectedBjsCall, - // Imported unconditionally by JavaScriptKit's core type-handle - // registration export, which is only invoked by BridgeJS glue. bjs_core_register_type_handles: unexpectedBjsCall, }; }, diff --git a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift index 71f7fffce..067b46489 100644 --- a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift +++ b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift @@ -204,21 +204,15 @@ extension _BridgedSwiftStackType { } } -/// Types usable as the generic argument of a generic imported `@JSFunction`. -/// Each conforming type owns a ``BridgeJSTypeHandle`` whose pointer is the -/// runtime type ID that selects the matching JS codec. Do not conform types by -/// hand; marking them `@JS` emits the conformance together with the JS codec. +/// A type usable as a generic argument of an imported `@JSFunction`. public protocol BridgedSwiftGenericBridgeable: _BridgedSwiftStackType where StackLiftResult == Self { @_spi(BridgeJS) static var bridgeJSTypeHandle: BridgeJSTypeHandle { get } } extension BridgedSwiftGenericBridgeable { - /// The runtime type ID passed across the bridge for this type. @_spi(BridgeJS) public static var bridgeJSTypeID: Int32 { bridgeJSTypeHandle.typeID } - /// Creates the type's unique handle. A generic static function so - /// conformances compile under Embedded Swift. @_spi(BridgeJS) public static func bridgeJSMakeTypeHandle() -> BridgeJSTypeHandle { #if hasFeature(Embedded) return BridgeJSTypeHandle() @@ -228,17 +222,11 @@ extension BridgedSwiftGenericBridgeable { } } -/// A per-type identity token for generic bridging: each conforming type stores -/// exactly one handle in a `static let`, so the handle's pointer identifies the -/// type at runtime without relying on type names, which could collide across -/// modules. +/// A per-type identity token for generic bridging. public final class BridgeJSTypeHandle: Sendable { #if hasFeature(Embedded) public init() {} #else - /// The conforming type, for exported generics (planned follow-up) to map a - /// type ID back to. `nonisolated(unsafe)`: an immutable metatype is safe to - /// share, but the compiler cannot infer that. public nonisolated(unsafe) let type: any BridgedSwiftGenericBridgeable.Type public init(_ type: any BridgedSwiftGenericBridgeable.Type) { @@ -246,7 +234,6 @@ public final class BridgeJSTypeHandle: Sendable { } #endif - /// The handle object's own address; pointers are 32-bit on wasm32. @_spi(BridgeJS) public var typeID: Int32 { #if arch(wasm32) return Int32(bitPattern: UInt32(UInt(bitPattern: Unmanaged.passUnretained(self).toOpaque()))) @@ -1013,29 +1000,11 @@ extension JSValue: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = JSValue.bridgeJSMakeTypeHandle() } -// MARK: Core generic type-handle registration -// -// Every `BridgedSwiftGenericBridgeable` type publishes its runtime type ID to the -// JS glue, which pairs the IDs with the codec array it emitted in the same order. -// The core types below are owned by this library, so their registration lives -// here once for the whole binary instead of being copied into every module's -// generated registration function; generated per-module registration only carries -// that module's own `@JS` types. -// -// The order is the ABI contract with the JS side: it must match -// `BridgeType.genericBridgeablePrimitives` in -// `Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift`, from which -// the link step builds the core codec array. `CoreTypeRegistrationContractTests` -// checks the two lists stay in sync at build time, and the generated JS verifies -// the count at registration time. +// Keep this order in sync with BridgeType.genericBridgeablePrimitives. #if arch(wasm32) @_extern(wasm, module: "bjs", name: "bjs_core_register_type_handles") private func _bjs_core_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) -/// Publishes the core (primitive) BridgeJS type handles to the JS glue. -/// -/// Called by the generated glue once per instance, before any module's own -/// registration function. Not intended to be called from user code. @_expose(wasm, "bjs_core_register_type_handles") public func _bjs_core_register_type_handles() { // BEGIN bjs_core_type_handles From f998117e43bc78baeb28bbada433be131b1b1ea3 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Tue, 11 Aug 2026 12:03:24 +0200 Subject: [PATCH 43/50] BridgeJS: Lower imported optional stack parameters fully on the stack An imported optional whose payload is stack-only ([T]?, [String: V]?, @JS struct?) used a hybrid convention: the isSome flag crossed as a wasm i32 parameter while the payload was conditionally pushed onto the shared stacks. Optional returns and optional array elements of the same types already travel entirely on the stacks: payload first, then a 0/1 flag on the i32 stack. This lowers those parameters the same way. The Swift thunk pushes the payload (if some) followed by the flag, the wasm signature carries no argument for the parameter, and the JS handler pops the flag before conditionally lifting the payload, through the same fragment already used for optional returns and elements. The hybrid shape was the last parameter category that both passed a wasm argument and pushed stack data, which is what enabled the argument transposition fixed in #794. Every stack-touching parameter is now flagless and reverse-ordered, matching returns and elements. All other optional parameter ABIs (scalars, strings, JSObject, closures, enums, heap objects) are unchanged. --- .../Sources/BridgeJSCore/ImportTS.swift | 3 + .../Sources/BridgeJSLink/JSGlueGen.swift | 23 +--- .../BridgeJSCodegenTests/Async.swift | 12 +- .../BridgeJSCodegenTests/GenericImports.swift | 12 +- .../BridgeJSCodegenTests/ImportArray.swift | 24 ++-- .../BridgeJSCodegenTests/SwiftClosure.swift | 12 +- .../SwiftStructImports.swift | 12 +- .../__Snapshots__/BridgeJSLinkTests/Async.js | 12 +- .../BridgeJSLinkTests/GenericImports.js | 13 +- .../BridgeJSLinkTests/ImportArray.js | 29 ++--- .../BridgeJSLinkTests/SwiftClosure.js | 12 +- .../BridgeJSLinkTests/SwiftStructImports.js | 12 +- .../JavaScriptKit/BridgeJSIntrinsics.swift | 63 +-------- .../Generated/BridgeJS.swift | 120 +++++++++--------- 14 files changed, 129 insertions(+), 230 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift index cb5a88e93..cff1aa979 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/ImportTS.swift @@ -971,6 +971,9 @@ extension BridgeType { throw BridgeJSCoreError("Namespace enums cannot be used as parameters") case .nullable(let wrappedType, _): let wrappedInfo = try wrappedType.loweringParameterInfo(context: context) + if wrappedInfo.loweredParameters.isEmpty { + return LoweringParameterInfo(loweredParameters: []) + } var params = [("isSome", WasmCoreType.i32)] params.append(contentsOf: wrappedInfo.loweredParameters) return LoweringParameterInfo(loweredParameters: params, useBorrowing: wrappedInfo.useBorrowing) diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift index d35c1ed10..3f8530c55 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/JSGlueGen.swift @@ -1051,16 +1051,13 @@ struct IntrinsicJSFragment: Sendable { ) } - let innerFragment = - if wrappedType.optionalParameterUsesStackABI { - try stackLiftFragment(elementType: wrappedType) - } else { - try liftParameter(type: wrappedType, context: bridgeContext) - } + if wrappedType.optionalParameterUsesStackABI { + return try optionalElementRaiseFragment(wrappedType: wrappedType, kind: kind) + } return compositeOptionalLiftParameter( wrappedType: wrappedType, kind: kind, - innerFragment: innerFragment + innerFragment: try liftParameter(type: wrappedType, context: bridgeContext) ) } @@ -1075,22 +1072,14 @@ struct IntrinsicJSFragment: Sendable { kind: JSOptionalKind, innerFragment: IntrinsicJSFragment ) -> IntrinsicJSFragment { - let isStackConvention = wrappedType.optionalParameterUsesStackABI let absenceLiteral = kind.absenceLiteral - let outerParams: [String] - if isStackConvention { - outerParams = ["isSome"] - } else { - outerParams = ["isSome"] + innerFragment.parameters - } - return IntrinsicJSFragment( - parameters: outerParams, + parameters: ["isSome"] + innerFragment.parameters, printCode: { arguments, context in let (scope, printer) = (context.scope, context.printer) let isSome = arguments[0] - let innerArgs = isStackConvention ? [] : Array(arguments.dropFirst()) + let innerArgs = Array(arguments.dropFirst()) let bufferPrinter = CodeFragmentPrinter() let innerResults = try innerFragment.printCode( diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift index 81c8c1c56..35618554c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/Async.swift @@ -626,20 +626,20 @@ func _$Promise_resolve_Sq10AsyncThemeO(_ promise: JSObject, _ value: Optional Void +fileprivate func promise_resolve_TestModule_Sq10AsyncPointV_extern(_ promise: Int32) -> Void #else -fileprivate func promise_resolve_TestModule_Sq10AsyncPointV_extern(_ promise: Int32, _ value: Int32) -> Void { +fileprivate func promise_resolve_TestModule_Sq10AsyncPointV_extern(_ promise: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func promise_resolve_TestModule_Sq10AsyncPointV(_ promise: Int32, _ value: Int32) -> Void { - return promise_resolve_TestModule_Sq10AsyncPointV_extern(promise, value) +@inline(never) fileprivate func promise_resolve_TestModule_Sq10AsyncPointV(_ promise: Int32) -> Void { + return promise_resolve_TestModule_Sq10AsyncPointV_extern(promise) } func _$Promise_resolve_Sq10AsyncPointV(_ promise: JSObject, _ value: Optional) throws(JSException) -> Void { - let valueIsSome = value.bridgeJSLowerParameter() + let _ = value.bridgeJSLowerParameter() let promiseValue = promise.bridgeJSLowerParameter() - promise_resolve_TestModule_Sq10AsyncPointV(promiseValue, valueIsSome) + promise_resolve_TestModule_Sq10AsyncPointV(promiseValue) if let error = _swift_js_take_exception() { throw error } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericImports.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericImports.swift index 7714c498e..01ed6196e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericImports.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/GenericImports.swift @@ -354,20 +354,20 @@ func _$importGenericDictionary(_ values: [Stri #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_importGenericAfterOptionalArray") -fileprivate func bjs_importGenericAfterOptionalArray_extern(_ values: Int32, _ _generic0TypeId: Int32) -> Void +fileprivate func bjs_importGenericAfterOptionalArray_extern(_ _generic0TypeId: Int32) -> Void #else -fileprivate func bjs_importGenericAfterOptionalArray_extern(_ values: Int32, _ _generic0TypeId: Int32) -> Void { +fileprivate func bjs_importGenericAfterOptionalArray_extern(_ _generic0TypeId: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_importGenericAfterOptionalArray(_ values: Int32, _ _generic0TypeId: Int32) -> Void { - return bjs_importGenericAfterOptionalArray_extern(values, _generic0TypeId) +@inline(never) fileprivate func bjs_importGenericAfterOptionalArray(_ _generic0TypeId: Int32) -> Void { + return bjs_importGenericAfterOptionalArray_extern(_generic0TypeId) } func _$importGenericAfterOptionalArray(_ values: Optional<[Int]>, _ value: T) throws(JSException) -> T { value.bridgeJSStackPush() - let valuesIsSome = values.bridgeJSLowerParameter() - bjs_importGenericAfterOptionalArray(valuesIsSome, T.bridgeJSTypeID) + let _ = values.bridgeJSLowerParameter() + bjs_importGenericAfterOptionalArray(T.bridgeJSTypeID) if let error = _swift_js_take_exception() { throw error } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.swift index 9c4b49e3c..12abbd1e6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ImportArray.swift @@ -41,20 +41,20 @@ func _$logStrings(_ items: [String]) throws(JSException) -> Void { #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_optionalArrayThenArray") -fileprivate func bjs_optionalArrayThenArray_extern(_ a: Int32) -> Int32 +fileprivate func bjs_optionalArrayThenArray_extern() -> Int32 #else -fileprivate func bjs_optionalArrayThenArray_extern(_ a: Int32) -> Int32 { +fileprivate func bjs_optionalArrayThenArray_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_optionalArrayThenArray(_ a: Int32) -> Int32 { - return bjs_optionalArrayThenArray_extern(a) +@inline(never) fileprivate func bjs_optionalArrayThenArray() -> Int32 { + return bjs_optionalArrayThenArray_extern() } func _$optionalArrayThenArray(_ a: Optional<[Int]>, _ b: [Int]) throws(JSException) -> Int { let _ = b.bridgeJSLowerParameter() - let aIsSome = a.bridgeJSLowerParameter() - let ret = bjs_optionalArrayThenArray(aIsSome) + let _ = a.bridgeJSLowerParameter() + let ret = bjs_optionalArrayThenArray() if let error = _swift_js_take_exception() { throw error } @@ -63,21 +63,21 @@ func _$optionalArrayThenArray(_ a: Optional<[Int]>, _ b: [Int]) throws(JSExcepti #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_borrowedStringAroundStackParams") -fileprivate func bjs_borrowedStringAroundStackParams_extern(_ sBytes: Int32, _ sLength: Int32, _ a: Int32) -> Int32 +fileprivate func bjs_borrowedStringAroundStackParams_extern(_ sBytes: Int32, _ sLength: Int32) -> Int32 #else -fileprivate func bjs_borrowedStringAroundStackParams_extern(_ sBytes: Int32, _ sLength: Int32, _ a: Int32) -> Int32 { +fileprivate func bjs_borrowedStringAroundStackParams_extern(_ sBytes: Int32, _ sLength: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_borrowedStringAroundStackParams(_ sBytes: Int32, _ sLength: Int32, _ a: Int32) -> Int32 { - return bjs_borrowedStringAroundStackParams_extern(sBytes, sLength, a) +@inline(never) fileprivate func bjs_borrowedStringAroundStackParams(_ sBytes: Int32, _ sLength: Int32) -> Int32 { + return bjs_borrowedStringAroundStackParams_extern(sBytes, sLength) } func _$borrowedStringAroundStackParams(_ s: String, _ a: Optional<[Int]>, _ b: [Int]) throws(JSException) -> Int { let ret0 = s.bridgeJSWithLoweredParameter { (sBytes, sLength) in let _ = b.bridgeJSLowerParameter() - let aIsSome = a.bridgeJSLowerParameter() - let ret = bjs_borrowedStringAroundStackParams(sBytes, sLength, aIsSome) + let _ = a.bridgeJSLowerParameter() + let ret = bjs_borrowedStringAroundStackParams(sBytes, sLength) return ret } let ret = ret0 diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift index f349f0c40..c2844aa9c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftClosure.swift @@ -992,14 +992,14 @@ public func _invoke_swift_closure_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO(_ b #if arch(wasm32) @_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV") -fileprivate func invoke_js_callback_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV_extern(_ callback: Int32, _ param0: Int32) -> Void +fileprivate func invoke_js_callback_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV_extern(_ callback: Int32) -> Void #else -fileprivate func invoke_js_callback_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV_extern(_ callback: Int32, _ param0: Int32) -> Void { +fileprivate func invoke_js_callback_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV_extern(_ callback: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV(_ callback: Int32, _ param0: Int32) -> Void { - return invoke_js_callback_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV_extern(callback, param0) +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV(_ callback: Int32) -> Void { + return invoke_js_callback_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV_extern(callback) } #if arch(wasm32) @@ -1019,9 +1019,9 @@ private enum _BJS_Closure_10TestModuleSq6AnimalV_Sq6AnimalV { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) - let param0IsSome = param0.bridgeJSLowerParameter() + let _ = param0.bridgeJSLowerParameter() let callbackValue = callback.bridgeJSLowerParameter() - invoke_js_callback_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV(callbackValue, param0IsSome) + invoke_js_callback_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV(callbackValue) return Optional.bridgeJSLiftReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.swift index 4e9899470..0d77ebe47 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/SwiftStructImports.swift @@ -75,19 +75,19 @@ func _$translate(_ point: Point, _ dx: Int, _ dy: Int) throws(JSException) -> Po #if arch(wasm32) @_extern(wasm, module: "TestModule", name: "bjs_roundTripOptional") -fileprivate func bjs_roundTripOptional_extern(_ point: Int32) -> Void +fileprivate func bjs_roundTripOptional_extern() -> Void #else -fileprivate func bjs_roundTripOptional_extern(_ point: Int32) -> Void { +fileprivate func bjs_roundTripOptional_extern() -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_roundTripOptional(_ point: Int32) -> Void { - return bjs_roundTripOptional_extern(point) +@inline(never) fileprivate func bjs_roundTripOptional() -> Void { + return bjs_roundTripOptional_extern() } func _$roundTripOptional(_ point: Optional) throws(JSException) -> Optional { - let pointIsSome = point.bridgeJSLowerParameter() - bjs_roundTripOptional(pointIsSome) + let _ = point.bridgeJSLowerParameter() + bjs_roundTripOptional() if let error = _swift_js_take_exception() { throw error } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js index 6f2a21501..c025cf4f0 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/Async.js @@ -584,16 +584,10 @@ export async function createInstantiator(options, swift) { setException(error); } } - bjs["promise_resolve_TestModule_Sq10AsyncPointV"] = function(promise, value) { + bjs["promise_resolve_TestModule_Sq10AsyncPointV"] = function(promise) { try { - let optResult; - if (value) { - const struct = structHelpers.M10TestModuleT10AsyncPoint.lift(); - optResult = struct; - } else { - optResult = null; - } - swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(optResult); + const optValue = __bjs_codec_Optional_M10TestModuleT10AsyncPoint.lift(); + swift.memory.getObject(promise)[__bjs_promiseSettlers].resolve(optValue); } catch (error) { setException(error); } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js index d120c255e..d8b1fdf15 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/GenericImports.js @@ -389,6 +389,7 @@ export async function createInstantiator(options, swift) { } const __bjs_codec_Array_Int = __bjs_arrayCodec(__bjs_primitiveCodecs.Int); + const __bjs_codec_Optional_Array_Int = __bjs_optionalCodec(__bjs_codec_Array_Int); const __bjs_codec_M10TestModuleT12GenericPoint = { lower: (v) => { structHelpers.M10TestModuleT12GenericPoint.lower(v); @@ -771,18 +772,12 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_importGenericAfterOptionalArray"] = function bjs_importGenericAfterOptionalArray(values, tTypeId) { + TestModule["bjs_importGenericAfterOptionalArray"] = function bjs_importGenericAfterOptionalArray(tTypeId) { try { const codecT = __bjs_codecForTypeId(tTypeId); - let optResult; - if (values) { - const arrayResult = __bjs_codec_Array_Int.lift(); - optResult = arrayResult; - } else { - optResult = null; - } + const optValue = __bjs_codec_Optional_Array_Int.lift(); const value = codecT.lift(); - let ret = imports.importGenericAfterOptionalArray(optResult, value); + let ret = imports.importGenericAfterOptionalArray(optValue, value); codecT.lower(ret); } catch (error) { setException(error); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js index 42c02479f..c92ea6ad3 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ImportArray.js @@ -356,6 +356,7 @@ export async function createInstantiator(options, swift) { const __bjs_codec_Array_Int = __bjs_arrayCodec(__bjs_primitiveCodecs.Int); const __bjs_codec_Array_String = __bjs_arrayCodec(__bjs_stringCodec); + const __bjs_codec_Optional_Array_Int = __bjs_optionalCodec(__bjs_codec_Array_Int); return { @@ -549,35 +550,23 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_optionalArrayThenArray"] = function bjs_optionalArrayThenArray(a) { + TestModule["bjs_optionalArrayThenArray"] = function bjs_optionalArrayThenArray() { try { - let optResult; - if (a) { - const arrayResult = __bjs_codec_Array_Int.lift(); - optResult = arrayResult; - } else { - optResult = null; - } - const arrayResult1 = __bjs_codec_Array_Int.lift(); - let ret = imports.optionalArrayThenArray(optResult, arrayResult1); + const optValue = __bjs_codec_Optional_Array_Int.lift(); + const arrayResult = __bjs_codec_Array_Int.lift(); + let ret = imports.optionalArrayThenArray(optValue, arrayResult); return ret; } catch (error) { setException(error); return 0 } } - TestModule["bjs_borrowedStringAroundStackParams"] = function bjs_borrowedStringAroundStackParams(sBytes, sCount, a) { + TestModule["bjs_borrowedStringAroundStackParams"] = function bjs_borrowedStringAroundStackParams(sBytes, sCount) { try { const string = decodeString(sBytes, sCount); - let optResult; - if (a) { - const arrayResult = __bjs_codec_Array_Int.lift(); - optResult = arrayResult; - } else { - optResult = null; - } - const arrayResult1 = __bjs_codec_Array_Int.lift(); - let ret = imports.borrowedStringAroundStackParams(string, optResult, arrayResult1); + const optValue = __bjs_codec_Optional_Array_Int.lift(); + const arrayResult = __bjs_codec_Array_Int.lift(); + let ret = imports.borrowedStringAroundStackParams(string, optValue, arrayResult); return ret; } catch (error) { setException(error); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js index 40fc1ba4f..279a9d3c6 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftClosure.js @@ -1099,17 +1099,11 @@ export async function createInstantiator(options, swift) { }; return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModuleSq5ThemeO_Sq5ThemeO); } - bjs["invoke_js_callback_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV"] = function(callbackId, param0) { + bjs["invoke_js_callback_TestModule_10TestModuleSq6AnimalV_Sq6AnimalV"] = function(callbackId) { try { const callback = swift.memory.getObject(callbackId); - let optResult; - if (param0) { - const struct = structHelpers.M10TestModuleT6Animal.lift(); - optResult = struct; - } else { - optResult = null; - } - let ret = callback(optResult); + const optValue = __bjs_codec_Optional_M10TestModuleT6Animal.lift(); + let ret = callback(optValue); __bjs_codec_Optional_M10TestModuleT6Animal.lower(ret); } catch (error) { setException(error); diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js index 4b5252483..134d7c28e 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/SwiftStructImports.js @@ -568,16 +568,10 @@ export async function createInstantiator(options, swift) { setException(error); } } - TestModule["bjs_roundTripOptional"] = function bjs_roundTripOptional(point) { + TestModule["bjs_roundTripOptional"] = function bjs_roundTripOptional() { try { - let optResult; - if (point) { - const struct = structHelpers.M10TestModuleT5Point.lift(); - optResult = struct; - } else { - optResult = null; - } - let ret = imports.roundTripOptional(optResult); + const optValue = __bjs_codec_Optional_M10TestModuleT5Point.lift(); + let ret = imports.roundTripOptional(optValue); __bjs_codec_Optional_M10TestModuleT5Point.lower(ret); } catch (error) { setException(error); diff --git a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift index 067b46489..ab0a9f4f0 100644 --- a/Sources/JavaScriptKit/BridgeJSIntrinsics.swift +++ b/Sources/JavaScriptKit/BridgeJSIntrinsics.swift @@ -2063,14 +2063,8 @@ extension _BridgedAsOptional where Wrapped: _BridgedSwiftStackType, Wrapped.Stac extension _BridgedAsOptional where Wrapped: _BridgedSwiftStackType, Wrapped.StackLiftResult == Wrapped, Wrapped: _BridgedSwiftTypeLoweredIntoVoidType { - @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { - switch asOptional { - case .none: - return 0 - case .some(let array): - array.bridgeJSLowerReturn() - return 1 - } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() { + Wrapped.bridgeJSStackPushAsOptional(asOptional) } @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { @@ -2487,24 +2481,6 @@ extension _BridgedAsOptional where Wrapped: _BridgedSwiftAssociatedValueEnum { } } -extension _BridgedAsOptional where Wrapped: _BridgedSwiftStruct { - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32) -> Self { - if isSome == 0 { - return Self(optional: nil) - } else { - return Self(optional: Wrapped.bridgeJSStackPop()) - } - } - - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void { - Wrapped.bridgeJSStackPushAsOptional(asOptional) - } - - @_spi(BridgeJS) public static func bridgeJSLiftParameter() -> Self { - Self.bridgeJSStackPop() - } -} - // MARK: - Array Support extension Array: _BridgedSwiftTypeLoweredIntoVoidType @@ -2580,41 +2556,6 @@ where Key == String, Value: _BridgedSwiftStackType, Value.StackLiftResult == Val } } -extension _BridgedAsOptional { - @_spi(BridgeJS) public consuming func bridgeJSLowerParameter() -> Int32 - where Wrapped == Dictionary, Value: _BridgedSwiftStackType, Value.StackLiftResult == Value { - switch asOptional { - case .none: - return 0 - case .some(let dict): - dict.bridgeJSStackPush() - return 1 - } - } - - @_spi(BridgeJS) public static func bridgeJSLiftParameter(_ isSome: Int32) -> Self - where Wrapped == Dictionary, Value: _BridgedSwiftStackType, Value.StackLiftResult == Value { - if isSome == 0 { - return Self(optional: nil) - } - return Self(optional: Dictionary.bridgeJSStackPop()) - } - - @_spi(BridgeJS) public static func bridgeJSLiftReturn() -> Self - where Wrapped == Dictionary, Value: _BridgedSwiftStackType, Value.StackLiftResult == Value { - let isSome = _swift_js_pop_i32() - if isSome == 0 { - return Self(optional: nil) - } - return Self(optional: Dictionary.bridgeJSStackPop()) - } - - @_spi(BridgeJS) public consuming func bridgeJSLowerReturn() -> Void - where Wrapped == Dictionary, Value: _BridgedSwiftStackType, Value.StackLiftResult == Value { - Wrapped.bridgeJSStackPushAsOptional(asOptional) - } -} - // MARK: Async Promise Awaiting /// Protocol for type-erasing `JSTypedClosure` in `_bjs_awaitPromise`. diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index c70de88dc..e453e3534 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -14625,20 +14625,20 @@ func _$Promise_resolve_Sa11PublicPointV(_ promise: JSObject, _ value: [PublicPoi #if arch(wasm32) @_extern(wasm, module: "bjs", name: "promise_resolve_BridgeJSRuntimeTests_Sq11PublicPointV") -fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq11PublicPointV_extern(_ promise: Int32, _ value: Int32) -> Void +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq11PublicPointV_extern(_ promise: Int32) -> Void #else -fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq11PublicPointV_extern(_ promise: Int32, _ value: Int32) -> Void { +fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq11PublicPointV_extern(_ promise: Int32) -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq11PublicPointV(_ promise: Int32, _ value: Int32) -> Void { - return promise_resolve_BridgeJSRuntimeTests_Sq11PublicPointV_extern(promise, value) +@inline(never) fileprivate func promise_resolve_BridgeJSRuntimeTests_Sq11PublicPointV(_ promise: Int32) -> Void { + return promise_resolve_BridgeJSRuntimeTests_Sq11PublicPointV_extern(promise) } func _$Promise_resolve_Sq11PublicPointV(_ promise: JSObject, _ value: Optional) throws(JSException) -> Void { - let valueIsSome = value.bridgeJSLowerParameter() + let _ = value.bridgeJSLowerParameter() let promiseValue = promise.bridgeJSLowerParameter() - promise_resolve_BridgeJSRuntimeTests_Sq11PublicPointV(promiseValue, valueIsSome) + promise_resolve_BridgeJSRuntimeTests_Sq11PublicPointV(promiseValue) if let error = _swift_js_take_exception() { throw error } } @@ -17234,20 +17234,20 @@ func _$jsRoundTripOptionalImportedPayloadSignal(_ value: Optional Int32 +fileprivate func bjs_jsJoinOptionalArrayThenArray_extern() -> Int32 #else -fileprivate func bjs_jsJoinOptionalArrayThenArray_extern(_ a: Int32) -> Int32 { +fileprivate func bjs_jsJoinOptionalArrayThenArray_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_jsJoinOptionalArrayThenArray(_ a: Int32) -> Int32 { - return bjs_jsJoinOptionalArrayThenArray_extern(a) +@inline(never) fileprivate func bjs_jsJoinOptionalArrayThenArray() -> Int32 { + return bjs_jsJoinOptionalArrayThenArray_extern() } func _$jsJoinOptionalArrayThenArray(_ a: Optional<[Int]>, _ b: [Int]) throws(JSException) -> String { let _ = b.bridgeJSLowerParameter() - let aIsSome = a.bridgeJSLowerParameter() - let ret = bjs_jsJoinOptionalArrayThenArray(aIsSome) + let _ = a.bridgeJSLowerParameter() + let ret = bjs_jsJoinOptionalArrayThenArray() if let error = _swift_js_take_exception() { throw error } @@ -17256,20 +17256,20 @@ func _$jsJoinOptionalArrayThenArray(_ a: Optional<[Int]>, _ b: [Int]) throws(JSE #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsJoinOptionalStructThenArray") -fileprivate func bjs_jsJoinOptionalStructThenArray_extern(_ a: Int32) -> Int32 +fileprivate func bjs_jsJoinOptionalStructThenArray_extern() -> Int32 #else -fileprivate func bjs_jsJoinOptionalStructThenArray_extern(_ a: Int32) -> Int32 { +fileprivate func bjs_jsJoinOptionalStructThenArray_extern() -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_jsJoinOptionalStructThenArray(_ a: Int32) -> Int32 { - return bjs_jsJoinOptionalStructThenArray_extern(a) +@inline(never) fileprivate func bjs_jsJoinOptionalStructThenArray() -> Int32 { + return bjs_jsJoinOptionalStructThenArray_extern() } func _$jsJoinOptionalStructThenArray(_ a: Optional, _ b: [Int]) throws(JSException) -> String { let _ = b.bridgeJSLowerParameter() - let aIsSome = a.bridgeJSLowerParameter() - let ret = bjs_jsJoinOptionalStructThenArray(aIsSome) + let _ = a.bridgeJSLowerParameter() + let ret = bjs_jsJoinOptionalStructThenArray() if let error = _swift_js_take_exception() { throw error } @@ -17300,21 +17300,21 @@ func _$jsJoinEnumThenArray(_ a: ImportedPayloadSignal, _ b: [Int]) throws(JSExce #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsJoinStringThenStackParams") -fileprivate func bjs_jsJoinStringThenStackParams_extern(_ sBytes: Int32, _ sLength: Int32, _ a: Int32) -> Int32 +fileprivate func bjs_jsJoinStringThenStackParams_extern(_ sBytes: Int32, _ sLength: Int32) -> Int32 #else -fileprivate func bjs_jsJoinStringThenStackParams_extern(_ sBytes: Int32, _ sLength: Int32, _ a: Int32) -> Int32 { +fileprivate func bjs_jsJoinStringThenStackParams_extern(_ sBytes: Int32, _ sLength: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_jsJoinStringThenStackParams(_ sBytes: Int32, _ sLength: Int32, _ a: Int32) -> Int32 { - return bjs_jsJoinStringThenStackParams_extern(sBytes, sLength, a) +@inline(never) fileprivate func bjs_jsJoinStringThenStackParams(_ sBytes: Int32, _ sLength: Int32) -> Int32 { + return bjs_jsJoinStringThenStackParams_extern(sBytes, sLength) } func _$jsJoinStringThenStackParams(_ s: String, _ a: Optional<[Int]>, _ b: [Int]) throws(JSException) -> String { let ret0 = s.bridgeJSWithLoweredParameter { (sBytes, sLength) in let _ = b.bridgeJSLowerParameter() - let aIsSome = a.bridgeJSLowerParameter() - let ret = bjs_jsJoinStringThenStackParams(sBytes, sLength, aIsSome) + let _ = a.bridgeJSLowerParameter() + let ret = bjs_jsJoinStringThenStackParams(sBytes, sLength) return ret } let ret = ret0 @@ -17517,20 +17517,20 @@ func _$jsGenericDictRoundTrip(_ values: [Strin #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsGenericAfterOptionalArray") -fileprivate func bjs_jsGenericAfterOptionalArray_extern(_ values: Int32, _ _generic0TypeId: Int32) -> Int32 +fileprivate func bjs_jsGenericAfterOptionalArray_extern(_ _generic0TypeId: Int32) -> Int32 #else -fileprivate func bjs_jsGenericAfterOptionalArray_extern(_ values: Int32, _ _generic0TypeId: Int32) -> Int32 { +fileprivate func bjs_jsGenericAfterOptionalArray_extern(_ _generic0TypeId: Int32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_jsGenericAfterOptionalArray(_ values: Int32, _ _generic0TypeId: Int32) -> Int32 { - return bjs_jsGenericAfterOptionalArray_extern(values, _generic0TypeId) +@inline(never) fileprivate func bjs_jsGenericAfterOptionalArray(_ _generic0TypeId: Int32) -> Int32 { + return bjs_jsGenericAfterOptionalArray_extern(_generic0TypeId) } func _$jsGenericAfterOptionalArray(_ values: Optional<[Int]>, _ value: T) throws(JSException) -> String { value.bridgeJSStackPush() - let valuesIsSome = values.bridgeJSLowerParameter() - let ret = bjs_jsGenericAfterOptionalArray(valuesIsSome, T.bridgeJSTypeID) + let _ = values.bridgeJSLowerParameter() + let ret = bjs_jsGenericAfterOptionalArray(T.bridgeJSTypeID) if let error = _swift_js_take_exception() { throw error } @@ -17689,19 +17689,19 @@ func _$jsTranslatePoint(_ point: Point, _ dx: Int, _ dy: Int) throws(JSException #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_jsRoundTripOptionalPoint") -fileprivate func bjs_jsRoundTripOptionalPoint_extern(_ point: Int32) -> Void +fileprivate func bjs_jsRoundTripOptionalPoint_extern() -> Void #else -fileprivate func bjs_jsRoundTripOptionalPoint_extern(_ point: Int32) -> Void { +fileprivate func bjs_jsRoundTripOptionalPoint_extern() -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_jsRoundTripOptionalPoint(_ point: Int32) -> Void { - return bjs_jsRoundTripOptionalPoint_extern(point) +@inline(never) fileprivate func bjs_jsRoundTripOptionalPoint() -> Void { + return bjs_jsRoundTripOptionalPoint_extern() } func _$jsRoundTripOptionalPoint(_ point: Optional) throws(JSException) -> Optional { - let pointIsSome = point.bridgeJSLowerParameter() - bjs_jsRoundTripOptionalPoint(pointIsSome) + let _ = point.bridgeJSLowerParameter() + bjs_jsRoundTripOptionalPoint() if let error = _swift_js_take_exception() { throw error } @@ -18758,50 +18758,50 @@ fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringUndefined_s #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_OptionalSupportImports_jsRoundTripOptionalJSValueArrayNull_static") -fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalJSValueArrayNull_static_extern(_ v: Int32) -> Void +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalJSValueArrayNull_static_extern() -> Void #else -fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalJSValueArrayNull_static_extern(_ v: Int32) -> Void { +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalJSValueArrayNull_static_extern() -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalJSValueArrayNull_static(_ v: Int32) -> Void { - return bjs_OptionalSupportImports_jsRoundTripOptionalJSValueArrayNull_static_extern(v) +@inline(never) fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalJSValueArrayNull_static() -> Void { + return bjs_OptionalSupportImports_jsRoundTripOptionalJSValueArrayNull_static_extern() } #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_OptionalSupportImports_jsRoundTripOptionalJSValueArrayUndefined_static") -fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalJSValueArrayUndefined_static_extern(_ v: Int32) -> Void +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalJSValueArrayUndefined_static_extern() -> Void #else -fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalJSValueArrayUndefined_static_extern(_ v: Int32) -> Void { +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalJSValueArrayUndefined_static_extern() -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalJSValueArrayUndefined_static(_ v: Int32) -> Void { - return bjs_OptionalSupportImports_jsRoundTripOptionalJSValueArrayUndefined_static_extern(v) +@inline(never) fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalJSValueArrayUndefined_static() -> Void { + return bjs_OptionalSupportImports_jsRoundTripOptionalJSValueArrayUndefined_static_extern() } #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryNull_static") -fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryNull_static_extern(_ v: Int32) -> Void +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryNull_static_extern() -> Void #else -fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryNull_static_extern(_ v: Int32) -> Void { +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryNull_static_extern() -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryNull_static(_ v: Int32) -> Void { - return bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryNull_static_extern(v) +@inline(never) fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryNull_static() -> Void { + return bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryNull_static_extern() } #if arch(wasm32) @_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryUndefined_static") -fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryUndefined_static_extern(_ v: Int32) -> Void +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryUndefined_static_extern() -> Void #else -fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryUndefined_static_extern(_ v: Int32) -> Void { +fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryUndefined_static_extern() -> Void { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryUndefined_static(_ v: Int32) -> Void { - return bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryUndefined_static_extern(v) +@inline(never) fileprivate func bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryUndefined_static() -> Void { + return bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryUndefined_static_extern() } #if arch(wasm32) @@ -18867,8 +18867,8 @@ func _$OptionalSupportImports_jsRoundTripOptionalStringUndefined(_ name: JSUndef } func _$OptionalSupportImports_jsRoundTripOptionalJSValueArrayNull(_ v: Optional<[JSValue]>) throws(JSException) -> Optional<[JSValue]> { - let vIsSome = v.bridgeJSLowerParameter() - bjs_OptionalSupportImports_jsRoundTripOptionalJSValueArrayNull_static(vIsSome) + let _ = v.bridgeJSLowerParameter() + bjs_OptionalSupportImports_jsRoundTripOptionalJSValueArrayNull_static() if let error = _swift_js_take_exception() { throw error } @@ -18876,8 +18876,8 @@ func _$OptionalSupportImports_jsRoundTripOptionalJSValueArrayNull(_ v: Optional< } func _$OptionalSupportImports_jsRoundTripOptionalJSValueArrayUndefined(_ v: JSUndefinedOr<[JSValue]>) throws(JSException) -> JSUndefinedOr<[JSValue]> { - let vIsSome = v.bridgeJSLowerParameter() - bjs_OptionalSupportImports_jsRoundTripOptionalJSValueArrayUndefined_static(vIsSome) + let _ = v.bridgeJSLowerParameter() + bjs_OptionalSupportImports_jsRoundTripOptionalJSValueArrayUndefined_static() if let error = _swift_js_take_exception() { throw error } @@ -18885,8 +18885,8 @@ func _$OptionalSupportImports_jsRoundTripOptionalJSValueArrayUndefined(_ v: JSUn } func _$OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryNull(_ v: Optional<[String: String]>) throws(JSException) -> Optional<[String: String]> { - let vIsSome = v.bridgeJSLowerParameter() - bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryNull_static(vIsSome) + let _ = v.bridgeJSLowerParameter() + bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryNull_static() if let error = _swift_js_take_exception() { throw error } @@ -18894,8 +18894,8 @@ func _$OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryNull(_ } func _$OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryUndefined(_ v: JSUndefinedOr<[String: String]>) throws(JSException) -> JSUndefinedOr<[String: String]> { - let vIsSome = v.bridgeJSLowerParameter() - bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryUndefined_static(vIsSome) + let _ = v.bridgeJSLowerParameter() + bjs_OptionalSupportImports_jsRoundTripOptionalStringToStringDictionaryUndefined_static() if let error = _swift_js_take_exception() { throw error } From 97504862f4f0afd66a260c1af43a8df7bf44204d Mon Sep 17 00:00:00 2001 From: William Taylor Date: Fri, 14 Aug 2026 16:27:32 +1000 Subject: [PATCH 44/50] BridgeJS: Emit diagnostics from extensions properly (#804) --- .../BridgeJSCore/SwiftToSkeleton.swift | 38 ++++++++++++++++--- .../BridgeJSToolTests/DiagnosticsTests.swift | 38 +++++++++++++++++++ 2 files changed, 71 insertions(+), 5 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index f37bfb822..937ec5c41 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -222,15 +222,14 @@ public final class SwiftToSkeleton { validatedJavaScriptModulePaths.insert(path) } - let exportErrors = exportCollector.errors.filter { $0.severity == .error } let importErrorsFatal = importCollector.errors.filter { $0.severity == .error && !$0.message.contains("Unsupported type '") } - let fileWarnings = (exportCollector.errors + importCollector.errors).filter { $0.severity == .warning } + let fileWarnings = importCollector.errors.filter { $0.severity == .warning } warnings.append(contentsOf: fileWarnings.map { (file: inputFilePath, diagnostic: $0) }) - if !exportErrors.isEmpty || !importErrorsFatal.isEmpty { + if !importErrorsFatal.isEmpty { perSourceErrors.append( - (inputFilePath: inputFilePath, errors: exportErrors + importErrorsFatal) + (inputFilePath: inputFilePath, errors: importErrorsFatal) ) } @@ -249,6 +248,18 @@ public final class SwiftToSkeleton { source.resolveDeferredExtensions(against: exportCollectors) } + // We have to collect diagnostics after all deferred extensions are resolved, since they could generate some. + for ((_, inputFilePath), exportCollector) in zip(sourceFiles, exportCollectors) { + let exportErrors = exportCollector.errors.filter { $0.severity == .error } + let fileWarnings = exportCollector.errors.filter { $0.severity == .warning } + warnings.append(contentsOf: fileWarnings.map { (file: inputFilePath, diagnostic: $0) }) + if !exportErrors.isEmpty { + perSourceErrors.append( + (inputFilePath: inputFilePath, errors: exportErrors) + ) + } + } + for collector in exportCollectors { collector.finalize(&exported) } @@ -858,6 +869,17 @@ extension AttributeListSyntax { } } +private final class JSAttributeFinder: SyntaxVisitor { + private(set) var found = false + + override func visit(_ node: AttributeSyntax) -> SyntaxVisitorContinueKind { + if node.attributeNameText == "JS" { + found = true + } + return .skipChildren + } +} + private final class ExportSwiftAPICollector: SyntaxAnyVisitor { var exportedFunctions: [ExportedFunction] = [] /// The names of the exported classes, in the order they were written in the source file @@ -1910,7 +1932,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { break } } - if !resolved { + if !resolved, containsJSAnnotatedDeclaration(ext.memberBlock.members) { diagnose( node: ext.extendedType, message: "Unsupported type '\(ext.extendedType.trimmedDescription)'.", @@ -1920,6 +1942,12 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { } } + private func containsJSAnnotatedDeclaration(_ members: MemberBlockItemListSyntax) -> Bool { + let finder = JSAttributeFinder(viewMode: .sourceAccurate) + finder.walk(members) + return finder.found + } + /// Walks extension members under the matching type’s state, returning whether the type was found. /// /// Note: The lookup scans dictionaries keyed by `makeKey(name:namespace:)`, matching only by diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift index 5abdf8fb2..4f45a9880 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/DiagnosticsTests.swift @@ -26,6 +26,44 @@ import Testing } } + @Test + func extensionOfUnknownTypeWithJSMemberProducesDiagnostic() throws { + let source = """ + extension Unknown { + @JS func bridged() -> Int { 42 } + } + """ + let diagnostics = try #require(moduleDiagnostics(source: source)) + #expect(diagnostics.description.contains("Unsupported type 'Unknown'")) + } + + @Test + func extensionWithoutJSMembersIsIgnored() throws { + let source = """ + extension String { + func helper() -> Int { 42 } + } + """ + #expect(moduleDiagnostics(source: source) == nil) + } + + @Test + func invalidJSMemberInsideExtensionProducesDiagnostic() throws { + let source = """ + @JS class Host { + @JS init() {} + } + + extension Host { + @JS struct Bad { + var field = 1 + } + } + """ + let diagnostics = try #require(moduleDiagnostics(source: source)) + #expect(diagnostics.description.contains("Struct field must have explicit type annotation")) + } + @Test func missingJavaScriptModuleProducesDiagnostic() throws { let source = """ From 2e36a76259d30a6fe4ae4f6be698741d333a20d1 Mon Sep 17 00:00:00 2001 From: William Taylor Date: Fri, 14 Aug 2026 15:13:22 +1000 Subject: [PATCH 45/50] BridgeJS: Allow extensions to contain types --- .../BridgeJSCore/SwiftToSkeleton.swift | 97 ++-- .../BridgeJSCore/TypeDeclResolver.swift | 54 ++- .../BridgeJSCodegenTests.swift | 22 + .../MacroSwift/ExtensionNestedTypes.swift | 68 +++ .../MacroSwift/ExtensionScopeParity.swift | 25 + .../Multifile/CrossFileNestedTypeClass.swift | 11 + .../CrossFileNestedTypeExtension.swift | 6 + .../CrossFileNestedTypeExtension.json | 100 ++++ .../CrossFileNestedTypeExtension.swift | 74 +++ .../ExtensionNestedTypes.json | 370 ++++++++++++++ .../ExtensionNestedTypes.swift | 342 +++++++++++++ .../ExtensionScopeParity.json | 151 ++++++ .../ExtensionScopeParity.swift | 167 +++++++ .../ExtensionNestedTypes.d.ts | 82 ++++ .../BridgeJSLinkTests/ExtensionNestedTypes.js | 457 ++++++++++++++++++ .../ExtensionScopeParity.d.ts | 52 ++ .../BridgeJSLinkTests/ExtensionScopeParity.js | 354 ++++++++++++++ .../CrossFileNestedTypeClassAPIs.swift | 13 + .../CrossFileNestedTypeExtensionAPIs.swift | 8 + .../ExtensionNestedTypesAPIs.swift | 70 +++ .../Generated/BridgeJS.swift | 390 +++++++++++++++ .../Generated/JavaScript/BridgeJS.json | 422 ++++++++++++++++ Tests/prelude.mjs | 23 + 23 files changed, 3301 insertions(+), 57 deletions(-) create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ExtensionNestedTypes.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ExtensionScopeParity.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileNestedTypeClass.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileNestedTypeExtension.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileNestedTypeExtension.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileNestedTypeExtension.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionNestedTypes.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionNestedTypes.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionScopeParity.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionScopeParity.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionNestedTypes.d.ts create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionNestedTypes.js create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionScopeParity.d.ts create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionScopeParity.js create mode 100644 Tests/BridgeJSRuntimeTests/CrossFileNestedTypeClassAPIs.swift create mode 100644 Tests/BridgeJSRuntimeTests/CrossFileNestedTypeExtensionAPIs.swift create mode 100644 Tests/BridgeJSRuntimeTests/ExtensionNestedTypesAPIs.swift diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index 937ec5c41..f119f5bff 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -536,12 +536,12 @@ public final class SwiftToSkeleton { if let typeDecl = typeDeclResolver.resolve(type) { if typeDecl.is(ProtocolDeclSyntax.self) { - let swiftCallName = SwiftToSkeleton.computeSwiftCallName(for: typeDecl, itemName: typeDecl.name.text) + let swiftCallName = computeSwiftCallName(for: typeDecl, itemName: typeDecl.name.text) return .swiftProtocol(swiftCallName) } if let enumDecl = typeDecl.as(EnumDeclSyntax.self) { - let swiftCallName = SwiftToSkeleton.computeSwiftCallName(for: enumDecl, itemName: enumDecl.name.text) + let swiftCallName = computeSwiftCallName(for: enumDecl, itemName: enumDecl.name.text) if let jsAttribute = enumDecl.attributes.firstJSAttribute, let aliasTarget = extractAliasTarget(from: jsAttribute) { @@ -580,7 +580,7 @@ public final class SwiftToSkeleton { } if let structDecl = typeDecl.as(StructDeclSyntax.self) { - let swiftCallName = SwiftToSkeleton.computeSwiftCallName( + let swiftCallName = computeSwiftCallName( for: structDecl, itemName: structDecl.name.text ) @@ -598,7 +598,7 @@ public final class SwiftToSkeleton { guard typeDecl.is(ClassDeclSyntax.self) || typeDecl.is(ActorDeclSyntax.self) else { return nil } - let swiftCallName = SwiftToSkeleton.computeSwiftCallName(for: typeDecl, itemName: typeDecl.name.text) + let swiftCallName = computeSwiftCallName(for: typeDecl, itemName: typeDecl.name.text) // A type annotated with @JSClass is a JavaScript object wrapper (imported), // even if it is declared as a Swift class. @@ -638,7 +638,7 @@ public final class SwiftToSkeleton { private func resolveExternal(for type: TypeSyntax, errors: inout [DiagnosticError]) -> BridgeType? { guard !externalModuleIndex.isEmpty, - var components = typeDeclResolver.qualifiedComponents(from: type) + var components = type.qualifiedComponents else { return nil } @@ -777,27 +777,50 @@ public final class SwiftToSkeleton { return nil } - /// Computes the full Swift call name by walking up the AST hierarchy to find all parent enums + /// This currently doesn’t work correctly for extensions on types defined in other modules, + /// which is fine for now since we don’t support extending @JS types from other modules. + /// This will need updating when we do. + fileprivate func enclosingDeclarations(of node: some SyntaxProtocol) -> [Syntax] { + var declarations: [Syntax] = [] + var visitedExtendedTypes: Set = [] + var currentNode: Syntax? = Syntax(node).parent + + while let parent = currentNode { + if let extensionDecl = parent.as(ExtensionDeclSyntax.self) { + if let extendedDecl = typeDeclResolver.resolve(extensionDecl.extendedType), + visitedExtendedTypes.insert(extendedDecl.id).inserted + { + declarations.append(Syntax(extendedDecl)) + currentNode = Syntax(extendedDecl).parent + } else { + currentNode = parent.parent + } + } else { + declarations.append(parent) + currentNode = parent.parent + } + } + return declarations + } + /// This generates the qualified name needed for Swift code generation (e.g., "Networking.API.HTTPServer") - fileprivate static func computeSwiftCallName(for node: some SyntaxProtocol, itemName: String) -> String { + fileprivate func computeSwiftCallName(for node: some SyntaxProtocol, itemName: String) -> String { var swiftPath: [String] = [] - var currentNode: Syntax? = node.parent - while let parent = currentNode { - if let enumDecl = parent.as(EnumDeclSyntax.self), + for declaration in enclosingDeclarations(of: node) { + if let enumDecl = declaration.as(EnumDeclSyntax.self), enumDecl.attributes.hasJSAttribute() { swiftPath.insert(enumDecl.name.text, at: 0) - } else if let structDecl = parent.as(StructDeclSyntax.self), + } else if let structDecl = declaration.as(StructDeclSyntax.self), structDecl.attributes.hasJSAttribute() { swiftPath.insert(structDecl.name.text, at: 0) - } else if let classDecl = parent.as(ClassDeclSyntax.self), + } else if let classDecl = declaration.as(ClassDeclSyntax.self), classDecl.attributes.hasJSAttribute() { swiftPath.insert(classDecl.name.text, at: 0) } - currentNode = parent.parent } if swiftPath.isEmpty { @@ -1883,7 +1906,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { resolvedNamespace: namespaceResult.namespace, parentTypeNamespace: computeParentTypeNamespace(for: node) ) - let swiftCallName = SwiftToSkeleton.computeSwiftCallName(for: node, itemName: name) + let swiftCallName = parent.computeSwiftCallName(for: node, itemName: name) let explicitAccessControl = computeExplicitAtLeastInternalAccessControl( for: node, message: "Class visibility must be at least internal" @@ -1949,25 +1972,23 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { } /// Walks extension members under the matching type’s state, returning whether the type was found. - /// - /// Note: The lookup scans dictionaries keyed by `makeKey(name:namespace:)`, matching only by - /// plain name. If two types share a name but differ by namespace, `.first(where:)` picks - /// whichever comes first. This is acceptable today since namespace collisions are unlikely, - /// but may need refinement if namespace-qualified extension resolution is added. func resolveExtension(_ ext: ExtensionDeclSyntax) -> Bool { - let name = ext.extendedType.trimmedDescription + guard let extendedDecl = parent.typeDeclResolver.resolve(ext.extendedType) else { + return false + } + let swiftCallName = parent.computeSwiftCallName(for: extendedDecl, itemName: extendedDecl.name.text) let state: State - if let entry = exportedClassByName.first(where: { $0.value.name == name }) { - state = .classBody(name: name, key: entry.key) - } else if let entry = exportedStructByName.first(where: { $0.value.name == name }) { - state = .structBody(name: name, key: entry.key) - } else if let entry = exportedEnumByName.first(where: { $0.value.name == name }) { - state = .enumBody(name: name, key: entry.key) - } else if exportedProtocolByName.values.contains(where: { $0.name == name }) { + if let entry = exportedClassByName.first(where: { $0.value.swiftCallName == swiftCallName }) { + state = .classBody(name: entry.value.name, key: entry.key) + } else if let entry = exportedStructByName.first(where: { $0.value.swiftCallName == swiftCallName }) { + state = .structBody(name: entry.value.name, key: entry.key) + } else if let entry = exportedEnumByName.first(where: { $0.value.swiftCallName == swiftCallName }) { + state = .enumBody(name: entry.value.name, key: entry.key) + } else if exportedProtocolByName.values.contains(where: { $0.name == swiftCallName }) { diagnose( node: ext.extendedType, message: "Protocol extensions are not supported by BridgeJS.", - hint: "You cannot extend `@JS` protocol '\(name)' with additional members" + hint: "You cannot extend `@JS` protocol '\(swiftCallName)' with additional members" ) return true } else { @@ -1986,7 +2007,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { jsAttribute: AttributeSyntax, aliasTarget: TypeSyntax ) { - let swiftCallName = SwiftToSkeleton.computeSwiftCallName(for: node, itemName: node.name.text) + let swiftCallName = parent.computeSwiftCallName(for: node, itemName: node.name.text) if extractNamespace(from: jsAttribute) != nil { errors.append( DiagnosticError( @@ -2051,7 +2072,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { parentTypeNamespace: computeParentTypeNamespace(for: node) ) let emitStyle = extractEnumStyle(from: jsAttribute) ?? .const - let swiftCallName = SwiftToSkeleton.computeSwiftCallName(for: node, itemName: name) + let swiftCallName = parent.computeSwiftCallName(for: node, itemName: name) let explicitAccessControl = computeExplicitAtLeastInternalAccessControl( for: node, message: "Enum visibility must be at least internal" @@ -2237,7 +2258,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { resolvedNamespace: namespaceResult.namespace, parentTypeNamespace: computeParentTypeNamespace(for: node) ) - let swiftCallName = SwiftToSkeleton.computeSwiftCallName(for: node, itemName: name) + let swiftCallName = parent.computeSwiftCallName(for: node, itemName: name) let explicitAccessControl = computeExplicitAtLeastInternalAccessControl( for: node, message: "Struct visibility must be at least internal" @@ -2552,10 +2573,9 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { /// Method allows for explicit namespace for top level enum, it will be used as base namespace and will concat enum name private func computeNamespace(for node: some SyntaxProtocol) -> [String]? { var namespace: [String] = [] - var currentNode: Syntax? = node.parent - while let parent = currentNode { - if let enumDecl = parent.as(EnumDeclSyntax.self), + for declaration in parent.enclosingDeclarations(of: node) { + if let enumDecl = declaration.as(EnumDeclSyntax.self), enumDecl.attributes.hasJSAttribute() { let isNamespaceEnum = !enumDecl.memberBlock.members.contains { member in @@ -2572,7 +2592,6 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { } } } - currentNode = parent.parent } return namespace.isEmpty ? nil : namespace @@ -2580,19 +2599,17 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { private func computeParentTypeNamespace(for node: some SyntaxProtocol) -> [String]? { var path: [String] = [] - var currentNode: Syntax? = node.parent - while let parent = currentNode { - if let structDecl = parent.as(StructDeclSyntax.self), + for declaration in parent.enclosingDeclarations(of: node) { + if let structDecl = declaration.as(StructDeclSyntax.self), structDecl.attributes.hasJSAttribute() { path.insert(structDecl.name.text, at: 0) - } else if let classDecl = parent.as(ClassDeclSyntax.self), + } else if let classDecl = declaration.as(ClassDeclSyntax.self), classDecl.attributes.hasJSAttribute() { path.insert(classDecl.name.text, at: 0) } - currentNode = parent.parent } return path.isEmpty ? nil : path diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/TypeDeclResolver.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/TypeDeclResolver.swift index ec04421aa..e5d77939b 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/TypeDeclResolver.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/TypeDeclResolver.swift @@ -16,8 +16,7 @@ class TypeDeclResolver { private class TypeDeclCollector: SyntaxVisitor { let resolver: TypeDeclResolver - var scope: [TypeDecl] = [] - var rootTypeDecls: [TypeDecl] = [] + var scope: [String] = [] init(resolver: TypeDeclResolver) { self.resolver = resolver @@ -26,17 +25,14 @@ class TypeDeclResolver { func visitNominalDecl(_ node: TypeDecl) -> SyntaxVisitorContinueKind { let name = node.name.text - let qualifiedName = scope.map(\.name.text) + [name] + let qualifiedName = scope + [name] resolver.typeDeclByQualifiedName[qualifiedName] = node - scope.append(node) + scope.append(name) return .visitChildren } func visitPostNominalDecl() { - let type = scope.removeLast() - if scope.isEmpty { - rootTypeDecls.append(type) - } + scope.removeLast() } override func visit(_ node: StructDeclSyntax) -> SyntaxVisitorContinueKind { @@ -72,10 +68,21 @@ class TypeDeclResolver { override func visit(_ node: TypeAliasDeclSyntax) -> SyntaxVisitorContinueKind { let name = node.name.text - let qualifiedName = scope.map(\.name.text) + [name] + let qualifiedName = scope + [name] resolver.typeAliasByQualifiedName[qualifiedName] = node return .skipChildren } + + override func visit(_ node: ExtensionDeclSyntax) -> SyntaxVisitorContinueKind { + guard let components = node.memberScopeComponents else { + return .skipChildren + } + scope.append(contentsOf: components) + return .visitChildren + } + override func visitPost(_ node: ExtensionDeclSyntax) { + scope.removeLast(node.memberScopeComponents?.count ?? 0) + } } /// Collects type declarations from a parsed Swift source file @@ -91,6 +98,10 @@ class TypeDeclResolver { while let parent = context.parent { if let parent = parent.asProtocol(NamedDeclSyntax.self), parent.isProtocol(DeclGroupSyntax.self) { innerToOuter.append(parent.name.text) + } else if let extensionDecl = parent.as(ExtensionDeclSyntax.self), + let components = extensionDecl.memberScopeComponents + { + innerToOuter.append(contentsOf: components.reversed()) } context = parent } @@ -106,7 +117,7 @@ class TypeDeclResolver { /// Search for the type declaration from the innermost scope to the outermost scope for i in (0...scope.count).reversed() { let qualifiedName = Array(scope[0.. QualifiedName? { - if let m = type.as(MemberTypeSyntax.self) { - guard let base = qualifiedComponents(from: TypeSyntax(m.baseType)) else { return nil } +} + +extension TypeSyntax { + var qualifiedComponents: TypeDeclResolver.QualifiedName? { + if let m = self.as(MemberTypeSyntax.self) { + guard let base = TypeSyntax(m.baseType).qualifiedComponents else { return nil } return base + [m.name.text] - } else if let id = type.as(IdentifierTypeSyntax.self) { + } else if let id = self.as(IdentifierTypeSyntax.self) { return [id.name.text] } else { return nil } } } + +extension ExtensionDeclSyntax { + var memberScopeComponents: TypeDeclResolver.QualifiedName? { + extendedType.qualifiedComponents + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift index 6d2f3d453..baffc0c20 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift @@ -336,6 +336,28 @@ import Testing try snapshotCodegen(skeleton: skeleton, name: "CrossFileExtension") } + @Test + func codegenCrossFileNestedTypeExtension() throws { + let swiftAPI = SwiftToSkeleton( + progress: .silent, + moduleName: "TestModule", + exposeToGlobal: false, + externalModuleIndex: .empty + ) + let classURL = Self.multifileInputsDirectory.appendingPathComponent("CrossFileNestedTypeClass.swift") + swiftAPI.addSourceFile( + Parser.parse(source: try String(contentsOf: classURL, encoding: .utf8)), + inputFilePath: "CrossFileNestedTypeClass.swift" + ) + let extensionURL = Self.multifileInputsDirectory.appendingPathComponent("CrossFileNestedTypeExtension.swift") + swiftAPI.addSourceFile( + Parser.parse(source: try String(contentsOf: extensionURL, encoding: .utf8)), + inputFilePath: "CrossFileNestedTypeExtension.swift" + ) + let skeleton = try swiftAPI.finalize() + try snapshotCodegen(skeleton: skeleton, name: "CrossFileNestedTypeExtension") + } + @Test func codegenSkipsEmptySkeletons() throws { let swiftAPI = SwiftToSkeleton( diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ExtensionNestedTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ExtensionNestedTypes.swift new file mode 100644 index 000000000..b3ef8ddaf --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ExtensionNestedTypes.swift @@ -0,0 +1,68 @@ +@JS class Library { + @JS var name: String + + @JS init(name: String) { + self.name = name + } + + @JS func describe() -> String { + name + } +} + +extension Library { + typealias Title = String + + @JS enum Genre: String { + case fiction + case reference + } + + @JS struct Shelf { + var label: String + + @JS init(label: String) { + self.label = label + } + + @JS static var capacity: Int { 32 } + } + + @JS func rename(_ title: Title) -> Title { + title + } + + @JS func shelf(label: String) -> Shelf { + Shelf(label: label) + } +} + +extension Library.Shelf { + @JS struct Divider { + var slot: Int + + @JS init(slot: Int) { + self.slot = slot + } + } + + @JS func describeShelf() -> String { + "Shelf: " + label + } +} + +@JS enum Message { + case update(Update) + case delete +} + +extension Message { + @JS enum Update { + case flip + case rotate + } +} + +@JS func roundTripMessage(_ message: Message) -> Message { + message +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ExtensionScopeParity.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ExtensionScopeParity.swift new file mode 100644 index 000000000..43a71c484 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ExtensionScopeParity.swift @@ -0,0 +1,25 @@ +@JS(namespace: "app") enum Toolbox { + @JS class Mallet { + @JS init() {} + } +} + +extension Toolbox { + @JS class Hammer { + @JS init() {} + } +} + +@JS enum Signal: String { + case ready +} + +extension Signal { + @JS struct Meta { + var note: String + + @JS init(note: String) { + self.note = note + } + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileNestedTypeClass.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileNestedTypeClass.swift new file mode 100644 index 000000000..7fa16b59f --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileNestedTypeClass.swift @@ -0,0 +1,11 @@ +@JS class Workspace { + let name: String + + @JS init(name: String) { + self.name = name + } + + @JS func describe() -> String { + name + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileNestedTypeExtension.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileNestedTypeExtension.swift new file mode 100644 index 000000000..1e99eae1e --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileNestedTypeExtension.swift @@ -0,0 +1,6 @@ +extension Workspace { + @JS enum Kind: String { + case personal + case shared + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileNestedTypeExtension.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileNestedTypeExtension.json new file mode 100644 index 000000000..ad8a71bb7 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileNestedTypeExtension.json @@ -0,0 +1,100 @@ +{ + "exported" : { + "aliases" : [ + + ], + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_Workspace_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "name", + "name" : "name", + "type" : { + "string" : { + + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_Workspace_describe", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "describe", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "name" : "Workspace", + "properties" : [ + + ], + "swiftCallName" : "Workspace" + } + ], + "enums" : [ + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "personal" + }, + { + "associatedValues" : [ + + ], + "name" : "shared" + } + ], + "emitStyle" : "const", + "name" : "Kind", + "namespace" : [ + "Workspace" + ], + "rawType" : "String", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Workspace.Kind", + "tsFullPath" : "Workspace.Kind" + } + ], + "exposeToGlobal" : false, + "functions" : [ + + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileNestedTypeExtension.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileNestedTypeExtension.swift new file mode 100644 index 000000000..7601f0f72 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileNestedTypeExtension.swift @@ -0,0 +1,74 @@ +extension Workspace.Kind: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +} + +@_expose(wasm, "bjs_Workspace_init") +@_cdecl("bjs_Workspace_init") +public func _bjs_Workspace_init(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = Workspace(name: String.bridgeJSLiftParameter(nameBytes, nameLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Workspace_describe") +@_cdecl("bjs_Workspace_describe") +public func _bjs_Workspace_describe(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = Workspace.bridgeJSLiftParameter(_self).describe() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Workspace_deinit") +@_cdecl("bjs_Workspace_deinit") +public func _bjs_Workspace_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension Workspace: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_Workspace_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_Workspace_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_Workspace_wrap") +fileprivate func _bjs_Workspace_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_Workspace_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_Workspace_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Workspace_wrap_extern(pointer) +} + +extension Workspace.Kind: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Workspace.Kind.bridgeJSMakeTypeHandle() +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Workspace.Kind.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionNestedTypes.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionNestedTypes.json new file mode 100644 index 000000000..e6cf2b271 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionNestedTypes.json @@ -0,0 +1,370 @@ +{ + "exported" : { + "aliases" : [ + + ], + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_Library_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "name", + "name" : "name", + "type" : { + "string" : { + + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_Library_describe", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "describe", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_Library_rename", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "rename", + "parameters" : [ + { + "label" : "_", + "name" : "title", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_Library_shelf", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "shelf", + "parameters" : [ + { + "label" : "label", + "name" : "label", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "Library.Shelf" + } + } + } + ], + "name" : "Library", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "name", + "type" : { + "string" : { + + } + } + } + ], + "swiftCallName" : "Library" + } + ], + "enums" : [ + { + "cases" : [ + { + "associatedValues" : [ + { + "type" : { + "caseEnum" : { + "_0" : "Message.Update" + } + } + } + ], + "name" : "update" + }, + { + "associatedValues" : [ + + ], + "name" : "delete" + } + ], + "emitStyle" : "const", + "name" : "Message", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Message", + "tsFullPath" : "Message" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "fiction" + }, + { + "associatedValues" : [ + + ], + "name" : "reference" + } + ], + "emitStyle" : "const", + "name" : "Genre", + "namespace" : [ + "Library" + ], + "rawType" : "String", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Library.Genre", + "tsFullPath" : "Library.Genre" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "flip" + }, + { + "associatedValues" : [ + + ], + "name" : "rotate" + } + ], + "emitStyle" : "const", + "name" : "Update", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Message.Update", + "tsFullPath" : "Update" + } + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_roundTripMessage", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripMessage", + "parameters" : [ + { + "label" : "_", + "name" : "message", + "type" : { + "associatedValueEnum" : { + "_0" : "Message" + } + } + } + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "Message" + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + { + "constructor" : { + "abiName" : "bjs_Library_Shelf_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "label", + "name" : "label", + "type" : { + "string" : { + + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_Library_Shelf_describeShelf", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "describeShelf", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "name" : "Shelf", + "namespace" : [ + "Library" + ], + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "label", + "namespace" : [ + "Library" + ], + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : true, + "name" : "capacity", + "staticContext" : { + "structName" : { + "_0" : "Library_Shelf" + } + }, + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "swiftCallName" : "Library.Shelf" + }, + { + "constructor" : { + "abiName" : "bjs_Library_Shelf_Divider_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "slot", + "name" : "slot", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ] + }, + "methods" : [ + + ], + "name" : "Divider", + "namespace" : [ + "Library", + "Shelf" + ], + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "slot", + "namespace" : [ + "Library", + "Shelf" + ], + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "swiftCallName" : "Library.Shelf.Divider" + } + ] + }, + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionNestedTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionNestedTypes.swift new file mode 100644 index 000000000..d7efa630c --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionNestedTypes.swift @@ -0,0 +1,342 @@ +extension Message: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> Message { + switch caseId { + case 0: + return .update(Message.Update.bridgeJSStackPop()) + case 1: + return .delete + default: + fatalError("Unknown Message case ID: \(caseId)") + } + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { + switch self { + case .update(let param0): + param0.bridgeJSStackPush() + return Int32(0) + case .delete: + return Int32(1) + } + } +} + +extension Library.Genre: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +} + +extension Message.Update: _BridgedSwiftCaseEnum { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + return bridgeJSRawValue + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> Message.Update { + return bridgeJSLiftParameter(value) + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> Message.Update { + return Message.Update(bridgeJSRawValue: value)! + } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { + return bridgeJSLowerParameter() + } + + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { + switch bridgeJSRawValue { + case 0: + self = .flip + case 1: + self = .rotate + default: + return nil + } + } + + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { + switch self { + case .flip: + return 0 + case .rotate: + return 1 + } + } +} + +extension Library.Shelf: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Library.Shelf { + let label = String.bridgeJSStackPop() + return Library.Shelf(label: label) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.label.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_Library_Shelf(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Library_Shelf())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Library_Shelf") +fileprivate func _bjs_struct_lower_Library_Shelf_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_Library_Shelf_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_Library_Shelf(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Library_Shelf_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Library_Shelf") +fileprivate func _bjs_struct_lift_Library_Shelf_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_Library_Shelf_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_Library_Shelf() -> Int32 { + return _bjs_struct_lift_Library_Shelf_extern() +} + +@_expose(wasm, "bjs_Library_Shelf_init") +@_cdecl("bjs_Library_Shelf_init") +public func _bjs_Library_Shelf_init(_ labelBytes: Int32, _ labelLength: Int32) -> Void { + #if arch(wasm32) + let ret = Library.Shelf(label: String.bridgeJSLiftParameter(labelBytes, labelLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Library_Shelf_static_capacity_get") +@_cdecl("bjs_Library_Shelf_static_capacity_get") +public func _bjs_Library_Shelf_static_capacity_get() -> Int32 { + #if arch(wasm32) + let ret = Library.Shelf.capacity + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Library_Shelf_describeShelf") +@_cdecl("bjs_Library_Shelf_describeShelf") +public func _bjs_Library_Shelf_describeShelf() -> Void { + #if arch(wasm32) + let ret = Library.Shelf.bridgeJSLiftParameter().describeShelf() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension Library.Shelf.Divider: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Library.Shelf.Divider { + let slot = Int.bridgeJSStackPop() + return Library.Shelf.Divider(slot: slot) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.slot.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_Library_Shelf_Divider(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Library_Shelf_Divider())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Library_Shelf_Divider") +fileprivate func _bjs_struct_lower_Library_Shelf_Divider_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_Library_Shelf_Divider_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_Library_Shelf_Divider(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Library_Shelf_Divider_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Library_Shelf_Divider") +fileprivate func _bjs_struct_lift_Library_Shelf_Divider_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_Library_Shelf_Divider_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_Library_Shelf_Divider() -> Int32 { + return _bjs_struct_lift_Library_Shelf_Divider_extern() +} + +@_expose(wasm, "bjs_Library_Shelf_Divider_init") +@_cdecl("bjs_Library_Shelf_Divider_init") +public func _bjs_Library_Shelf_Divider_init(_ slot: Int32) -> Void { + #if arch(wasm32) + let ret = Library.Shelf.Divider(slot: Int.bridgeJSLiftParameter(slot)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_roundTripMessage") +@_cdecl("bjs_roundTripMessage") +public func _bjs_roundTripMessage(_ message: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripMessage(_: Message.bridgeJSLiftParameter(message)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Library_init") +@_cdecl("bjs_Library_init") +public func _bjs_Library_init(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = Library(name: String.bridgeJSLiftParameter(nameBytes, nameLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Library_describe") +@_cdecl("bjs_Library_describe") +public func _bjs_Library_describe(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = Library.bridgeJSLiftParameter(_self).describe() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Library_rename") +@_cdecl("bjs_Library_rename") +public func _bjs_Library_rename(_ _self: UnsafeMutableRawPointer, _ titleBytes: Int32, _ titleLength: Int32) -> Void { + #if arch(wasm32) + let ret = Library.bridgeJSLiftParameter(_self).rename(_: String.bridgeJSLiftParameter(titleBytes, titleLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Library_shelf") +@_cdecl("bjs_Library_shelf") +public func _bjs_Library_shelf(_ _self: UnsafeMutableRawPointer, _ labelBytes: Int32, _ labelLength: Int32) -> Void { + #if arch(wasm32) + let ret = Library.bridgeJSLiftParameter(_self).shelf(label: String.bridgeJSLiftParameter(labelBytes, labelLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Library_name_get") +@_cdecl("bjs_Library_name_get") +public func _bjs_Library_name_get(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = Library.bridgeJSLiftParameter(_self).name + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Library_name_set") +@_cdecl("bjs_Library_name_set") +public func _bjs_Library_name_set(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + #if arch(wasm32) + Library.bridgeJSLiftParameter(_self).name = String.bridgeJSLiftParameter(valueBytes, valueLength) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Library_deinit") +@_cdecl("bjs_Library_deinit") +public func _bjs_Library_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension Library: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_Library_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_Library_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_Library_wrap") +fileprivate func _bjs_Library_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_Library_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_Library_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Library_wrap_extern(pointer) +} + +extension Library.Shelf: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Library.Shelf.bridgeJSMakeTypeHandle() +} + +extension Library.Shelf.Divider: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Library.Shelf.Divider.bridgeJSMakeTypeHandle() +} + +extension Message: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Message.bridgeJSMakeTypeHandle() +} + +extension Library.Genre: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Library.Genre.bridgeJSMakeTypeHandle() +} + +extension Message.Update: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Message.Update.bridgeJSMakeTypeHandle() +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Library.Shelf.bridgeJSTypeID, + Library.Shelf.Divider.bridgeJSTypeID, + Message.bridgeJSTypeID, + Library.Genre.bridgeJSTypeID, + Message.Update.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionScopeParity.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionScopeParity.json new file mode 100644 index 000000000..2e25e938e --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionScopeParity.json @@ -0,0 +1,151 @@ +{ + "exported" : { + "aliases" : [ + + ], + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_app_Toolbox_Mallet_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + + ], + "name" : "Mallet", + "namespace" : [ + "app", + "Toolbox" + ], + "properties" : [ + + ], + "swiftCallName" : "Toolbox.Mallet" + }, + { + "constructor" : { + "abiName" : "bjs_app_Toolbox_Hammer_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + + ], + "name" : "Hammer", + "namespace" : [ + "app", + "Toolbox" + ], + "properties" : [ + + ], + "swiftCallName" : "Toolbox.Hammer" + } + ], + "enums" : [ + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "Toolbox", + "namespace" : [ + "app" + ], + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Toolbox", + "tsFullPath" : "app.Toolbox" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "ready" + } + ], + "emitStyle" : "const", + "name" : "Signal", + "rawType" : "String", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Signal", + "tsFullPath" : "Signal" + } + ], + "exposeToGlobal" : false, + "functions" : [ + + ], + "protocols" : [ + + ], + "structs" : [ + { + "constructor" : { + "abiName" : "bjs_Meta_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "note", + "name" : "note", + "type" : { + "string" : { + + } + } + } + ] + }, + "methods" : [ + + ], + "name" : "Meta", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "note", + "type" : { + "string" : { + + } + } + } + ], + "swiftCallName" : "Signal.Meta" + } + ] + }, + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionScopeParity.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionScopeParity.swift new file mode 100644 index 000000000..7fe6db4d2 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionScopeParity.swift @@ -0,0 +1,167 @@ +extension Signal: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +} + +extension Signal.Meta: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Signal.Meta { + let note = String.bridgeJSStackPop() + return Signal.Meta(note: note) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.note.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_Meta(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Meta())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Meta") +fileprivate func _bjs_struct_lower_Meta_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_Meta_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_Meta(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Meta_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Meta") +fileprivate func _bjs_struct_lift_Meta_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_Meta_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_Meta() -> Int32 { + return _bjs_struct_lift_Meta_extern() +} + +@_expose(wasm, "bjs_Meta_init") +@_cdecl("bjs_Meta_init") +public func _bjs_Meta_init(_ noteBytes: Int32, _ noteLength: Int32) -> Void { + #if arch(wasm32) + let ret = Signal.Meta(note: String.bridgeJSLiftParameter(noteBytes, noteLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_app_Toolbox_Mallet_init") +@_cdecl("bjs_app_Toolbox_Mallet_init") +public func _bjs_app_Toolbox_Mallet_init() -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = Toolbox.Mallet() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_app_Toolbox_Mallet_deinit") +@_cdecl("bjs_app_Toolbox_Mallet_deinit") +public func _bjs_app_Toolbox_Mallet_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension Toolbox.Mallet: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_app_Toolbox_Mallet_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_app_Toolbox_Mallet_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_app_Toolbox_Mallet_wrap") +fileprivate func _bjs_app_Toolbox_Mallet_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_app_Toolbox_Mallet_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_app_Toolbox_Mallet_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_app_Toolbox_Mallet_wrap_extern(pointer) +} + +@_expose(wasm, "bjs_app_Toolbox_Hammer_init") +@_cdecl("bjs_app_Toolbox_Hammer_init") +public func _bjs_app_Toolbox_Hammer_init() -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = Toolbox.Hammer() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_app_Toolbox_Hammer_deinit") +@_cdecl("bjs_app_Toolbox_Hammer_deinit") +public func _bjs_app_Toolbox_Hammer_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension Toolbox.Hammer: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_app_Toolbox_Hammer_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_app_Toolbox_Hammer_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_app_Toolbox_Hammer_wrap") +fileprivate func _bjs_app_Toolbox_Hammer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_app_Toolbox_Hammer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_app_Toolbox_Hammer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_app_Toolbox_Hammer_wrap_extern(pointer) +} + +extension Signal.Meta: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Signal.Meta.bridgeJSMakeTypeHandle() +} + +extension Signal: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Signal.bridgeJSMakeTypeHandle() +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Signal.Meta.bridgeJSTypeID, + Signal.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionNestedTypes.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionNestedTypes.d.ts new file mode 100644 index 000000000..df59ccefd --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionNestedTypes.d.ts @@ -0,0 +1,82 @@ +// 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`. + +export const MessageValues: { + readonly Tag: { + readonly Update: 0; + readonly Delete: 1; + }; +}; + +export type MessageTag = + { tag: typeof MessageValues.Tag.Update; param0: UpdateTag } | { tag: typeof MessageValues.Tag.Delete } + +export const UpdateValues: { + readonly Flip: 0; + readonly Rotate: 1; +}; +export type UpdateTag = typeof UpdateValues[keyof typeof UpdateValues]; + +export type MessageObject = typeof MessageValues; + +export type GenreObject = typeof Library.GenreValues; + +export type UpdateObject = typeof UpdateValues; + +export namespace Library { + const GenreValues: { + readonly Fiction: "fiction"; + readonly Reference: "reference"; + }; + type GenreTag = typeof GenreValues[keyof typeof GenreValues]; + export interface Shelf { + label: string; + describeShelf(): string; + } + export namespace Shelf { + export interface Divider { + slot: number; + } + } +} +/// Represents a Swift heap object like a class instance or an actor instance. +export interface SwiftHeapObject { + /// Release the heap object. + /// + /// Note: Calling this method will release the heap object and it will no longer be accessible. + release(): void; +} +export interface Library extends SwiftHeapObject { + describe(): string; + rename(title: string): string; + shelf(label: string): Library.Shelf; + name: string; +} +export type Exports = { + roundTripMessage(message: MessageTag): MessageTag; + Message: MessageObject + Update: UpdateObject + Library: { + new(name: string): Library; + Genre: GenreObject + Shelf: { + init(label: string): Library.Shelf; + readonly capacity: number; + Divider: { + init(slot: number): Library.Shelf.Divider; + }, + }, + }, +} +export type Imports = { +} +export function createInstantiator(options: { + imports: Imports; +}, swift: any): Promise<{ + addImports: (importObject: WebAssembly.Imports) => void; + setInstance: (instance: WebAssembly.Instance) => void; + createExports: (instance: WebAssembly.Instance) => Exports; +}>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionNestedTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionNestedTypes.js new file mode 100644 index 000000000..d031ff64b --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionNestedTypes.js @@ -0,0 +1,457 @@ +// 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`. + +export const MessageValues = { + Tag: { + Update: 0, + Delete: 1, + }, +}; +export const GenreValues = { + Fiction: "fiction", + Reference: "reference", +}; + +export const UpdateValues = { + Flip: 0, + Rotate: 1, +}; + +export async function createInstantiator(options, swift) { + let instance; + let memory; + let setException; + let decodeString; + const textDecoder = new TextDecoder("utf-8"); + const textEncoder = new TextEncoder("utf-8"); + let tmpRetString; + let tmpRetBytes; + let tmpRetException; + let tmpRetOptionalBool; + let tmpRetOptionalInt; + let tmpRetOptionalFloat; + let tmpRetOptionalDouble; + let tmpRetOptionalHeapObject; + let strStack = []; + let i32Stack = []; + let i64Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; + let taStack = []; + const enumHelpers = {}; + const structHelpers = {}; + + let _exports = null; + let bjs = null; + const __bjs_createStructHelpers_M10TestModuleT7LibraryT5Shelf = () => ({ + lower: (value) => { + const bytes = textEncoder.encode(value.label); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + }, + lift: () => { + const string = strStack.pop(); + const instance1 = { label: string }; + instance1.describeShelf = function() { + structHelpers.M10TestModuleT7LibraryT5Shelf.lower(this); + const ret = instance.exports.bjs_Library_Shelf_describeShelf(); + const ret1 = tmpRetString; + tmpRetString = undefined; + return ret1; + }.bind(instance1); + return instance1; + } + }); + const __bjs_createStructHelpers_M10TestModuleT7LibraryT5ShelfT7Divider = () => ({ + lower: (value) => { + i32Stack.push((value.slot | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return { slot: int }; + } + }); + const __bjs_createEnumHelpers_M10TestModuleT7Message = () => ({ + lower: (value) => { + const enumTag = value.tag; + switch (enumTag) { + case MessageValues.Tag.Update: { + i32Stack.push((value.param0 | 0)); + return MessageValues.Tag.Update; + } + case MessageValues.Tag.Delete: { + return MessageValues.Tag.Delete; + } + default: throw new Error("Unknown MessageValues tag: " + String(enumTag)); + } + }, + lift: (tag) => { + tag = tag | 0; + switch (tag) { + case MessageValues.Tag.Update: { + const caseId = i32Stack.pop(); + return { tag: MessageValues.Tag.Update, param0: caseId }; + } + case MessageValues.Tag.Delete: return { tag: MessageValues.Tag.Delete }; + default: throw new Error("Unknown MessageValues tag returned from Swift: " + String(tag)); + } + } + }); + + return { + /** + * @param {WebAssembly.Imports} importObject + */ + addImports: (importObject, importsContext) => { + bjs = {}; + importObject["bjs"] = bjs; + bjs["swift_js_return_string"] = function(ptr, len) { + tmpRetString = decodeString(ptr, len); + } + bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { + const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); + bytes.set(source); + } + bjs["swift_js_make_js_string"] = function(ptr, len) { + return swift.memory.retain(decodeString(ptr, len)); + } + bjs["swift_js_init_memory_with_result"] = function(ptr, len) { + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); + target.set(tmpRetBytes); + tmpRetBytes = undefined; + } + bjs["swift_js_throw"] = function(id) { + tmpRetException = swift.memory.retainByRef(id); + } + bjs["swift_js_retain"] = function(id) { + return swift.memory.retainByRef(id); + } + bjs["swift_js_release"] = function(id) { + swift.memory.release(id); + } + bjs["swift_js_push_i32"] = function(v) { + i32Stack.push(v | 0); + } + bjs["swift_js_push_f32"] = function(v) { + f32Stack.push(Math.fround(v)); + } + bjs["swift_js_push_f64"] = function(v) { + f64Stack.push(v); + } + bjs["swift_js_push_string"] = function(ptr, len) { + const value = decodeString(ptr, len); + strStack.push(value); + } + bjs["swift_js_pop_i32"] = function() { + return i32Stack.pop(); + } + bjs["swift_js_pop_f32"] = function() { + return f32Stack.pop(); + } + bjs["swift_js_pop_f64"] = function() { + return f64Stack.pop(); + } + bjs["swift_js_push_pointer"] = function(pointer) { + ptrStack.push(pointer); + } + bjs["swift_js_pop_pointer"] = function() { + return ptrStack.pop(); + } + bjs["swift_js_push_i64"] = function(v) { + i64Stack.push(v); + } + bjs["swift_js_pop_i64"] = function() { + return i64Stack.pop(); + } + const taCtors = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array]; + bjs["swift_js_push_typed_array"] = function(kind, ptr, count) { + const Ctor = taCtors[kind]; + const byteLen = count * Ctor.BYTES_PER_ELEMENT; + const copy = memory.buffer.slice(ptr, ptr + byteLen); + taStack.push(Array.from(new Ctor(copy))); + } + bjs["swift_js_struct_lower_Library_Shelf"] = function(objectId) { + structHelpers.M10TestModuleT7LibraryT5Shelf.lower(swift.memory.getObject(objectId)); + } + bjs["swift_js_struct_lift_Library_Shelf"] = function() { + const value = structHelpers.M10TestModuleT7LibraryT5Shelf.lift(); + return swift.memory.retain(value); + } + bjs["swift_js_struct_lower_Library_Shelf_Divider"] = function(objectId) { + structHelpers.M10TestModuleT7LibraryT5ShelfT7Divider.lower(swift.memory.getObject(objectId)); + } + bjs["swift_js_struct_lift_Library_Shelf_Divider"] = function() { + const value = structHelpers.M10TestModuleT7LibraryT5ShelfT7Divider.lift(); + return swift.memory.retain(value); + } + bjs["bjs_core_register_type_handles"] = function() {}; + bjs["bjs_TestModule_register_type_handles"] = function() {}; + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } + bjs["swift_js_return_optional_bool"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalBool = null; + } else { + tmpRetOptionalBool = value !== 0; + } + } + bjs["swift_js_return_optional_int"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalInt = null; + } else { + tmpRetOptionalInt = value | 0; + } + } + bjs["swift_js_return_optional_float"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalFloat = null; + } else { + tmpRetOptionalFloat = Math.fround(value); + } + } + bjs["swift_js_return_optional_double"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalDouble = null; + } else { + tmpRetOptionalDouble = value; + } + } + bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = decodeString(ptr, len); + } + } + bjs["swift_js_return_optional_object"] = function(isSome, objectId) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = swift.memory.getObject(objectId); + } + } + bjs["swift_js_return_optional_heap_object"] = function(isSome, pointer) { + if (isSome === 0) { + tmpRetOptionalHeapObject = null; + } else { + tmpRetOptionalHeapObject = pointer; + } + } + bjs["swift_js_get_optional_int_presence"] = function() { + return tmpRetOptionalInt != null ? 1 : 0; + } + bjs["swift_js_get_optional_int_value"] = function() { + const value = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; + return value; + } + bjs["swift_js_get_optional_string"] = function() { + const str = tmpRetString; + tmpRetString = undefined; + if (str == null) { + return -1; + } else { + const bytes = textEncoder.encode(str); + tmpRetBytes = bytes; + return bytes.length; + } + } + bjs["swift_js_get_optional_float_presence"] = function() { + return tmpRetOptionalFloat != null ? 1 : 0; + } + bjs["swift_js_get_optional_float_value"] = function() { + const value = tmpRetOptionalFloat; + tmpRetOptionalFloat = undefined; + return value; + } + bjs["swift_js_get_optional_double_presence"] = function() { + return tmpRetOptionalDouble != null ? 1 : 0; + } + bjs["swift_js_get_optional_double_value"] = function() { + const value = tmpRetOptionalDouble; + tmpRetOptionalDouble = undefined; + return value; + } + bjs["swift_js_get_optional_heap_object_pointer"] = function() { + const pointer = tmpRetOptionalHeapObject; + tmpRetOptionalHeapObject = undefined; + return pointer || 0; + } + bjs["swift_js_closure_unregister"] = function(funcRef) {} + // Wrapper functions for module: TestModule + if (!importObject["TestModule"]) { + importObject["TestModule"] = {}; + } + importObject["TestModule"]["bjs_Library_wrap"] = function(pointer) { + const obj = _exports['Library'].__construct(pointer); + return swift.memory.retain(obj); + }; + }, + setInstance: (i) => { + instance = i; + memory = instance.exports.memory; + + decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + + setException = (error) => { + instance.exports._swift_js_exception.value = swift.memory.retain(error) + } + }, + /** @param {WebAssembly.Instance} instance */ + createExports: (instance) => { + const js = swift.memory.heap; + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.identityMap?.delete(state.pointer); + state.deinit(state.pointer); + }); + + /// Represents a Swift heap object like a class instance or an actor instance. + class SwiftHeapObject { + static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; + const makeFresh = (identityMap) => { + const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false, identityMap }; + obj.pointer = pointer; + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); + if (identityMap) { + identityMap.set(pointer, new WeakRef(obj)); + } + return obj; + }; + + if (!identityCache) { + return makeFresh(null); + } + + const cached = identityCache.get(pointer)?.deref(); + if (cached && !cached.__swiftHeapObjectState.hasReleased) { + deinit(pointer); + return cached; + } + if (identityCache.has(pointer)) { + identityCache.delete(pointer); + } + + return makeFresh(identityCache); + } + + release() { + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.identityMap?.delete(state.pointer); + state.deinit(state.pointer); + } + } + class Library extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Library_deinit, Library.prototype, null); + } + + constructor(name) { + const nameBytes = textEncoder.encode(name); + const nameId = swift.memory.retain(nameBytes); + const ret = instance.exports.bjs_Library_init(nameId, nameBytes.length); + return Library.__construct(ret); + } + describe() { + instance.exports.bjs_Library_describe(this.pointer); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + } + rename(title) { + const titleBytes = textEncoder.encode(title); + const titleId = swift.memory.retain(titleBytes); + instance.exports.bjs_Library_rename(this.pointer, titleId, titleBytes.length); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + } + shelf(label) { + const labelBytes = textEncoder.encode(label); + const labelId = swift.memory.retain(labelBytes); + instance.exports.bjs_Library_shelf(this.pointer, labelId, labelBytes.length); + const structValue = structHelpers.M10TestModuleT7LibraryT5Shelf.lift(); + return structValue; + } + get name() { + instance.exports.bjs_Library_name_get(this.pointer); + const ret = tmpRetString; + tmpRetString = undefined; + return ret; + } + set name(value) { + const valueBytes = textEncoder.encode(value); + const valueId = swift.memory.retain(valueBytes); + instance.exports.bjs_Library_name_set(this.pointer, valueId, valueBytes.length); + } + } + const __bjs_helpers_M10TestModuleT7LibraryT5Shelf = __bjs_createStructHelpers_M10TestModuleT7LibraryT5Shelf(); + structHelpers.M10TestModuleT7LibraryT5Shelf = __bjs_helpers_M10TestModuleT7LibraryT5Shelf; + + const __bjs_helpers_M10TestModuleT7LibraryT5ShelfT7Divider = __bjs_createStructHelpers_M10TestModuleT7LibraryT5ShelfT7Divider(); + structHelpers.M10TestModuleT7LibraryT5ShelfT7Divider = __bjs_helpers_M10TestModuleT7LibraryT5ShelfT7Divider; + + const __bjs_helpers_M10TestModuleT7Message = __bjs_createEnumHelpers_M10TestModuleT7Message(); + enumHelpers.M10TestModuleT7Message = __bjs_helpers_M10TestModuleT7Message; + + const exports = { + roundTripMessage: function bjs_roundTripMessage(message) { + const messageCaseId = enumHelpers.M10TestModuleT7Message.lower(message); + instance.exports.bjs_roundTripMessage(messageCaseId); + const ret = enumHelpers.M10TestModuleT7Message.lift(i32Stack.pop()); + return ret; + }, + Message: MessageValues, + Update: UpdateValues, + Library: Object.assign(Library, { + Genre: GenreValues, + Shelf: { + init: function(label) { + const labelBytes = textEncoder.encode(label); + const labelId = swift.memory.retain(labelBytes); + instance.exports.bjs_Library_Shelf_init(labelId, labelBytes.length); + const structValue = structHelpers.M10TestModuleT7LibraryT5Shelf.lift(); + return structValue; + }, + get capacity() { + const ret = instance.exports.bjs_Library_Shelf_static_capacity_get(); + return ret; + }, + Divider: { + init: function(slot) { + instance.exports.bjs_Library_Shelf_Divider_init(slot); + const structValue = structHelpers.M10TestModuleT7LibraryT5ShelfT7Divider.lift(); + return structValue; + }, + }, + }, + }), + }; + _exports = exports; + return exports; + }, + } +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionScopeParity.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionScopeParity.d.ts new file mode 100644 index 000000000..74569a6db --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionScopeParity.d.ts @@ -0,0 +1,52 @@ +// 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`. + +export const SignalValues: { + readonly Ready: "ready"; +}; +export type SignalTag = typeof SignalValues[keyof typeof SignalValues]; + +export interface Meta { + note: string; +} +export type SignalObject = typeof SignalValues; + +/// Represents a Swift heap object like a class instance or an actor instance. +export interface SwiftHeapObject { + /// Release the heap object. + /// + /// Note: Calling this method will release the heap object and it will no longer be accessible. + release(): void; +} +export interface Mallet extends SwiftHeapObject { +} +export interface Hammer extends SwiftHeapObject { +} +export type Exports = { + Signal: SignalObject + Meta: { + init(note: string): Signal.Meta; + }, + app: { + Toolbox: { + Hammer: { + new(): Hammer; + }, + Mallet: { + new(): Mallet; + }, + }, + }, +} +export type Imports = { +} +export function createInstantiator(options: { + imports: Imports; +}, swift: any): Promise<{ + addImports: (importObject: WebAssembly.Imports) => void; + setInstance: (instance: WebAssembly.Instance) => void; + createExports: (instance: WebAssembly.Instance) => Exports; +}>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionScopeParity.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionScopeParity.js new file mode 100644 index 000000000..6b8ae44b1 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionScopeParity.js @@ -0,0 +1,354 @@ +// 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`. + +export const SignalValues = { + Ready: "ready", +}; + +export async function createInstantiator(options, swift) { + let instance; + let memory; + let setException; + let decodeString; + const textDecoder = new TextDecoder("utf-8"); + const textEncoder = new TextEncoder("utf-8"); + let tmpRetString; + let tmpRetBytes; + let tmpRetException; + let tmpRetOptionalBool; + let tmpRetOptionalInt; + let tmpRetOptionalFloat; + let tmpRetOptionalDouble; + let tmpRetOptionalHeapObject; + let strStack = []; + let i32Stack = []; + let i64Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; + let taStack = []; + const enumHelpers = {}; + const structHelpers = {}; + + let _exports = null; + let bjs = null; + const __bjs_createStructHelpers_M10TestModuleT6SignalT4Meta = () => ({ + lower: (value) => { + const bytes = textEncoder.encode(value.note); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + }, + lift: () => { + const string = strStack.pop(); + return { note: string }; + } + }); + + return { + /** + * @param {WebAssembly.Imports} importObject + */ + addImports: (importObject, importsContext) => { + bjs = {}; + importObject["bjs"] = bjs; + bjs["swift_js_return_string"] = function(ptr, len) { + tmpRetString = decodeString(ptr, len); + } + bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { + const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); + bytes.set(source); + } + bjs["swift_js_make_js_string"] = function(ptr, len) { + return swift.memory.retain(decodeString(ptr, len)); + } + bjs["swift_js_init_memory_with_result"] = function(ptr, len) { + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); + target.set(tmpRetBytes); + tmpRetBytes = undefined; + } + bjs["swift_js_throw"] = function(id) { + tmpRetException = swift.memory.retainByRef(id); + } + bjs["swift_js_retain"] = function(id) { + return swift.memory.retainByRef(id); + } + bjs["swift_js_release"] = function(id) { + swift.memory.release(id); + } + bjs["swift_js_push_i32"] = function(v) { + i32Stack.push(v | 0); + } + bjs["swift_js_push_f32"] = function(v) { + f32Stack.push(Math.fround(v)); + } + bjs["swift_js_push_f64"] = function(v) { + f64Stack.push(v); + } + bjs["swift_js_push_string"] = function(ptr, len) { + const value = decodeString(ptr, len); + strStack.push(value); + } + bjs["swift_js_pop_i32"] = function() { + return i32Stack.pop(); + } + bjs["swift_js_pop_f32"] = function() { + return f32Stack.pop(); + } + bjs["swift_js_pop_f64"] = function() { + return f64Stack.pop(); + } + bjs["swift_js_push_pointer"] = function(pointer) { + ptrStack.push(pointer); + } + bjs["swift_js_pop_pointer"] = function() { + return ptrStack.pop(); + } + bjs["swift_js_push_i64"] = function(v) { + i64Stack.push(v); + } + bjs["swift_js_pop_i64"] = function() { + return i64Stack.pop(); + } + const taCtors = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array]; + bjs["swift_js_push_typed_array"] = function(kind, ptr, count) { + const Ctor = taCtors[kind]; + const byteLen = count * Ctor.BYTES_PER_ELEMENT; + const copy = memory.buffer.slice(ptr, ptr + byteLen); + taStack.push(Array.from(new Ctor(copy))); + } + bjs["swift_js_struct_lower_Meta"] = function(objectId) { + structHelpers.M10TestModuleT6SignalT4Meta.lower(swift.memory.getObject(objectId)); + } + bjs["swift_js_struct_lift_Meta"] = function() { + const value = structHelpers.M10TestModuleT6SignalT4Meta.lift(); + return swift.memory.retain(value); + } + bjs["bjs_core_register_type_handles"] = function() {}; + bjs["bjs_TestModule_register_type_handles"] = function() {}; + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } + bjs["swift_js_return_optional_bool"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalBool = null; + } else { + tmpRetOptionalBool = value !== 0; + } + } + bjs["swift_js_return_optional_int"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalInt = null; + } else { + tmpRetOptionalInt = value | 0; + } + } + bjs["swift_js_return_optional_float"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalFloat = null; + } else { + tmpRetOptionalFloat = Math.fround(value); + } + } + bjs["swift_js_return_optional_double"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalDouble = null; + } else { + tmpRetOptionalDouble = value; + } + } + bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = decodeString(ptr, len); + } + } + bjs["swift_js_return_optional_object"] = function(isSome, objectId) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = swift.memory.getObject(objectId); + } + } + bjs["swift_js_return_optional_heap_object"] = function(isSome, pointer) { + if (isSome === 0) { + tmpRetOptionalHeapObject = null; + } else { + tmpRetOptionalHeapObject = pointer; + } + } + bjs["swift_js_get_optional_int_presence"] = function() { + return tmpRetOptionalInt != null ? 1 : 0; + } + bjs["swift_js_get_optional_int_value"] = function() { + const value = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; + return value; + } + bjs["swift_js_get_optional_string"] = function() { + const str = tmpRetString; + tmpRetString = undefined; + if (str == null) { + return -1; + } else { + const bytes = textEncoder.encode(str); + tmpRetBytes = bytes; + return bytes.length; + } + } + bjs["swift_js_get_optional_float_presence"] = function() { + return tmpRetOptionalFloat != null ? 1 : 0; + } + bjs["swift_js_get_optional_float_value"] = function() { + const value = tmpRetOptionalFloat; + tmpRetOptionalFloat = undefined; + return value; + } + bjs["swift_js_get_optional_double_presence"] = function() { + return tmpRetOptionalDouble != null ? 1 : 0; + } + bjs["swift_js_get_optional_double_value"] = function() { + const value = tmpRetOptionalDouble; + tmpRetOptionalDouble = undefined; + return value; + } + bjs["swift_js_get_optional_heap_object_pointer"] = function() { + const pointer = tmpRetOptionalHeapObject; + tmpRetOptionalHeapObject = undefined; + return pointer || 0; + } + bjs["swift_js_closure_unregister"] = function(funcRef) {} + // Wrapper functions for module: TestModule + if (!importObject["TestModule"]) { + importObject["TestModule"] = {}; + } + importObject["TestModule"]["bjs_app_Toolbox_Hammer_wrap"] = function(pointer) { + const obj = _exports.app.Toolbox.Hammer.__construct(pointer); + return swift.memory.retain(obj); + }; + importObject["TestModule"]["bjs_app_Toolbox_Mallet_wrap"] = function(pointer) { + const obj = _exports.app.Toolbox.Mallet.__construct(pointer); + return swift.memory.retain(obj); + }; + }, + setInstance: (i) => { + instance = i; + memory = instance.exports.memory; + + decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + + setException = (error) => { + instance.exports._swift_js_exception.value = swift.memory.retain(error) + } + }, + /** @param {WebAssembly.Instance} instance */ + createExports: (instance) => { + const js = swift.memory.heap; + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.identityMap?.delete(state.pointer); + state.deinit(state.pointer); + }); + + /// Represents a Swift heap object like a class instance or an actor instance. + class SwiftHeapObject { + static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; + const makeFresh = (identityMap) => { + const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false, identityMap }; + obj.pointer = pointer; + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); + if (identityMap) { + identityMap.set(pointer, new WeakRef(obj)); + } + return obj; + }; + + if (!identityCache) { + return makeFresh(null); + } + + const cached = identityCache.get(pointer)?.deref(); + if (cached && !cached.__swiftHeapObjectState.hasReleased) { + deinit(pointer); + return cached; + } + if (identityCache.has(pointer)) { + identityCache.delete(pointer); + } + + return makeFresh(identityCache); + } + + release() { + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.identityMap?.delete(state.pointer); + state.deinit(state.pointer); + } + } + class Mallet extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_app_Toolbox_Mallet_deinit, Mallet.prototype, null); + } + + constructor() { + const ret = instance.exports.bjs_app_Toolbox_Mallet_init(); + return Mallet.__construct(ret); + } + } + class Hammer extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_app_Toolbox_Hammer_deinit, Hammer.prototype, null); + } + + constructor() { + const ret = instance.exports.bjs_app_Toolbox_Hammer_init(); + return Hammer.__construct(ret); + } + } + const __bjs_helpers_M10TestModuleT6SignalT4Meta = __bjs_createStructHelpers_M10TestModuleT6SignalT4Meta(); + structHelpers.M10TestModuleT6SignalT4Meta = __bjs_helpers_M10TestModuleT6SignalT4Meta; + + const exports = { + Signal: SignalValues, + Meta: { + init: function(note) { + const noteBytes = textEncoder.encode(note); + const noteId = swift.memory.retain(noteBytes); + instance.exports.bjs_Meta_init(noteId, noteBytes.length); + const structValue = structHelpers.M10TestModuleT6SignalT4Meta.lift(); + return structValue; + }, + }, + app: { + Toolbox: { + Hammer, + Mallet, + }, + }, + }; + _exports = exports; + return exports; + }, + } +} \ No newline at end of file diff --git a/Tests/BridgeJSRuntimeTests/CrossFileNestedTypeClassAPIs.swift b/Tests/BridgeJSRuntimeTests/CrossFileNestedTypeClassAPIs.swift new file mode 100644 index 000000000..8663f1fe5 --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/CrossFileNestedTypeClassAPIs.swift @@ -0,0 +1,13 @@ +import JavaScriptKit + +@JS class Workspace { + let name: String + + @JS init(name: String) { + self.name = name + } + + @JS func describe() -> String { + name + } +} diff --git a/Tests/BridgeJSRuntimeTests/CrossFileNestedTypeExtensionAPIs.swift b/Tests/BridgeJSRuntimeTests/CrossFileNestedTypeExtensionAPIs.swift new file mode 100644 index 000000000..c50446ee2 --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/CrossFileNestedTypeExtensionAPIs.swift @@ -0,0 +1,8 @@ +import JavaScriptKit + +extension Workspace { + @JS enum Kind: String { + case personal + case shared + } +} diff --git a/Tests/BridgeJSRuntimeTests/ExtensionNestedTypesAPIs.swift b/Tests/BridgeJSRuntimeTests/ExtensionNestedTypesAPIs.swift new file mode 100644 index 000000000..b09807ac7 --- /dev/null +++ b/Tests/BridgeJSRuntimeTests/ExtensionNestedTypesAPIs.swift @@ -0,0 +1,70 @@ +import JavaScriptKit + +@JS class Library { + @JS var name: String + + @JS init(name: String) { + self.name = name + } + + @JS func describe() -> String { + name + } +} + +extension Library { + typealias Title = String + + @JS enum Genre: String { + case fiction + case reference + } + + @JS struct Shelf { + var label: String + + @JS init(label: String) { + self.label = label + } + + @JS static var capacity: Int { 32 } + } + + @JS func rename(_ title: Title) -> Title { + title + } + + @JS func shelf(label: String) -> Shelf { + Shelf(label: label) + } +} + +extension Library.Shelf { + @JS struct Divider { + var slot: Int + + @JS init(slot: Int) { + self.slot = slot + } + } + + @JS func describeShelf() -> String { + "Shelf: " + label + } +} + +@JS enum Message { + case update(Update) + case delete +} + +extension Message { + @JS enum Update { + case flip + case rotate + } +} + +@JS func roundTripMessage(_ message: Message) -> Message { + message +} diff --git a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift index e453e3534..f16bce9f2 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift +++ b/Tests/BridgeJSRuntimeTests/Generated/BridgeJS.swift @@ -4878,6 +4878,9 @@ extension AsyncImportedPayloadResult: _BridgedSwiftAssociatedValueEnum { } } +extension Workspace.Kind: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +} + @_expose(wasm, "bjs_DefaultArgumentExports_static_testStringDefault") @_cdecl("bjs_DefaultArgumentExports_static_testStringDefault") public func _bjs_DefaultArgumentExports_static_testStringDefault(_ messageBytes: Int32, _ messageLength: Int32) -> Void { @@ -5924,6 +5927,67 @@ public func _bjs_NestedStructGroupB_static_roundtripMetadata() -> Void { extension NestedTypeHost.Variant: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { } +extension Message: _BridgedSwiftAssociatedValueEnum { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPopPayload(_ caseId: Int32) -> Message { + switch caseId { + case 0: + return .update(Message.Update.bridgeJSStackPop()) + case 1: + return .delete + default: + fatalError("Unknown Message case ID: \(caseId)") + } + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPushPayload() -> Int32 { + switch self { + case .update(let param0): + param0.bridgeJSStackPush() + return Int32(0) + case .delete: + return Int32(1) + } + } +} + +extension Library.Genre: _BridgedSwiftEnumNoPayload, _BridgedSwiftRawValueEnum { +} + +extension Message.Update: _BridgedSwiftCaseEnum { + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { + return bridgeJSRawValue + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftReturn(_ value: Int32) -> Message.Update { + return bridgeJSLiftParameter(value) + } + @_spi(BridgeJS) @_transparent public static func bridgeJSLiftParameter(_ value: Int32) -> Message.Update { + return Message.Update(bridgeJSRawValue: value)! + } + @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerReturn() -> Int32 { + return bridgeJSLowerParameter() + } + + @_spi(BridgeJS) @usableFromInline init?(bridgeJSRawValue: Int32) { + switch bridgeJSRawValue { + case 0: + self = .flip + case 1: + self = .rotate + default: + return nil + } + } + + @_spi(BridgeJS) @usableFromInline var bridgeJSRawValue: Int32 { + switch self { + case .flip: + return 0 + case .rotate: + return 1 + } + } +} + extension LightColor: _BridgedSwiftCaseEnum { @_spi(BridgeJS) @_transparent public consuming func bridgeJSLowerParameter() -> Int32 { return bridgeJSRawValue @@ -6848,6 +6912,142 @@ public func _bjs_NestedTypeHost_Label_static_untitled() -> Void { #endif } +extension Library.Shelf: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Library.Shelf { + let label = String.bridgeJSStackPop() + return Library.Shelf(label: label) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.label.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_Library_Shelf(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Library_Shelf())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Library_Shelf") +fileprivate func _bjs_struct_lower_Library_Shelf_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_Library_Shelf_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_Library_Shelf(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Library_Shelf_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Library_Shelf") +fileprivate func _bjs_struct_lift_Library_Shelf_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_Library_Shelf_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_Library_Shelf() -> Int32 { + return _bjs_struct_lift_Library_Shelf_extern() +} + +@_expose(wasm, "bjs_Library_Shelf_init") +@_cdecl("bjs_Library_Shelf_init") +public func _bjs_Library_Shelf_init(_ labelBytes: Int32, _ labelLength: Int32) -> Void { + #if arch(wasm32) + let ret = Library.Shelf(label: String.bridgeJSLiftParameter(labelBytes, labelLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Library_Shelf_static_capacity_get") +@_cdecl("bjs_Library_Shelf_static_capacity_get") +public func _bjs_Library_Shelf_static_capacity_get() -> Int32 { + #if arch(wasm32) + let ret = Library.Shelf.capacity + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Library_Shelf_describeShelf") +@_cdecl("bjs_Library_Shelf_describeShelf") +public func _bjs_Library_Shelf_describeShelf() -> Void { + #if arch(wasm32) + let ret = Library.Shelf.bridgeJSLiftParameter().describeShelf() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension Library.Shelf.Divider: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Library.Shelf.Divider { + let slot = Int.bridgeJSStackPop() + return Library.Shelf.Divider(slot: slot) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.slot.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_Library_Shelf_Divider(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Library_Shelf_Divider())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Library_Shelf_Divider") +fileprivate func _bjs_struct_lower_Library_Shelf_Divider_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_Library_Shelf_Divider_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_Library_Shelf_Divider(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Library_Shelf_Divider_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Library_Shelf_Divider") +fileprivate func _bjs_struct_lift_Library_Shelf_Divider_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_Library_Shelf_Divider_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_Library_Shelf_Divider() -> Int32 { + return _bjs_struct_lift_Library_Shelf_Divider_extern() +} + +@_expose(wasm, "bjs_Library_Shelf_Divider_init") +@_cdecl("bjs_Library_Shelf_Divider_init") +public func _bjs_Library_Shelf_Divider_init(_ slot: Int32) -> Void { + #if arch(wasm32) + let ret = Library.Shelf.Divider(slot: Int.bridgeJSLiftParameter(slot)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + extension GenericRTPoint: _BridgedSwiftStruct { @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> GenericRTPoint { let y = Int.bridgeJSStackPop() @@ -9990,6 +10190,17 @@ public func _bjs_makeAdder(_ base: Int32) -> Int32 { #endif } +@_expose(wasm, "bjs_roundTripMessage") +@_cdecl("bjs_roundTripMessage") +public func _bjs_roundTripMessage(_ message: Int32) -> Void { + #if arch(wasm32) + let ret = roundTripMessage(_: Message.bridgeJSLiftParameter(message)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_renamedEcho") @_cdecl("bjs_renamedEcho") public func _bjs_renamedEcho(_ valueBytes: Int32, _ valueLength: Int32) -> Void { @@ -10759,6 +10970,59 @@ fileprivate func _bjs_ClosureSupportExports_wrap_extern(_ pointer: UnsafeMutable return _bjs_ClosureSupportExports_wrap_extern(pointer) } +@_expose(wasm, "bjs_Workspace_init") +@_cdecl("bjs_Workspace_init") +public func _bjs_Workspace_init(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = Workspace(name: String.bridgeJSLiftParameter(nameBytes, nameLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Workspace_describe") +@_cdecl("bjs_Workspace_describe") +public func _bjs_Workspace_describe(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = Workspace.bridgeJSLiftParameter(_self).describe() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Workspace_deinit") +@_cdecl("bjs_Workspace_deinit") +public func _bjs_Workspace_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension Workspace: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_Workspace_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_Workspace_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Workspace_wrap") +fileprivate func _bjs_Workspace_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_Workspace_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_Workspace_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Workspace_wrap_extern(pointer) +} + @_expose(wasm, "bjs_DefaultArgumentConstructorDefaults_init") @_cdecl("bjs_DefaultArgumentConstructorDefaults_init") public func _bjs_DefaultArgumentConstructorDefaults_init(_ nameBytes: Int32, _ nameLength: Int32, _ count: Int32, _ enabled: Int32, _ status: Int32, _ tagIsSome: Int32, _ tagBytes: Int32, _ tagLength: Int32) -> UnsafeMutableRawPointer { @@ -13371,6 +13635,102 @@ fileprivate func _bjs_NestedTypeHost_wrap_extern(_ pointer: UnsafeMutableRawPoin return _bjs_NestedTypeHost_wrap_extern(pointer) } +@_expose(wasm, "bjs_Library_init") +@_cdecl("bjs_Library_init") +public func _bjs_Library_init(_ nameBytes: Int32, _ nameLength: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = Library(name: String.bridgeJSLiftParameter(nameBytes, nameLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Library_describe") +@_cdecl("bjs_Library_describe") +public func _bjs_Library_describe(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = Library.bridgeJSLiftParameter(_self).describe() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Library_rename") +@_cdecl("bjs_Library_rename") +public func _bjs_Library_rename(_ _self: UnsafeMutableRawPointer, _ titleBytes: Int32, _ titleLength: Int32) -> Void { + #if arch(wasm32) + let ret = Library.bridgeJSLiftParameter(_self).rename(_: String.bridgeJSLiftParameter(titleBytes, titleLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Library_shelf") +@_cdecl("bjs_Library_shelf") +public func _bjs_Library_shelf(_ _self: UnsafeMutableRawPointer, _ labelBytes: Int32, _ labelLength: Int32) -> Void { + #if arch(wasm32) + let ret = Library.bridgeJSLiftParameter(_self).shelf(label: String.bridgeJSLiftParameter(labelBytes, labelLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Library_name_get") +@_cdecl("bjs_Library_name_get") +public func _bjs_Library_name_get(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = Library.bridgeJSLiftParameter(_self).name + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Library_name_set") +@_cdecl("bjs_Library_name_set") +public func _bjs_Library_name_set(_ _self: UnsafeMutableRawPointer, _ valueBytes: Int32, _ valueLength: Int32) -> Void { + #if arch(wasm32) + Library.bridgeJSLiftParameter(_self).name = String.bridgeJSLiftParameter(valueBytes, valueLength) + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Library_deinit") +@_cdecl("bjs_Library_deinit") +public func _bjs_Library_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension Library: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_Library_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_Library_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "BridgeJSRuntimeTests", name: "bjs_Library_wrap") +fileprivate func _bjs_Library_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_Library_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_Library_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Library_wrap_extern(pointer) +} + @_expose(wasm, "bjs_ImportGenericBox_init") @_cdecl("bjs_ImportGenericBox_init") public func _bjs_ImportGenericBox_init(_ value: Int32) -> UnsafeMutableRawPointer { @@ -13863,6 +14223,14 @@ extension NestedTypeHost.Label: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = NestedTypeHost.Label.bridgeJSMakeTypeHandle() } +extension Library.Shelf: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Library.Shelf.bridgeJSMakeTypeHandle() +} + +extension Library.Shelf.Divider: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Library.Shelf.Divider.bridgeJSMakeTypeHandle() +} + extension GenericRTPoint: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = GenericRTPoint.bridgeJSMakeTypeHandle() } @@ -13987,6 +14355,10 @@ extension AsyncImportedPayloadResult: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = AsyncImportedPayloadResult.bridgeJSMakeTypeHandle() } +extension Workspace.Kind: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Workspace.Kind.bridgeJSMakeTypeHandle() +} + extension Direction: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = Direction.bridgeJSMakeTypeHandle() } @@ -14083,6 +14455,18 @@ extension NestedTypeHost.Variant: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = NestedTypeHost.Variant.bridgeJSMakeTypeHandle() } +extension Message: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Message.bridgeJSMakeTypeHandle() +} + +extension Library.Genre: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Library.Genre.bridgeJSMakeTypeHandle() +} + +extension Message.Update: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Message.Update.bridgeJSMakeTypeHandle() +} + extension LightColor: BridgedSwiftGenericBridgeable { @_spi(BridgeJS) public static let bridgeJSTypeHandle = LightColor.bridgeJSMakeTypeHandle() } @@ -19051,6 +19435,8 @@ public func _bjs_BridgeJSRuntimeTests_register_type_handles() { NestedStructGroupA.Metadata.bridgeJSTypeID, NestedStructGroupB.Metadata.bridgeJSTypeID, NestedTypeHost.Label.bridgeJSTypeID, + Library.Shelf.bridgeJSTypeID, + Library.Shelf.Divider.bridgeJSTypeID, GenericRTPoint.bridgeJSTypeID, GenericRTNamespace.Metadata.bridgeJSTypeID, Point.bridgeJSTypeID, @@ -19082,6 +19468,7 @@ public func _bjs_BridgeJSRuntimeTests_register_type_handles() { Shape.bridgeJSTypeID, InnerTag.bridgeJSTypeID, AsyncImportedPayloadResult.bridgeJSTypeID, + Workspace.Kind.bridgeJSTypeID, Direction.bridgeJSTypeID, Status.bridgeJSTypeID, Theme.bridgeJSTypeID, @@ -19106,6 +19493,9 @@ public func _bjs_BridgeJSRuntimeTests_register_type_handles() { StaticCalculator.bridgeJSTypeID, StaticPropertyEnum.bridgeJSTypeID, NestedTypeHost.Variant.bridgeJSTypeID, + Message.bridgeJSTypeID, + Library.Genre.bridgeJSTypeID, + Message.Update.bridgeJSTypeID, LightColor.bridgeJSTypeID, ImportedPayloadSignal.bridgeJSTypeID, GenericRTColor.bridgeJSTypeID, diff --git a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json index 8622b1cc9..c1a3e26cc 100644 --- a/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json +++ b/Tests/BridgeJSRuntimeTests/Generated/JavaScript/BridgeJS.json @@ -831,6 +831,51 @@ ], "swiftCallName" : "ClosureSupportExports" }, + { + "constructor" : { + "abiName" : "bjs_Workspace_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "name", + "name" : "name", + "type" : { + "string" : { + + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_Workspace_describe", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "describe", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "name" : "Workspace", + "properties" : [ + + ], + "swiftCallName" : "Workspace" + }, { "constructor" : { "abiName" : "bjs_DefaultArgumentConstructorDefaults_init", @@ -4844,6 +4889,110 @@ ], "swiftCallName" : "NestedTypeHost" }, + { + "constructor" : { + "abiName" : "bjs_Library_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "name", + "name" : "name", + "type" : { + "string" : { + + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_Library_describe", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "describe", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_Library_rename", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "rename", + "parameters" : [ + { + "label" : "_", + "name" : "title", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "string" : { + + } + } + }, + { + "abiName" : "bjs_Library_shelf", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "shelf", + "parameters" : [ + { + "label" : "label", + "name" : "label", + "type" : { + "string" : { + + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "Library.Shelf" + } + } + } + ], + "name" : "Library", + "properties" : [ + { + "isReadonly" : false, + "isStatic" : false, + "name" : "name", + "type" : { + "string" : { + + } + } + } + ], + "swiftCallName" : "Library" + }, { "constructor" : { "abiName" : "bjs_ImportGenericBox_init", @@ -7508,6 +7657,36 @@ "swiftCallName" : "AsyncImportedPayloadResult", "tsFullPath" : "AsyncImportedPayloadResult" }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "personal" + }, + { + "associatedValues" : [ + + ], + "name" : "shared" + } + ], + "emitStyle" : "const", + "name" : "Kind", + "namespace" : [ + "Workspace" + ], + "rawType" : "String", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Workspace.Kind", + "tsFullPath" : "Workspace.Kind" + }, { "cases" : [ @@ -10329,6 +10508,94 @@ "swiftCallName" : "NestedTypeHost.Variant", "tsFullPath" : "NestedTypeHost.Variant" }, + { + "cases" : [ + { + "associatedValues" : [ + { + "type" : { + "caseEnum" : { + "_0" : "Message.Update" + } + } + } + ], + "name" : "update" + }, + { + "associatedValues" : [ + + ], + "name" : "delete" + } + ], + "emitStyle" : "const", + "name" : "Message", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Message", + "tsFullPath" : "Message" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "fiction" + }, + { + "associatedValues" : [ + + ], + "name" : "reference" + } + ], + "emitStyle" : "const", + "name" : "Genre", + "namespace" : [ + "Library" + ], + "rawType" : "String", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Library.Genre", + "tsFullPath" : "Library.Genre" + }, + { + "cases" : [ + { + "associatedValues" : [ + + ], + "name" : "flip" + }, + { + "associatedValues" : [ + + ], + "name" : "rotate" + } + ], + "emitStyle" : "const", + "name" : "Update", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Message.Update", + "tsFullPath" : "Update" + }, { "cases" : [ { @@ -17145,6 +17412,31 @@ } } }, + { + "abiName" : "bjs_roundTripMessage", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "roundTripMessage", + "parameters" : [ + { + "label" : "_", + "name" : "message", + "type" : { + "associatedValueEnum" : { + "_0" : "Message" + } + } + } + ], + "returnType" : { + "associatedValueEnum" : { + "_0" : "Message" + } + } + }, { "abiName" : "bjs_renamedEcho", "effects" : { @@ -18679,6 +18971,136 @@ ], "swiftCallName" : "NestedTypeHost.Label" }, + { + "constructor" : { + "abiName" : "bjs_Library_Shelf_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "label", + "name" : "label", + "type" : { + "string" : { + + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_Library_Shelf_describeShelf", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "describeShelf", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "name" : "Shelf", + "namespace" : [ + "Library" + ], + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "label", + "namespace" : [ + "Library" + ], + "type" : { + "string" : { + + } + } + }, + { + "isReadonly" : true, + "isStatic" : true, + "name" : "capacity", + "staticContext" : { + "structName" : { + "_0" : "Library_Shelf" + } + }, + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "swiftCallName" : "Library.Shelf" + }, + { + "constructor" : { + "abiName" : "bjs_Library_Shelf_Divider_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "slot", + "name" : "slot", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ] + }, + "methods" : [ + + ], + "name" : "Divider", + "namespace" : [ + "Library", + "Shelf" + ], + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "slot", + "namespace" : [ + "Library", + "Shelf" + ], + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "swiftCallName" : "Library.Shelf.Divider" + }, { "methods" : [ diff --git a/Tests/prelude.mjs b/Tests/prelude.mjs index b7e21e821..78271e1ba 100644 --- a/Tests/prelude.mjs +++ b/Tests/prelude.mjs @@ -743,6 +743,29 @@ function BridgeJSRuntimeTests_runJsWorks(instance, exports) { assert.equal(exports.NestedTypeHost.Label.untitled().text, "untitled"); nestedHost.release(); + const library = new exports.Library("Central"); + assert.equal(library.describe(), "Central"); + assert.equal(library.rename("Annex"), "Annex"); + assert.equal(exports.Library.Genre.Fiction, "fiction"); + assert.equal(exports.Library.Genre.Reference, "reference"); + const shelf = exports.Library.Shelf.init("History"); + assert.equal(shelf.label, "History"); + assert.equal(exports.Library.Shelf.capacity, 32); + assert.equal(library.shelf("Science").label, "Science"); + assert.equal(shelf.describeShelf(), "Shelf: History"); + assert.equal(exports.Library.Shelf.Divider.init(5).slot, 5); + const updateMessage = { tag: exports.Message.Tag.Update, param0: exports.Update.Flip }; + assert.deepEqual(exports.roundTripMessage(updateMessage), updateMessage); + const deleteMessage = { tag: exports.Message.Tag.Delete }; + assert.deepEqual(exports.roundTripMessage(deleteMessage), deleteMessage); + library.release(); + + const workspace = new exports.Workspace("Docs"); + assert.equal(workspace.describe(), "Docs"); + assert.equal(exports.Workspace.Kind.Personal, "personal"); + assert.equal(exports.Workspace.Kind.Shared, "shared"); + workspace.release(); + const s1 = { tag: exports.APIResult.Tag.Success, param0: "Cześć 🙋‍♂️" }; const f1 = { tag: exports.APIResult.Tag.Failure, param0: 42 }; const i1 = { tag: APIResultValues.Tag.Info }; From 0b453a5c895658213e83e3621c313020307b08fb Mon Sep 17 00:00:00 2001 From: William Taylor Date: Fri, 14 Aug 2026 16:44:43 +1000 Subject: [PATCH 46/50] BridgeJS: Fix nested type references in generated TS --- .../Sources/BridgeJSLink/BridgeJSLink.swift | 36 ++- .../BridgeJSSkeleton/BridgeJSSkeleton.swift | 8 + .../MacroSwift/NamespacedClassSignature.swift | 9 + .../NamespacedClassSignature.json | 80 +++++ .../NamespacedClassSignature.swift | 52 +++ .../ExtensionScopeParity.d.ts | 2 +- .../NamespacedClassSignature.d.ts | 32 ++ .../NamespacedClassSignature.js | 304 ++++++++++++++++++ 8 files changed, 511 insertions(+), 12 deletions(-) create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/NamespacedClassSignature.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NamespacedClassSignature.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NamespacedClassSignature.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NamespacedClassSignature.d.ts create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NamespacedClassSignature.js diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index 8b46af1b4..b796c35e7 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -1704,6 +1704,24 @@ public struct BridgeJSLink { } } return type.tsType + case .swiftStruct(let name): + for skeleton in exportedSkeletons { + for structDef in skeleton.structs { + if structDef.name == name || structDef.swiftCallName == name { + return structDef.tsFullPath + } + } + } + return type.tsType + case .swiftHeapObject(let name): + for skeleton in exportedSkeletons { + for klass in skeleton.classes { + if klass.name == name || klass.swiftCallName == name { + return klass.name + } + } + } + return type.tsType case .alias(_, let underlying): return resolveTypeScriptType(underlying, exportedSkeletons: exportedSkeletons) case .nullable(let wrapped, let kind): @@ -2903,7 +2921,7 @@ extension BridgeJSLink { let namespaceEnumPaths = skeleton.enums .filter { $0.enumType == .namespace } .filter { !$0.staticProperties.isEmpty || !$0.staticMethods.isEmpty } - .map { ($0.namespace ?? []) + [$0.name] } + .map(\.tsPathComponents) return itemNamespaces + namespaceEnumPaths } @@ -2961,15 +2979,13 @@ extension BridgeJSLink { } for enumDef in skeleton.enums where enumDef.enumType == .namespace { for function in enumDef.staticMethods { - let fullNamespace = (enumDef.namespace ?? []) + [enumDef.name] - let namespacePath = fullNamespace.joined(separator: ".") + let namespacePath = enumDef.tsFullPath printer.write( "globalThis.\(namespacePath).\(function.resolvedJSName) = exports.\(namespacePath).\(function.resolvedJSName);" ) } for property in enumDef.staticProperties { - let fullNamespace = (enumDef.namespace ?? []) + [enumDef.name] - let namespacePath = fullNamespace.joined(separator: ".") + let namespacePath = enumDef.tsFullPath let exportsPath = "exports.\(namespacePath)" printer.write( @@ -3082,7 +3098,7 @@ extension BridgeJSLink { for klass in skeleton.classes { var currentNode = rootNode - for part in (klass.namespace ?? []) + [klass.name] { + for part in klass.tsPathComponents { currentNode = currentNode.addChild(part) } currentNode.content.declaration = .classType(klass) @@ -3090,7 +3106,7 @@ extension BridgeJSLink { for structDef in skeleton.structs { var currentNode = rootNode - for part in (structDef.namespace ?? []) + [structDef.name] { + for part in structDef.tsPathComponents { currentNode = currentNode.addChild(part) } currentNode.content.declaration = .structType(structDef) @@ -3106,17 +3122,15 @@ extension BridgeJSLink { for enumDef in skeleton.enums where enumDef.enumType == .namespace { for property in enumDef.staticProperties { - let fullNamespace = (enumDef.namespace ?? []) + [enumDef.name] var currentNode = rootNode - for part in fullNamespace { + for part in enumDef.tsPathComponents { currentNode = currentNode.addChild(part) } currentNode.content.staticProperties.append(property) } for function in enumDef.staticMethods { - let fullNamespace = (enumDef.namespace ?? []) + [enumDef.name] var currentNode = rootNode - for part in fullNamespace { + for part in enumDef.tsPathComponents { currentNode = currentNode.addChild(part) } currentNode.content.functions.append(function) diff --git a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift index ed7dee420..79d6b4b07 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift @@ -14,6 +14,14 @@ extension NamespacedExportedType { } return name } + + public var tsPathComponents: [String] { + (namespace ?? []) + [name] + } + + public var tsFullPath: String { + tsPathComponents.joined(separator: ".") + } } // MARK: - ABI Name Generation diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/NamespacedClassSignature.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/NamespacedClassSignature.swift new file mode 100644 index 000000000..4e684ac11 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/NamespacedClassSignature.swift @@ -0,0 +1,9 @@ +@JS enum Workshop { + @JS class Bench { + @JS init() {} + } +} + +@JS func makeBench() -> Workshop.Bench { + Workshop.Bench() +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NamespacedClassSignature.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NamespacedClassSignature.json new file mode 100644 index 000000000..a6aaddafe --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NamespacedClassSignature.json @@ -0,0 +1,80 @@ +{ + "exported" : { + "aliases" : [ + + ], + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_Workshop_Bench_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + + ], + "name" : "Bench", + "namespace" : [ + "Workshop" + ], + "properties" : [ + + ], + "swiftCallName" : "Workshop.Bench" + } + ], + "enums" : [ + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "Workshop", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Workshop", + "tsFullPath" : "Workshop" + } + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_makeBench", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "makeBench", + "parameters" : [ + + ], + "returnType" : { + "swiftHeapObject" : { + "_0" : "Workshop.Bench" + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + + ] + }, + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NamespacedClassSignature.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NamespacedClassSignature.swift new file mode 100644 index 000000000..0bb5652f1 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NamespacedClassSignature.swift @@ -0,0 +1,52 @@ +@_expose(wasm, "bjs_makeBench") +@_cdecl("bjs_makeBench") +public func _bjs_makeBench() -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = makeBench() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Workshop_Bench_init") +@_cdecl("bjs_Workshop_Bench_init") +public func _bjs_Workshop_Bench_init() -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = Workshop.Bench() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Workshop_Bench_deinit") +@_cdecl("bjs_Workshop_Bench_deinit") +public func _bjs_Workshop_Bench_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension Workshop.Bench: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_Workshop_Bench_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_Workshop_Bench_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_Workshop_Bench_wrap") +fileprivate func _bjs_Workshop_Bench_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_Workshop_Bench_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_Workshop_Bench_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Workshop_Bench_wrap_extern(pointer) +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionScopeParity.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionScopeParity.d.ts index 74569a6db..9097d0270 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionScopeParity.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionScopeParity.d.ts @@ -28,7 +28,7 @@ export interface Hammer extends SwiftHeapObject { export type Exports = { Signal: SignalObject Meta: { - init(note: string): Signal.Meta; + init(note: string): Meta; }, app: { Toolbox: { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NamespacedClassSignature.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NamespacedClassSignature.d.ts new file mode 100644 index 000000000..35e010247 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NamespacedClassSignature.d.ts @@ -0,0 +1,32 @@ +// 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`. + +/// Represents a Swift heap object like a class instance or an actor instance. +export interface SwiftHeapObject { + /// Release the heap object. + /// + /// Note: Calling this method will release the heap object and it will no longer be accessible. + release(): void; +} +export interface Bench extends SwiftHeapObject { +} +export type Exports = { + makeBench(): Bench; + Workshop: { + Bench: { + new(): Bench; + }, + }, +} +export type Imports = { +} +export function createInstantiator(options: { + imports: Imports; +}, swift: any): Promise<{ + addImports: (importObject: WebAssembly.Imports) => void; + setInstance: (instance: WebAssembly.Instance) => void; + createExports: (instance: WebAssembly.Instance) => Exports; +}>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NamespacedClassSignature.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NamespacedClassSignature.js new file mode 100644 index 000000000..33ca4c706 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NamespacedClassSignature.js @@ -0,0 +1,304 @@ +// 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`. + +export async function createInstantiator(options, swift) { + let instance; + let memory; + let setException; + let decodeString; + const textDecoder = new TextDecoder("utf-8"); + const textEncoder = new TextEncoder("utf-8"); + let tmpRetString; + let tmpRetBytes; + let tmpRetException; + let tmpRetOptionalBool; + let tmpRetOptionalInt; + let tmpRetOptionalFloat; + let tmpRetOptionalDouble; + let tmpRetOptionalHeapObject; + let strStack = []; + let i32Stack = []; + let i64Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; + let taStack = []; + const enumHelpers = {}; + const structHelpers = {}; + + let _exports = null; + let bjs = null; + + return { + /** + * @param {WebAssembly.Imports} importObject + */ + addImports: (importObject, importsContext) => { + bjs = {}; + importObject["bjs"] = bjs; + bjs["swift_js_return_string"] = function(ptr, len) { + tmpRetString = decodeString(ptr, len); + } + bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { + const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); + bytes.set(source); + } + bjs["swift_js_make_js_string"] = function(ptr, len) { + return swift.memory.retain(decodeString(ptr, len)); + } + bjs["swift_js_init_memory_with_result"] = function(ptr, len) { + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); + target.set(tmpRetBytes); + tmpRetBytes = undefined; + } + bjs["swift_js_throw"] = function(id) { + tmpRetException = swift.memory.retainByRef(id); + } + bjs["swift_js_retain"] = function(id) { + return swift.memory.retainByRef(id); + } + bjs["swift_js_release"] = function(id) { + swift.memory.release(id); + } + bjs["swift_js_push_i32"] = function(v) { + i32Stack.push(v | 0); + } + bjs["swift_js_push_f32"] = function(v) { + f32Stack.push(Math.fround(v)); + } + bjs["swift_js_push_f64"] = function(v) { + f64Stack.push(v); + } + bjs["swift_js_push_string"] = function(ptr, len) { + const value = decodeString(ptr, len); + strStack.push(value); + } + bjs["swift_js_pop_i32"] = function() { + return i32Stack.pop(); + } + bjs["swift_js_pop_f32"] = function() { + return f32Stack.pop(); + } + bjs["swift_js_pop_f64"] = function() { + return f64Stack.pop(); + } + bjs["swift_js_push_pointer"] = function(pointer) { + ptrStack.push(pointer); + } + bjs["swift_js_pop_pointer"] = function() { + return ptrStack.pop(); + } + bjs["swift_js_push_i64"] = function(v) { + i64Stack.push(v); + } + bjs["swift_js_pop_i64"] = function() { + return i64Stack.pop(); + } + const taCtors = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array]; + bjs["swift_js_push_typed_array"] = function(kind, ptr, count) { + const Ctor = taCtors[kind]; + const byteLen = count * Ctor.BYTES_PER_ELEMENT; + const copy = memory.buffer.slice(ptr, ptr + byteLen); + taStack.push(Array.from(new Ctor(copy))); + } + bjs["bjs_core_register_type_handles"] = function() {}; + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } + bjs["swift_js_return_optional_bool"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalBool = null; + } else { + tmpRetOptionalBool = value !== 0; + } + } + bjs["swift_js_return_optional_int"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalInt = null; + } else { + tmpRetOptionalInt = value | 0; + } + } + bjs["swift_js_return_optional_float"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalFloat = null; + } else { + tmpRetOptionalFloat = Math.fround(value); + } + } + bjs["swift_js_return_optional_double"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalDouble = null; + } else { + tmpRetOptionalDouble = value; + } + } + bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = decodeString(ptr, len); + } + } + bjs["swift_js_return_optional_object"] = function(isSome, objectId) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = swift.memory.getObject(objectId); + } + } + bjs["swift_js_return_optional_heap_object"] = function(isSome, pointer) { + if (isSome === 0) { + tmpRetOptionalHeapObject = null; + } else { + tmpRetOptionalHeapObject = pointer; + } + } + bjs["swift_js_get_optional_int_presence"] = function() { + return tmpRetOptionalInt != null ? 1 : 0; + } + bjs["swift_js_get_optional_int_value"] = function() { + const value = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; + return value; + } + bjs["swift_js_get_optional_string"] = function() { + const str = tmpRetString; + tmpRetString = undefined; + if (str == null) { + return -1; + } else { + const bytes = textEncoder.encode(str); + tmpRetBytes = bytes; + return bytes.length; + } + } + bjs["swift_js_get_optional_float_presence"] = function() { + return tmpRetOptionalFloat != null ? 1 : 0; + } + bjs["swift_js_get_optional_float_value"] = function() { + const value = tmpRetOptionalFloat; + tmpRetOptionalFloat = undefined; + return value; + } + bjs["swift_js_get_optional_double_presence"] = function() { + return tmpRetOptionalDouble != null ? 1 : 0; + } + bjs["swift_js_get_optional_double_value"] = function() { + const value = tmpRetOptionalDouble; + tmpRetOptionalDouble = undefined; + return value; + } + bjs["swift_js_get_optional_heap_object_pointer"] = function() { + const pointer = tmpRetOptionalHeapObject; + tmpRetOptionalHeapObject = undefined; + return pointer || 0; + } + bjs["swift_js_closure_unregister"] = function(funcRef) {} + // Wrapper functions for module: TestModule + if (!importObject["TestModule"]) { + importObject["TestModule"] = {}; + } + importObject["TestModule"]["bjs_Workshop_Bench_wrap"] = function(pointer) { + const obj = _exports.Workshop.Bench.__construct(pointer); + return swift.memory.retain(obj); + }; + }, + setInstance: (i) => { + instance = i; + memory = instance.exports.memory; + + decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + + setException = (error) => { + instance.exports._swift_js_exception.value = swift.memory.retain(error) + } + }, + /** @param {WebAssembly.Instance} instance */ + createExports: (instance) => { + const js = swift.memory.heap; + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.identityMap?.delete(state.pointer); + state.deinit(state.pointer); + }); + + /// Represents a Swift heap object like a class instance or an actor instance. + class SwiftHeapObject { + static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; + const makeFresh = (identityMap) => { + const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false, identityMap }; + obj.pointer = pointer; + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); + if (identityMap) { + identityMap.set(pointer, new WeakRef(obj)); + } + return obj; + }; + + if (!identityCache) { + return makeFresh(null); + } + + const cached = identityCache.get(pointer)?.deref(); + if (cached && !cached.__swiftHeapObjectState.hasReleased) { + deinit(pointer); + return cached; + } + if (identityCache.has(pointer)) { + identityCache.delete(pointer); + } + + return makeFresh(identityCache); + } + + release() { + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.identityMap?.delete(state.pointer); + state.deinit(state.pointer); + } + } + class Bench extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Workshop_Bench_deinit, Bench.prototype, null); + } + + constructor() { + const ret = instance.exports.bjs_Workshop_Bench_init(); + return Bench.__construct(ret); + } + } + const exports = { + makeBench: function bjs_makeBench() { + const ret = instance.exports.bjs_makeBench(); + return Bench.__construct(ret); + }, + Workshop: { + Bench, + }, + }; + _exports = exports; + return exports; + }, + } +} \ No newline at end of file From ae935a974a47ca277ca29584595e03e56f87f1ef Mon Sep 17 00:00:00 2001 From: William Taylor Date: Mon, 17 Aug 2026 12:58:43 +1000 Subject: [PATCH 47/50] Fix types in extensions bugs --- .../BridgeJSCore/SwiftToSkeleton.swift | 61 +++- .../Sources/BridgeJSLink/BridgeJSLink.swift | 29 +- .../BridgeJSCodegenTests.swift | 24 ++ .../ExtensionOrderIndependence.swift | 19 + .../CrossFileExtensionOrderMember.swift | 5 + .../CrossFileExtensionOrderType.swift | 13 + .../MacroSwift/NamespacedClassSignature.swift | 4 + .../MacroSwift/NestedTypeNameCollision.swift | 25 ++ .../CrossFileExtensionOrderIndependence.json | 106 ++++++ .../CrossFileExtensionOrderIndependence.swift | 128 +++++++ .../ExtensionOrderIndependence.json | 106 ++++++ .../ExtensionOrderIndependence.swift | 128 +++++++ .../NamespacedClassSignature.json | 53 +++ .../NamespacedClassSignature.swift | 74 ++++ .../NestedTypeNameCollision.json | 177 +++++++++ .../NestedTypeNameCollision.swift | 159 ++++++++ .../ExtensionOrderIndependence.d.ts | 38 ++ .../ExtensionOrderIndependence.js | 339 ++++++++++++++++++ .../NamespacedClassSignature.d.ts | 1 + .../NamespacedClassSignature.js | 57 +++ .../NestedTypeNameCollision.d.ts | 35 ++ .../NestedTypeNameCollision.js | 299 +++++++++++++++ 22 files changed, 1851 insertions(+), 29 deletions(-) create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ExtensionOrderIndependence.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileExtensionOrderMember.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileExtensionOrderType.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/NestedTypeNameCollision.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtensionOrderIndependence.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtensionOrderIndependence.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionOrderIndependence.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionOrderIndependence.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedTypeNameCollision.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedTypeNameCollision.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionOrderIndependence.d.ts create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionOrderIndependence.js create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedTypeNameCollision.d.ts create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedTypeNameCollision.js diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index f119f5bff..fb9cee01c 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -139,6 +139,39 @@ public final class SwiftToSkeleton { sourceFiles.append((sourceFile, inputFilePath)) } + private func resolveDeferredExtensions(_ exportCollectors: [ExportSwiftAPICollector]) { + var pendingExtensions = exportCollectors.flatMap { collector in + collector.deferredExtensions.map { (owner: collector, declaration: $0) } + } + var previousCount: Int + // An extended type might be defined in another extension, so keep resolving until no more progress is made. + repeat { + previousCount = pendingExtensions.count + var nextPendingExtensions: [(owner: ExportSwiftAPICollector, declaration: ExtensionDeclSyntax)] = [] + for pending in pendingExtensions { + if !resolveExtension(pending.declaration, in: exportCollectors) { + nextPendingExtensions.append(pending) + } + } + pendingExtensions = nextPendingExtensions + } while pendingExtensions.count < previousCount + for pending in pendingExtensions { + pending.owner.diagnoseUnresolvedExtension(pending.declaration) + } + } + + private func resolveExtension( + _ declaration: ExtensionDeclSyntax, + in exportCollectors: [ExportSwiftAPICollector] + ) -> Bool { + for collector in exportCollectors { + if collector.resolveExtension(declaration) { + return true + } + } + return false + } + public func finalize() throws -> BridgeJSSkeleton { var perSourceErrors: [(inputFilePath: String, errors: [DiagnosticError])] = [] var importedFiles: [ImportedFileSkeleton] = [] @@ -244,9 +277,7 @@ public final class SwiftToSkeleton { } // Resolve extensions against all collectors. This needs to happen at this point so we can resolve both same file and cross file extensions. - for source in exportCollectors { - source.resolveDeferredExtensions(against: exportCollectors) - } + resolveDeferredExtensions(exportCollectors) // We have to collect diagnostics after all deferred extensions are resolved, since they could generate some. for ((_, inputFilePath), exportCollector) in zip(sourceFiles, exportCollectors) { @@ -1946,23 +1977,15 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { return .skipChildren } - func resolveDeferredExtensions(against collectors: [ExportSwiftAPICollector]) { - for ext in deferredExtensions { - var resolved = false - for collector in collectors { - if collector.resolveExtension(ext) { - resolved = true - break - } - } - if !resolved, containsJSAnnotatedDeclaration(ext.memberBlock.members) { - diagnose( - node: ext.extendedType, - message: "Unsupported type '\(ext.extendedType.trimmedDescription)'.", - hint: "You can only extend `@JS` annotated types defined in the same module" - ) - } + func diagnoseUnresolvedExtension(_ ext: ExtensionDeclSyntax) { + guard containsJSAnnotatedDeclaration(ext.memberBlock.members) else { + return } + diagnose( + node: ext.extendedType, + message: "Unsupported type '\(ext.extendedType.trimmedDescription)'.", + hint: "You can only extend `@JS` annotated types defined in the same module" + ) } private func containsJSAnnotatedDeclaration(_ members: MemberBlockItemListSyntax) -> Bool { diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index b796c35e7..0e5bdc221 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -1689,7 +1689,7 @@ public struct BridgeJSLink { // Look up the enum to get its tsFullPath for skeleton in exportedSkeletons { for enumDef in skeleton.enums { - if enumDef.name == name || enumDef.swiftCallName == name { + if enumDef.swiftCallName == name { // Use the stored tsFullPath which has the full namespace switch type { case .namespaceEnum: @@ -1707,7 +1707,7 @@ public struct BridgeJSLink { case .swiftStruct(let name): for skeleton in exportedSkeletons { for structDef in skeleton.structs { - if structDef.name == name || structDef.swiftCallName == name { + if structDef.swiftCallName == name { return structDef.tsFullPath } } @@ -1716,12 +1716,14 @@ public struct BridgeJSLink { case .swiftHeapObject(let name): for skeleton in exportedSkeletons { for klass in skeleton.classes { - if klass.name == name || klass.swiftCallName == name { + if klass.swiftCallName == name { return klass.name } } } return type.tsType + case .closure(let signature, _): + return signature.renderTSFunctionType { resolveTypeScriptType($0, exportedSkeletons: exportedSkeletons) } case .alias(_, let underlying): return resolveTypeScriptType(underlying, exportedSkeletons: exportedSkeletons) case .nullable(let wrapped, let kind): @@ -3761,7 +3763,8 @@ extension BridgeJSLink { let abiName = getter.abiName(context: nil) let funcLines = thunkBuilder.renderFunction(name: abiName) if getter.from == nil { - importObjectBuilder.appendDts(["readonly \(renderTSPropertyName(jsName)): \(getter.type.tsType);"]) + importObjectBuilder.appendDts(["readonly \(renderTSPropertyName(jsName)): \(getter.type.tsType);"] + ) } importObjectBuilder.assignToImportObject(name: abiName, function: funcLines) } @@ -4230,6 +4233,17 @@ struct BridgeJSLinkError: Error { let message: String } +extension ClosureSignature { + fileprivate func renderTSFunctionType(renderType: (BridgeType) -> String) -> String { + let renderedParameters = parameters.enumerated().map { index, parameter in + "arg\(index): \(renderType(parameter))" + }.joined(separator: ", ") + let renderedReturnType = renderType(returnType) + let returnTypeWithEffect = isAsync ? "Promise<\(renderedReturnType)>" : renderedReturnType + return "(\(renderedParameters)) => \(returnTypeWithEffect)" + } +} + extension BridgeType { var tsType: String { switch self { @@ -4271,12 +4285,7 @@ extension BridgeType { case .swiftProtocol(let name): return name case .closure(let signature, _): - let paramTypes = signature.parameters.enumerated().map { index, param in - "arg\(index): \(param.tsType)" - }.joined(separator: ", ") - let returnTS = - signature.isAsync ? "Promise<\(signature.returnType.tsType)>" : signature.returnType.tsType - return "(\(paramTypes)) => \(returnTS)" + return signature.renderTSFunctionType { $0.tsType } case .array(let elementType): let inner = elementType.tsType if inner.contains("|") || inner.contains("=>") { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift index baffc0c20..11347dc40 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSCodegenTests.swift @@ -358,6 +358,30 @@ import Testing try snapshotCodegen(skeleton: skeleton, name: "CrossFileNestedTypeExtension") } + @Test + func codegenCrossFileExtensionOrderIndependence() throws { + let swiftAPI = SwiftToSkeleton( + progress: .silent, + moduleName: "TestModule", + exposeToGlobal: false, + externalModuleIndex: .empty + ) + let memberURL = Self.multifileInputsDirectory.appendingPathComponent("CrossFileExtensionOrderMember.swift") + swiftAPI.addSourceFile( + Parser.parse(source: try String(contentsOf: memberURL, encoding: .utf8)), + inputFilePath: "CrossFileExtensionOrderMember.swift" + ) + let typeURL = Self.multifileInputsDirectory.appendingPathComponent("CrossFileExtensionOrderType.swift") + swiftAPI.addSourceFile( + Parser.parse(source: try String(contentsOf: typeURL, encoding: .utf8)), + inputFilePath: "CrossFileExtensionOrderType.swift" + ) + let skeleton = try swiftAPI.finalize() + let record = skeleton.exported?.structs.first { $0.swiftCallName == "Archive.Record" } + #expect(record?.methods.map(\.name) == ["describeRecord"]) + try snapshotCodegen(skeleton: skeleton, name: "CrossFileExtensionOrderIndependence") + } + @Test func codegenSkipsEmptySkeletons() throws { let swiftAPI = SwiftToSkeleton( diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ExtensionOrderIndependence.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ExtensionOrderIndependence.swift new file mode 100644 index 000000000..143a60233 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/ExtensionOrderIndependence.swift @@ -0,0 +1,19 @@ +@JS class Depot { + @JS init() {} +} + +extension Depot.Crate { + @JS func describeCrate() -> String { + "Crate: " + label + } +} + +extension Depot { + @JS struct Crate { + var label: String + + @JS init(label: String) { + self.label = label + } + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileExtensionOrderMember.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileExtensionOrderMember.swift new file mode 100644 index 000000000..277e9d40f --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileExtensionOrderMember.swift @@ -0,0 +1,5 @@ +extension Archive.Record { + @JS func describeRecord() -> String { + "Record: " + label + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileExtensionOrderType.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileExtensionOrderType.swift new file mode 100644 index 000000000..641e25559 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/Multifile/CrossFileExtensionOrderType.swift @@ -0,0 +1,13 @@ +@JS class Archive { + @JS init() {} +} + +extension Archive { + @JS struct Record { + var label: String + + @JS init(label: String) { + self.label = label + } + } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/NamespacedClassSignature.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/NamespacedClassSignature.swift index 4e684ac11..67841f250 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/NamespacedClassSignature.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/NamespacedClassSignature.swift @@ -7,3 +7,7 @@ @JS func makeBench() -> Workshop.Bench { Workshop.Bench() } + +@JS func refitBench(_ bench: Workshop.Bench, _ transform: (Workshop.Bench) -> Workshop.Bench) -> Workshop.Bench { + transform(bench) +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/NestedTypeNameCollision.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/NestedTypeNameCollision.swift new file mode 100644 index 000000000..231e8d7b6 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/NestedTypeNameCollision.swift @@ -0,0 +1,25 @@ +@JS enum Catalog { + @JS struct Entry { + var title: String + + @JS init(title: String) { + self.title = title + } + } +} + +@JS struct Entry { + var identifier: Int + + @JS init(identifier: Int) { + self.identifier = identifier + } +} + +@JS func takeEntry(_ entry: Entry) -> Entry { + entry +} + +@JS func takeCatalogEntry(_ entry: Catalog.Entry) -> Catalog.Entry { + entry +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtensionOrderIndependence.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtensionOrderIndependence.json new file mode 100644 index 000000000..ef20e9a28 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtensionOrderIndependence.json @@ -0,0 +1,106 @@ +{ + "exported" : { + "aliases" : [ + + ], + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_Archive_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + + ], + "name" : "Archive", + "properties" : [ + + ], + "swiftCallName" : "Archive" + } + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + + ], + "protocols" : [ + + ], + "structs" : [ + { + "constructor" : { + "abiName" : "bjs_Archive_Record_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "label", + "name" : "label", + "type" : { + "string" : { + + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_Archive_Record_describeRecord", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "describeRecord", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "name" : "Record", + "namespace" : [ + "Archive" + ], + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "label", + "namespace" : [ + "Archive" + ], + "type" : { + "string" : { + + } + } + } + ], + "swiftCallName" : "Archive.Record" + } + ] + }, + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtensionOrderIndependence.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtensionOrderIndependence.swift new file mode 100644 index 000000000..c8df6b29e --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/CrossFileExtensionOrderIndependence.swift @@ -0,0 +1,128 @@ +extension Archive.Record: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Archive.Record { + let label = String.bridgeJSStackPop() + return Archive.Record(label: label) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.label.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_Archive_Record(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Archive_Record())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Archive_Record") +fileprivate func _bjs_struct_lower_Archive_Record_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_Archive_Record_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_Archive_Record(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Archive_Record_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Archive_Record") +fileprivate func _bjs_struct_lift_Archive_Record_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_Archive_Record_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_Archive_Record() -> Int32 { + return _bjs_struct_lift_Archive_Record_extern() +} + +@_expose(wasm, "bjs_Archive_Record_init") +@_cdecl("bjs_Archive_Record_init") +public func _bjs_Archive_Record_init(_ labelBytes: Int32, _ labelLength: Int32) -> Void { + #if arch(wasm32) + let ret = Archive.Record(label: String.bridgeJSLiftParameter(labelBytes, labelLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Archive_Record_describeRecord") +@_cdecl("bjs_Archive_Record_describeRecord") +public func _bjs_Archive_Record_describeRecord() -> Void { + #if arch(wasm32) + let ret = Archive.Record.bridgeJSLiftParameter().describeRecord() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Archive_init") +@_cdecl("bjs_Archive_init") +public func _bjs_Archive_init() -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = Archive() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Archive_deinit") +@_cdecl("bjs_Archive_deinit") +public func _bjs_Archive_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension Archive: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_Archive_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_Archive_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_Archive_wrap") +fileprivate func _bjs_Archive_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_Archive_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_Archive_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Archive_wrap_extern(pointer) +} + +extension Archive.Record: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Archive.Record.bridgeJSMakeTypeHandle() +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Archive.Record.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionOrderIndependence.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionOrderIndependence.json new file mode 100644 index 000000000..9096006ae --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionOrderIndependence.json @@ -0,0 +1,106 @@ +{ + "exported" : { + "aliases" : [ + + ], + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_Depot_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + + ], + "name" : "Depot", + "properties" : [ + + ], + "swiftCallName" : "Depot" + } + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + + ], + "protocols" : [ + + ], + "structs" : [ + { + "constructor" : { + "abiName" : "bjs_Depot_Crate_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "label", + "name" : "label", + "type" : { + "string" : { + + } + } + } + ] + }, + "methods" : [ + { + "abiName" : "bjs_Depot_Crate_describeCrate", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "describeCrate", + "parameters" : [ + + ], + "returnType" : { + "string" : { + + } + } + } + ], + "name" : "Crate", + "namespace" : [ + "Depot" + ], + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "label", + "namespace" : [ + "Depot" + ], + "type" : { + "string" : { + + } + } + } + ], + "swiftCallName" : "Depot.Crate" + } + ] + }, + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionOrderIndependence.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionOrderIndependence.swift new file mode 100644 index 000000000..cc8091bbe --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/ExtensionOrderIndependence.swift @@ -0,0 +1,128 @@ +extension Depot.Crate: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Depot.Crate { + let label = String.bridgeJSStackPop() + return Depot.Crate(label: label) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.label.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_Depot_Crate(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Depot_Crate())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Depot_Crate") +fileprivate func _bjs_struct_lower_Depot_Crate_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_Depot_Crate_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_Depot_Crate(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Depot_Crate_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Depot_Crate") +fileprivate func _bjs_struct_lift_Depot_Crate_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_Depot_Crate_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_Depot_Crate() -> Int32 { + return _bjs_struct_lift_Depot_Crate_extern() +} + +@_expose(wasm, "bjs_Depot_Crate_init") +@_cdecl("bjs_Depot_Crate_init") +public func _bjs_Depot_Crate_init(_ labelBytes: Int32, _ labelLength: Int32) -> Void { + #if arch(wasm32) + let ret = Depot.Crate(label: String.bridgeJSLiftParameter(labelBytes, labelLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Depot_Crate_describeCrate") +@_cdecl("bjs_Depot_Crate_describeCrate") +public func _bjs_Depot_Crate_describeCrate() -> Void { + #if arch(wasm32) + let ret = Depot.Crate.bridgeJSLiftParameter().describeCrate() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Depot_init") +@_cdecl("bjs_Depot_init") +public func _bjs_Depot_init() -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = Depot() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Depot_deinit") +@_cdecl("bjs_Depot_deinit") +public func _bjs_Depot_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension Depot: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_Depot_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_Depot_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_Depot_wrap") +fileprivate func _bjs_Depot_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_Depot_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_Depot_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Depot_wrap_extern(pointer) +} + +extension Depot.Crate: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Depot.Crate.bridgeJSMakeTypeHandle() +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Depot.Crate.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NamespacedClassSignature.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NamespacedClassSignature.json index a6aaddafe..e4568f101 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NamespacedClassSignature.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NamespacedClassSignature.json @@ -64,6 +64,59 @@ "_0" : "Workshop.Bench" } } + }, + { + "abiName" : "bjs_refitBench", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "refitBench", + "parameters" : [ + { + "label" : "_", + "name" : "bench", + "type" : { + "swiftHeapObject" : { + "_0" : "Workshop.Bench" + } + } + }, + { + "label" : "_", + "name" : "transform", + "type" : { + "closure" : { + "_0" : { + "isAsync" : false, + "isThrows" : false, + "mangleName" : "10TestModule14Workshop.BenchC_14Workshop.BenchC", + "moduleName" : "TestModule", + "parameters" : [ + { + "swiftHeapObject" : { + "_0" : "Workshop.Bench" + } + } + ], + "returnType" : { + "swiftHeapObject" : { + "_0" : "Workshop.Bench" + } + }, + "sendingParameters" : false + }, + "useJSTypedClosure" : false + } + } + } + ], + "returnType" : { + "swiftHeapObject" : { + "_0" : "Workshop.Bench" + } + } } ], "protocols" : [ diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NamespacedClassSignature.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NamespacedClassSignature.swift index 0bb5652f1..511d0f75c 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NamespacedClassSignature.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NamespacedClassSignature.swift @@ -1,3 +1,66 @@ +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC") +fileprivate func invoke_js_callback_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC_extern(_ callback: Int32, _ param0: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer +#else +fileprivate func invoke_js_callback_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC_extern(_ callback: Int32, _ param0: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC(_ callback: Int32, _ param0: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + return invoke_js_callback_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC_extern(callback, param0) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC") +fileprivate func make_swift_closure_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +#else +fileprivate func make_swift_closure_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC_extern(boxPtr, file, line) +} + +private enum _BJS_Closure_10TestModule14Workshop.BenchC_14Workshop.BenchC { + static func bridgeJSLift(_ callbackId: Int32) -> (Workshop.Bench) -> Workshop.Bench { + let callback = JSObject.bridgeJSLiftParameter(callbackId) + return { [callback] param0 in + #if arch(wasm32) + let param0Pointer = param0.bridgeJSLowerParameter() + let callbackValue = callback.bridgeJSLowerParameter() + let ret = invoke_js_callback_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC(callbackValue, param0Pointer) + return Workshop.Bench.bridgeJSLiftReturn(ret) + #else + fatalError("Only available on WebAssembly") + #endif + } + } +} + +extension JSTypedClosure where Signature == (Workshop.Bench) -> Workshop.Bench { + init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Workshop.Bench) -> Workshop.Bench) { + self.init( + makeClosure: make_swift_closure_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC, + body: body, + fileID: fileID, + line: line + ) + } +} + +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC") +@_cdecl("invoke_swift_closure_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC") +public func _invoke_swift_closure_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC(_ boxPtr: UnsafeMutableRawPointer, _ param0: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let closure = Unmanaged<_BridgeJSTypedClosureBox<(Workshop.Bench) -> Workshop.Bench>>.fromOpaque(boxPtr).takeUnretainedValue().closure + let result = closure(Workshop.Bench.bridgeJSLiftParameter(param0)) + return result.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_makeBench") @_cdecl("bjs_makeBench") public func _bjs_makeBench() -> UnsafeMutableRawPointer { @@ -9,6 +72,17 @@ public func _bjs_makeBench() -> UnsafeMutableRawPointer { #endif } +@_expose(wasm, "bjs_refitBench") +@_cdecl("bjs_refitBench") +public func _bjs_refitBench(_ bench: UnsafeMutableRawPointer, _ transform: Int32) -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = refitBench(_: Workshop.Bench.bridgeJSLiftParameter(bench), _: _BJS_Closure_10TestModule14Workshop.BenchC_14Workshop.BenchC.bridgeJSLift(transform)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + @_expose(wasm, "bjs_Workshop_Bench_init") @_cdecl("bjs_Workshop_Bench_init") public func _bjs_Workshop_Bench_init() -> UnsafeMutableRawPointer { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedTypeNameCollision.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedTypeNameCollision.json new file mode 100644 index 000000000..8683e11b1 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedTypeNameCollision.json @@ -0,0 +1,177 @@ +{ + "exported" : { + "aliases" : [ + + ], + "classes" : [ + + ], + "enums" : [ + { + "cases" : [ + + ], + "emitStyle" : "const", + "name" : "Catalog", + "staticMethods" : [ + + ], + "staticProperties" : [ + + ], + "swiftCallName" : "Catalog", + "tsFullPath" : "Catalog" + } + ], + "exposeToGlobal" : false, + "functions" : [ + { + "abiName" : "bjs_takeEntry", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "takeEntry", + "parameters" : [ + { + "label" : "_", + "name" : "entry", + "type" : { + "swiftStruct" : { + "_0" : "Entry" + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "Entry" + } + } + }, + { + "abiName" : "bjs_takeCatalogEntry", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "takeCatalogEntry", + "parameters" : [ + { + "label" : "_", + "name" : "entry", + "type" : { + "swiftStruct" : { + "_0" : "Catalog.Entry" + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "Catalog.Entry" + } + } + } + ], + "protocols" : [ + + ], + "structs" : [ + { + "constructor" : { + "abiName" : "bjs_Catalog_Entry_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "title", + "name" : "title", + "type" : { + "string" : { + + } + } + } + ] + }, + "methods" : [ + + ], + "name" : "Entry", + "namespace" : [ + "Catalog" + ], + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "title", + "namespace" : [ + "Catalog" + ], + "type" : { + "string" : { + + } + } + } + ], + "swiftCallName" : "Catalog.Entry" + }, + { + "constructor" : { + "abiName" : "bjs_Entry_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "identifier", + "name" : "identifier", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ] + }, + "methods" : [ + + ], + "name" : "Entry", + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "identifier", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "swiftCallName" : "Entry" + } + ] + }, + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedTypeNameCollision.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedTypeNameCollision.swift new file mode 100644 index 000000000..266f37f09 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NestedTypeNameCollision.swift @@ -0,0 +1,159 @@ +extension Catalog.Entry: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Catalog.Entry { + let title = String.bridgeJSStackPop() + return Catalog.Entry(title: title) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.title.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_Catalog_Entry(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Catalog_Entry())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Catalog_Entry") +fileprivate func _bjs_struct_lower_Catalog_Entry_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_Catalog_Entry_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_Catalog_Entry(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Catalog_Entry_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Catalog_Entry") +fileprivate func _bjs_struct_lift_Catalog_Entry_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_Catalog_Entry_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_Catalog_Entry() -> Int32 { + return _bjs_struct_lift_Catalog_Entry_extern() +} + +@_expose(wasm, "bjs_Catalog_Entry_init") +@_cdecl("bjs_Catalog_Entry_init") +public func _bjs_Catalog_Entry_init(_ titleBytes: Int32, _ titleLength: Int32) -> Void { + #if arch(wasm32) + let ret = Catalog.Entry(title: String.bridgeJSLiftParameter(titleBytes, titleLength)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension Entry: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Entry { + let identifier = Int.bridgeJSStackPop() + return Entry(identifier: identifier) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.identifier.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_Entry(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Entry())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Entry") +fileprivate func _bjs_struct_lower_Entry_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_Entry_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_Entry(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Entry_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Entry") +fileprivate func _bjs_struct_lift_Entry_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_Entry_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_Entry() -> Int32 { + return _bjs_struct_lift_Entry_extern() +} + +@_expose(wasm, "bjs_Entry_init") +@_cdecl("bjs_Entry_init") +public func _bjs_Entry_init(_ identifier: Int32) -> Void { + #if arch(wasm32) + let ret = Entry(identifier: Int.bridgeJSLiftParameter(identifier)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_takeEntry") +@_cdecl("bjs_takeEntry") +public func _bjs_takeEntry() -> Void { + #if arch(wasm32) + let ret = takeEntry(_: Entry.bridgeJSLiftParameter()) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_takeCatalogEntry") +@_cdecl("bjs_takeCatalogEntry") +public func _bjs_takeCatalogEntry() -> Void { + #if arch(wasm32) + let ret = takeCatalogEntry(_: Catalog.Entry.bridgeJSLiftParameter()) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension Catalog.Entry: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Catalog.Entry.bridgeJSMakeTypeHandle() +} + +extension Entry: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Entry.bridgeJSMakeTypeHandle() +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Catalog.Entry.bridgeJSTypeID, + Entry.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionOrderIndependence.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionOrderIndependence.d.ts new file mode 100644 index 000000000..2b16f6a6d --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionOrderIndependence.d.ts @@ -0,0 +1,38 @@ +// 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`. + +export namespace Depot { + export interface Crate { + label: string; + describeCrate(): string; + } +} +/// Represents a Swift heap object like a class instance or an actor instance. +export interface SwiftHeapObject { + /// Release the heap object. + /// + /// Note: Calling this method will release the heap object and it will no longer be accessible. + release(): void; +} +export interface Depot extends SwiftHeapObject { +} +export type Exports = { + Depot: { + new(): Depot; + Crate: { + init(label: string): Depot.Crate; + }, + }, +} +export type Imports = { +} +export function createInstantiator(options: { + imports: Imports; +}, swift: any): Promise<{ + addImports: (importObject: WebAssembly.Imports) => void; + setInstance: (instance: WebAssembly.Instance) => void; + createExports: (instance: WebAssembly.Instance) => Exports; +}>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionOrderIndependence.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionOrderIndependence.js new file mode 100644 index 000000000..6cc339d24 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/ExtensionOrderIndependence.js @@ -0,0 +1,339 @@ +// 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`. + +export async function createInstantiator(options, swift) { + let instance; + let memory; + let setException; + let decodeString; + const textDecoder = new TextDecoder("utf-8"); + const textEncoder = new TextEncoder("utf-8"); + let tmpRetString; + let tmpRetBytes; + let tmpRetException; + let tmpRetOptionalBool; + let tmpRetOptionalInt; + let tmpRetOptionalFloat; + let tmpRetOptionalDouble; + let tmpRetOptionalHeapObject; + let strStack = []; + let i32Stack = []; + let i64Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; + let taStack = []; + const enumHelpers = {}; + const structHelpers = {}; + + let _exports = null; + let bjs = null; + const __bjs_createStructHelpers_M10TestModuleT5DepotT5Crate = () => ({ + lower: (value) => { + const bytes = textEncoder.encode(value.label); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + }, + lift: () => { + const string = strStack.pop(); + const instance1 = { label: string }; + instance1.describeCrate = function() { + structHelpers.M10TestModuleT5DepotT5Crate.lower(this); + const ret = instance.exports.bjs_Depot_Crate_describeCrate(); + const ret1 = tmpRetString; + tmpRetString = undefined; + return ret1; + }.bind(instance1); + return instance1; + } + }); + + return { + /** + * @param {WebAssembly.Imports} importObject + */ + addImports: (importObject, importsContext) => { + bjs = {}; + importObject["bjs"] = bjs; + bjs["swift_js_return_string"] = function(ptr, len) { + tmpRetString = decodeString(ptr, len); + } + bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { + const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); + bytes.set(source); + } + bjs["swift_js_make_js_string"] = function(ptr, len) { + return swift.memory.retain(decodeString(ptr, len)); + } + bjs["swift_js_init_memory_with_result"] = function(ptr, len) { + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); + target.set(tmpRetBytes); + tmpRetBytes = undefined; + } + bjs["swift_js_throw"] = function(id) { + tmpRetException = swift.memory.retainByRef(id); + } + bjs["swift_js_retain"] = function(id) { + return swift.memory.retainByRef(id); + } + bjs["swift_js_release"] = function(id) { + swift.memory.release(id); + } + bjs["swift_js_push_i32"] = function(v) { + i32Stack.push(v | 0); + } + bjs["swift_js_push_f32"] = function(v) { + f32Stack.push(Math.fround(v)); + } + bjs["swift_js_push_f64"] = function(v) { + f64Stack.push(v); + } + bjs["swift_js_push_string"] = function(ptr, len) { + const value = decodeString(ptr, len); + strStack.push(value); + } + bjs["swift_js_pop_i32"] = function() { + return i32Stack.pop(); + } + bjs["swift_js_pop_f32"] = function() { + return f32Stack.pop(); + } + bjs["swift_js_pop_f64"] = function() { + return f64Stack.pop(); + } + bjs["swift_js_push_pointer"] = function(pointer) { + ptrStack.push(pointer); + } + bjs["swift_js_pop_pointer"] = function() { + return ptrStack.pop(); + } + bjs["swift_js_push_i64"] = function(v) { + i64Stack.push(v); + } + bjs["swift_js_pop_i64"] = function() { + return i64Stack.pop(); + } + const taCtors = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array]; + bjs["swift_js_push_typed_array"] = function(kind, ptr, count) { + const Ctor = taCtors[kind]; + const byteLen = count * Ctor.BYTES_PER_ELEMENT; + const copy = memory.buffer.slice(ptr, ptr + byteLen); + taStack.push(Array.from(new Ctor(copy))); + } + bjs["swift_js_struct_lower_Depot_Crate"] = function(objectId) { + structHelpers.M10TestModuleT5DepotT5Crate.lower(swift.memory.getObject(objectId)); + } + bjs["swift_js_struct_lift_Depot_Crate"] = function() { + const value = structHelpers.M10TestModuleT5DepotT5Crate.lift(); + return swift.memory.retain(value); + } + bjs["bjs_core_register_type_handles"] = function() {}; + bjs["bjs_TestModule_register_type_handles"] = function() {}; + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } + bjs["swift_js_return_optional_bool"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalBool = null; + } else { + tmpRetOptionalBool = value !== 0; + } + } + bjs["swift_js_return_optional_int"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalInt = null; + } else { + tmpRetOptionalInt = value | 0; + } + } + bjs["swift_js_return_optional_float"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalFloat = null; + } else { + tmpRetOptionalFloat = Math.fround(value); + } + } + bjs["swift_js_return_optional_double"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalDouble = null; + } else { + tmpRetOptionalDouble = value; + } + } + bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = decodeString(ptr, len); + } + } + bjs["swift_js_return_optional_object"] = function(isSome, objectId) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = swift.memory.getObject(objectId); + } + } + bjs["swift_js_return_optional_heap_object"] = function(isSome, pointer) { + if (isSome === 0) { + tmpRetOptionalHeapObject = null; + } else { + tmpRetOptionalHeapObject = pointer; + } + } + bjs["swift_js_get_optional_int_presence"] = function() { + return tmpRetOptionalInt != null ? 1 : 0; + } + bjs["swift_js_get_optional_int_value"] = function() { + const value = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; + return value; + } + bjs["swift_js_get_optional_string"] = function() { + const str = tmpRetString; + tmpRetString = undefined; + if (str == null) { + return -1; + } else { + const bytes = textEncoder.encode(str); + tmpRetBytes = bytes; + return bytes.length; + } + } + bjs["swift_js_get_optional_float_presence"] = function() { + return tmpRetOptionalFloat != null ? 1 : 0; + } + bjs["swift_js_get_optional_float_value"] = function() { + const value = tmpRetOptionalFloat; + tmpRetOptionalFloat = undefined; + return value; + } + bjs["swift_js_get_optional_double_presence"] = function() { + return tmpRetOptionalDouble != null ? 1 : 0; + } + bjs["swift_js_get_optional_double_value"] = function() { + const value = tmpRetOptionalDouble; + tmpRetOptionalDouble = undefined; + return value; + } + bjs["swift_js_get_optional_heap_object_pointer"] = function() { + const pointer = tmpRetOptionalHeapObject; + tmpRetOptionalHeapObject = undefined; + return pointer || 0; + } + bjs["swift_js_closure_unregister"] = function(funcRef) {} + // Wrapper functions for module: TestModule + if (!importObject["TestModule"]) { + importObject["TestModule"] = {}; + } + importObject["TestModule"]["bjs_Depot_wrap"] = function(pointer) { + const obj = _exports['Depot'].__construct(pointer); + return swift.memory.retain(obj); + }; + }, + setInstance: (i) => { + instance = i; + memory = instance.exports.memory; + + decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + + setException = (error) => { + instance.exports._swift_js_exception.value = swift.memory.retain(error) + } + }, + /** @param {WebAssembly.Instance} instance */ + createExports: (instance) => { + const js = swift.memory.heap; + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.identityMap?.delete(state.pointer); + state.deinit(state.pointer); + }); + + /// Represents a Swift heap object like a class instance or an actor instance. + class SwiftHeapObject { + static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; + const makeFresh = (identityMap) => { + const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false, identityMap }; + obj.pointer = pointer; + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); + if (identityMap) { + identityMap.set(pointer, new WeakRef(obj)); + } + return obj; + }; + + if (!identityCache) { + return makeFresh(null); + } + + const cached = identityCache.get(pointer)?.deref(); + if (cached && !cached.__swiftHeapObjectState.hasReleased) { + deinit(pointer); + return cached; + } + if (identityCache.has(pointer)) { + identityCache.delete(pointer); + } + + return makeFresh(identityCache); + } + + release() { + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.identityMap?.delete(state.pointer); + state.deinit(state.pointer); + } + } + class Depot extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Depot_deinit, Depot.prototype, null); + } + + constructor() { + const ret = instance.exports.bjs_Depot_init(); + return Depot.__construct(ret); + } + } + const __bjs_helpers_M10TestModuleT5DepotT5Crate = __bjs_createStructHelpers_M10TestModuleT5DepotT5Crate(); + structHelpers.M10TestModuleT5DepotT5Crate = __bjs_helpers_M10TestModuleT5DepotT5Crate; + + const exports = { + Depot: Object.assign(Depot, { + Crate: { + init: function(label) { + const labelBytes = textEncoder.encode(label); + const labelId = swift.memory.retain(labelBytes); + instance.exports.bjs_Depot_Crate_init(labelId, labelBytes.length); + const structValue = structHelpers.M10TestModuleT5DepotT5Crate.lift(); + return structValue; + }, + }, + }), + }; + _exports = exports; + return exports; + }, + } +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NamespacedClassSignature.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NamespacedClassSignature.d.ts index 35e010247..7c7c4ce3a 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NamespacedClassSignature.d.ts +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NamespacedClassSignature.d.ts @@ -15,6 +15,7 @@ export interface Bench extends SwiftHeapObject { } export type Exports = { makeBench(): Bench; + refitBench(bench: Bench, transform: (arg0: Bench) => Bench): Bench; Workshop: { Bench: { new(): Bench; diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NamespacedClassSignature.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NamespacedClassSignature.js index 33ca4c706..e963771c4 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NamespacedClassSignature.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NamespacedClassSignature.js @@ -31,6 +31,31 @@ export async function createInstantiator(options, swift) { let _exports = null; let bjs = null; + const swiftClosureRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.unregistered) { return; } + instance?.exports?.bjs_release_swift_closure(state.pointer); + }); + const makeClosure = (pointer, file, line, func) => { + const state = { pointer, file, line, unregistered: false }; + const real = (...args) => { + if (state.unregistered) { + const bytes = new Uint8Array(memory.buffer, state.file >>> 0); + let length = 0; + while (bytes[length] !== 0) { length += 1; } + const fileID = decodeString(state.file, length); + throw new Error(`Attempted to call a released JSTypedClosure created at ${fileID}:${state.line}`); + } + return func(...args); + }; + real.__unregister = () => { + if (state.unregistered) { return; } + state.unregistered = true; + swiftClosureRegistry.unregister(state); + }; + swiftClosureRegistry.register(real, state, state); + return swift.memory.retain(real); + }; + return { /** @@ -204,6 +229,33 @@ export async function createInstantiator(options, swift) { return pointer || 0; } bjs["swift_js_closure_unregister"] = function(funcRef) {} + bjs["swift_js_closure_unregister"] = function(funcRef) { + const func = swift.memory.getObject(funcRef); + func.__unregister(); + } + bjs["invoke_js_callback_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC"] = function(callbackId, param0) { + try { + const callback = swift.memory.getObject(callbackId); + let ret = callback(_exports.Workshop.Bench.__construct(param0)); + return ret.pointer; + } catch (error) { + setException(error); + return 0 + } + } + bjs["make_swift_closure_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC = function(param0) { + const ret = instance.exports.invoke_swift_closure_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC(boxPtr, param0.pointer); + if (tmpRetException) { + const error = swift.memory.getObject(tmpRetException); + swift.memory.release(tmpRetException); + tmpRetException = undefined; + throw error; + } + return _exports.Workshop.Bench.__construct(ret); + }; + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC); + } // Wrapper functions for module: TestModule if (!importObject["TestModule"]) { importObject["TestModule"] = {}; @@ -293,6 +345,11 @@ export async function createInstantiator(options, swift) { const ret = instance.exports.bjs_makeBench(); return Bench.__construct(ret); }, + refitBench: function bjs_refitBench(bench, transform) { + const callbackId = swift.memory.retain(transform); + const ret = instance.exports.bjs_refitBench(bench.pointer, callbackId); + return Bench.__construct(ret); + }, Workshop: { Bench, }, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedTypeNameCollision.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedTypeNameCollision.d.ts new file mode 100644 index 000000000..13c22ea11 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedTypeNameCollision.d.ts @@ -0,0 +1,35 @@ +// 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`. + +export interface Entry { + identifier: number; +} +export namespace Catalog { + export interface Entry { + title: string; + } +} +export type Exports = { + takeEntry(entry: Entry): Entry; + takeCatalogEntry(entry: Catalog.Entry): Catalog.Entry; + Catalog: { + Entry: { + init(title: string): Catalog.Entry; + }, + }, + Entry: { + init(identifier: number): Entry; + }, +} +export type Imports = { +} +export function createInstantiator(options: { + imports: Imports; +}, swift: any): Promise<{ + addImports: (importObject: WebAssembly.Imports) => void; + setInstance: (instance: WebAssembly.Instance) => void; + createExports: (instance: WebAssembly.Instance) => Exports; +}>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedTypeNameCollision.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedTypeNameCollision.js new file mode 100644 index 000000000..1f4400ce9 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NestedTypeNameCollision.js @@ -0,0 +1,299 @@ +// 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`. + +export async function createInstantiator(options, swift) { + let instance; + let memory; + let setException; + let decodeString; + const textDecoder = new TextDecoder("utf-8"); + const textEncoder = new TextEncoder("utf-8"); + let tmpRetString; + let tmpRetBytes; + let tmpRetException; + let tmpRetOptionalBool; + let tmpRetOptionalInt; + let tmpRetOptionalFloat; + let tmpRetOptionalDouble; + let tmpRetOptionalHeapObject; + let strStack = []; + let i32Stack = []; + let i64Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; + let taStack = []; + const enumHelpers = {}; + const structHelpers = {}; + + let _exports = null; + let bjs = null; + const __bjs_createStructHelpers_M10TestModuleT7CatalogT5Entry = () => ({ + lower: (value) => { + const bytes = textEncoder.encode(value.title); + const id = swift.memory.retain(bytes); + i32Stack.push(bytes.length); + i32Stack.push(id); + }, + lift: () => { + const string = strStack.pop(); + return { title: string }; + } + }); + const __bjs_createStructHelpers_M10TestModuleT5Entry = () => ({ + lower: (value) => { + i32Stack.push((value.identifier | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return { identifier: int }; + } + }); + + return { + /** + * @param {WebAssembly.Imports} importObject + */ + addImports: (importObject, importsContext) => { + bjs = {}; + importObject["bjs"] = bjs; + bjs["swift_js_return_string"] = function(ptr, len) { + tmpRetString = decodeString(ptr, len); + } + bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { + const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); + bytes.set(source); + } + bjs["swift_js_make_js_string"] = function(ptr, len) { + return swift.memory.retain(decodeString(ptr, len)); + } + bjs["swift_js_init_memory_with_result"] = function(ptr, len) { + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); + target.set(tmpRetBytes); + tmpRetBytes = undefined; + } + bjs["swift_js_throw"] = function(id) { + tmpRetException = swift.memory.retainByRef(id); + } + bjs["swift_js_retain"] = function(id) { + return swift.memory.retainByRef(id); + } + bjs["swift_js_release"] = function(id) { + swift.memory.release(id); + } + bjs["swift_js_push_i32"] = function(v) { + i32Stack.push(v | 0); + } + bjs["swift_js_push_f32"] = function(v) { + f32Stack.push(Math.fround(v)); + } + bjs["swift_js_push_f64"] = function(v) { + f64Stack.push(v); + } + bjs["swift_js_push_string"] = function(ptr, len) { + const value = decodeString(ptr, len); + strStack.push(value); + } + bjs["swift_js_pop_i32"] = function() { + return i32Stack.pop(); + } + bjs["swift_js_pop_f32"] = function() { + return f32Stack.pop(); + } + bjs["swift_js_pop_f64"] = function() { + return f64Stack.pop(); + } + bjs["swift_js_push_pointer"] = function(pointer) { + ptrStack.push(pointer); + } + bjs["swift_js_pop_pointer"] = function() { + return ptrStack.pop(); + } + bjs["swift_js_push_i64"] = function(v) { + i64Stack.push(v); + } + bjs["swift_js_pop_i64"] = function() { + return i64Stack.pop(); + } + const taCtors = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array]; + bjs["swift_js_push_typed_array"] = function(kind, ptr, count) { + const Ctor = taCtors[kind]; + const byteLen = count * Ctor.BYTES_PER_ELEMENT; + const copy = memory.buffer.slice(ptr, ptr + byteLen); + taStack.push(Array.from(new Ctor(copy))); + } + bjs["swift_js_struct_lower_Catalog_Entry"] = function(objectId) { + structHelpers.M10TestModuleT7CatalogT5Entry.lower(swift.memory.getObject(objectId)); + } + bjs["swift_js_struct_lift_Catalog_Entry"] = function() { + const value = structHelpers.M10TestModuleT7CatalogT5Entry.lift(); + return swift.memory.retain(value); + } + bjs["swift_js_struct_lower_Entry"] = function(objectId) { + structHelpers.M10TestModuleT5Entry.lower(swift.memory.getObject(objectId)); + } + bjs["swift_js_struct_lift_Entry"] = function() { + const value = structHelpers.M10TestModuleT5Entry.lift(); + return swift.memory.retain(value); + } + bjs["bjs_core_register_type_handles"] = function() {}; + bjs["bjs_TestModule_register_type_handles"] = function() {}; + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } + bjs["swift_js_return_optional_bool"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalBool = null; + } else { + tmpRetOptionalBool = value !== 0; + } + } + bjs["swift_js_return_optional_int"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalInt = null; + } else { + tmpRetOptionalInt = value | 0; + } + } + bjs["swift_js_return_optional_float"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalFloat = null; + } else { + tmpRetOptionalFloat = Math.fround(value); + } + } + bjs["swift_js_return_optional_double"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalDouble = null; + } else { + tmpRetOptionalDouble = value; + } + } + bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = decodeString(ptr, len); + } + } + bjs["swift_js_return_optional_object"] = function(isSome, objectId) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = swift.memory.getObject(objectId); + } + } + bjs["swift_js_return_optional_heap_object"] = function(isSome, pointer) { + if (isSome === 0) { + tmpRetOptionalHeapObject = null; + } else { + tmpRetOptionalHeapObject = pointer; + } + } + bjs["swift_js_get_optional_int_presence"] = function() { + return tmpRetOptionalInt != null ? 1 : 0; + } + bjs["swift_js_get_optional_int_value"] = function() { + const value = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; + return value; + } + bjs["swift_js_get_optional_string"] = function() { + const str = tmpRetString; + tmpRetString = undefined; + if (str == null) { + return -1; + } else { + const bytes = textEncoder.encode(str); + tmpRetBytes = bytes; + return bytes.length; + } + } + bjs["swift_js_get_optional_float_presence"] = function() { + return tmpRetOptionalFloat != null ? 1 : 0; + } + bjs["swift_js_get_optional_float_value"] = function() { + const value = tmpRetOptionalFloat; + tmpRetOptionalFloat = undefined; + return value; + } + bjs["swift_js_get_optional_double_presence"] = function() { + return tmpRetOptionalDouble != null ? 1 : 0; + } + bjs["swift_js_get_optional_double_value"] = function() { + const value = tmpRetOptionalDouble; + tmpRetOptionalDouble = undefined; + return value; + } + bjs["swift_js_get_optional_heap_object_pointer"] = function() { + const pointer = tmpRetOptionalHeapObject; + tmpRetOptionalHeapObject = undefined; + return pointer || 0; + } + bjs["swift_js_closure_unregister"] = function(funcRef) {} + }, + setInstance: (i) => { + instance = i; + memory = instance.exports.memory; + + decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + + setException = (error) => { + instance.exports._swift_js_exception.value = swift.memory.retain(error) + } + }, + /** @param {WebAssembly.Instance} instance */ + createExports: (instance) => { + const js = swift.memory.heap; + const __bjs_helpers_M10TestModuleT7CatalogT5Entry = __bjs_createStructHelpers_M10TestModuleT7CatalogT5Entry(); + structHelpers.M10TestModuleT7CatalogT5Entry = __bjs_helpers_M10TestModuleT7CatalogT5Entry; + + const __bjs_helpers_M10TestModuleT5Entry = __bjs_createStructHelpers_M10TestModuleT5Entry(); + structHelpers.M10TestModuleT5Entry = __bjs_helpers_M10TestModuleT5Entry; + + const exports = { + takeEntry: function bjs_takeEntry(entry) { + structHelpers.M10TestModuleT5Entry.lower(entry); + instance.exports.bjs_takeEntry(); + const structValue = structHelpers.M10TestModuleT5Entry.lift(); + return structValue; + }, + takeCatalogEntry: function bjs_takeCatalogEntry(entry) { + structHelpers.M10TestModuleT7CatalogT5Entry.lower(entry); + instance.exports.bjs_takeCatalogEntry(); + const structValue = structHelpers.M10TestModuleT7CatalogT5Entry.lift(); + return structValue; + }, + Catalog: { + Entry: { + init: function(title) { + const titleBytes = textEncoder.encode(title); + const titleId = swift.memory.retain(titleBytes); + instance.exports.bjs_Catalog_Entry_init(titleId, titleBytes.length); + const structValue = structHelpers.M10TestModuleT7CatalogT5Entry.lift(); + return structValue; + }, + }, + }, + Entry: { + init: function(identifier) { + instance.exports.bjs_Entry_init(identifier); + const structValue = structHelpers.M10TestModuleT5Entry.lift(); + return structValue; + }, + }, + }; + _exports = exports; + return exports; + }, + } +} \ No newline at end of file From 59a62746895f6a2d5e4c68ff2e9d4c486415a73f Mon Sep 17 00:00:00 2001 From: William Taylor Date: Mon, 17 Aug 2026 16:03:35 +1000 Subject: [PATCH 48/50] =?UTF-8?q?BridgeJS:=20Don=E2=80=99t=20put=20dots=20?= =?UTF-8?q?in=20mangled=20name?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../BridgeJSSkeleton/BridgeJSSkeleton.swift | 18 ++++++---- .../NamespacedClassSignature.json | 2 +- .../NamespacedClassSignature.swift | 34 +++++++++---------- .../NamespacedClassSignature.js | 10 +++--- 4 files changed, 35 insertions(+), 29 deletions(-) diff --git a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift index 79d6b4b07..8aaa6d5cd 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSSkeleton/BridgeJSSkeleton.swift @@ -1987,11 +1987,11 @@ extension BridgeType { case .void: return "y" case .jsObject(let name): let typeName = name ?? "JSObject" - return "\(typeName.count)\(typeName)C" + return "\(Self.mangleQualifiedName(typeName))C" case .jsValue: return "7JSValueV" case .swiftHeapObject(let name): - return "\(name.count)\(name)C" + return "\(Self.mangleQualifiedName(name))C" case .unsafePointer(let ptr): func sanitize(_ s: String) -> String { s.filter { $0.isNumber || $0.isLetter } @@ -2016,11 +2016,11 @@ extension BridgeType { .rawValueEnum(let name, _), .associatedValueEnum(let name), .namespaceEnum(let name): - return "\(name.count)\(name)O" + return "\(Self.mangleQualifiedName(name))O" case .swiftProtocol(let name): - return "\(name.count)\(name)P" + return "\(Self.mangleQualifiedName(name))P" case .swiftStruct(let name): - return "\(name.count)\(name)V" + return "\(Self.mangleQualifiedName(name))V" case .closure(let signature, let useJSTypedClosure): let params = signature.parameters.isEmpty @@ -2037,12 +2037,18 @@ extension BridgeType { case .alias(let name, _): // `name` is the namespace-qualified swiftCallName (unique), so the underlying // representation isn't mangled in - aliases bridge via their JS type's ABI. - return "Al\(name.count)\(name)" + return "Al\(Self.mangleQualifiedName(name))" case .generic(let name): return "\(name.count)\(name)T" } } + /// Transforms a namespace-qualified name into a valid identifier by removing + /// each dot and prefixing each component with length (e.g. `Workshop.Bench` -> `8Workshop5Bench`). + private static func mangleQualifiedName(_ name: String) -> String { + name.split(separator: ".").map { "\($0.count)\($0)" }.joined() + } + /// Determines if an optional type requires side-channel communication for protocol property returns /// /// Side channels are needed when the wrapped type cannot be directly returned via WASM, diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NamespacedClassSignature.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NamespacedClassSignature.json index e4568f101..e6ea49859 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NamespacedClassSignature.json +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NamespacedClassSignature.json @@ -91,7 +91,7 @@ "_0" : { "isAsync" : false, "isThrows" : false, - "mangleName" : "10TestModule14Workshop.BenchC_14Workshop.BenchC", + "mangleName" : "10TestModule8Workshop5BenchC_8Workshop5BenchC", "moduleName" : "TestModule", "parameters" : [ { diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NamespacedClassSignature.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NamespacedClassSignature.swift index 511d0f75c..bff3007b7 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NamespacedClassSignature.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/NamespacedClassSignature.swift @@ -1,35 +1,35 @@ #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC") -fileprivate func invoke_js_callback_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC_extern(_ callback: Int32, _ param0: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer +@_extern(wasm, module: "bjs", name: "invoke_js_callback_TestModule_10TestModule8Workshop5BenchC_8Workshop5BenchC") +fileprivate func invoke_js_callback_TestModule_10TestModule8Workshop5BenchC_8Workshop5BenchC_extern(_ callback: Int32, _ param0: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer #else -fileprivate func invoke_js_callback_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC_extern(_ callback: Int32, _ param0: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { +fileprivate func invoke_js_callback_TestModule_10TestModule8Workshop5BenchC_8Workshop5BenchC_extern(_ callback: Int32, _ param0: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC(_ callback: Int32, _ param0: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { - return invoke_js_callback_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC_extern(callback, param0) +@inline(never) fileprivate func invoke_js_callback_TestModule_10TestModule8Workshop5BenchC_8Workshop5BenchC(_ callback: Int32, _ param0: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { + return invoke_js_callback_TestModule_10TestModule8Workshop5BenchC_8Workshop5BenchC_extern(callback, param0) } #if arch(wasm32) -@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC") -fileprivate func make_swift_closure_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 +@_extern(wasm, module: "bjs", name: "make_swift_closure_TestModule_10TestModule8Workshop5BenchC_8Workshop5BenchC") +fileprivate func make_swift_closure_TestModule_10TestModule8Workshop5BenchC_8Workshop5BenchC_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 #else -fileprivate func make_swift_closure_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { +fileprivate func make_swift_closure_TestModule_10TestModule8Workshop5BenchC_8Workshop5BenchC_extern(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { fatalError("Only available on WebAssembly") } #endif -@inline(never) fileprivate func make_swift_closure_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { - return make_swift_closure_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC_extern(boxPtr, file, line) +@inline(never) fileprivate func make_swift_closure_TestModule_10TestModule8Workshop5BenchC_8Workshop5BenchC(_ boxPtr: UnsafeMutableRawPointer, _ file: UnsafePointer, _ line: UInt32) -> Int32 { + return make_swift_closure_TestModule_10TestModule8Workshop5BenchC_8Workshop5BenchC_extern(boxPtr, file, line) } -private enum _BJS_Closure_10TestModule14Workshop.BenchC_14Workshop.BenchC { +private enum _BJS_Closure_10TestModule8Workshop5BenchC_8Workshop5BenchC { static func bridgeJSLift(_ callbackId: Int32) -> (Workshop.Bench) -> Workshop.Bench { let callback = JSObject.bridgeJSLiftParameter(callbackId) return { [callback] param0 in #if arch(wasm32) let param0Pointer = param0.bridgeJSLowerParameter() let callbackValue = callback.bridgeJSLowerParameter() - let ret = invoke_js_callback_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC(callbackValue, param0Pointer) + let ret = invoke_js_callback_TestModule_10TestModule8Workshop5BenchC_8Workshop5BenchC(callbackValue, param0Pointer) return Workshop.Bench.bridgeJSLiftReturn(ret) #else fatalError("Only available on WebAssembly") @@ -41,7 +41,7 @@ private enum _BJS_Closure_10TestModule14Workshop.BenchC_14Workshop.BenchC { extension JSTypedClosure where Signature == (Workshop.Bench) -> Workshop.Bench { init(fileID: StaticString = #fileID, line: UInt32 = #line, _ body: @escaping (Workshop.Bench) -> Workshop.Bench) { self.init( - makeClosure: make_swift_closure_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC, + makeClosure: make_swift_closure_TestModule_10TestModule8Workshop5BenchC_8Workshop5BenchC, body: body, fileID: fileID, line: line @@ -49,9 +49,9 @@ extension JSTypedClosure where Signature == (Workshop.Bench) -> Workshop.Bench { } } -@_expose(wasm, "invoke_swift_closure_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC") -@_cdecl("invoke_swift_closure_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC") -public func _invoke_swift_closure_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC(_ boxPtr: UnsafeMutableRawPointer, _ param0: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { +@_expose(wasm, "invoke_swift_closure_TestModule_10TestModule8Workshop5BenchC_8Workshop5BenchC") +@_cdecl("invoke_swift_closure_TestModule_10TestModule8Workshop5BenchC_8Workshop5BenchC") +public func _invoke_swift_closure_TestModule_10TestModule8Workshop5BenchC_8Workshop5BenchC(_ boxPtr: UnsafeMutableRawPointer, _ param0: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer { #if arch(wasm32) let closure = Unmanaged<_BridgeJSTypedClosureBox<(Workshop.Bench) -> Workshop.Bench>>.fromOpaque(boxPtr).takeUnretainedValue().closure let result = closure(Workshop.Bench.bridgeJSLiftParameter(param0)) @@ -76,7 +76,7 @@ public func _bjs_makeBench() -> UnsafeMutableRawPointer { @_cdecl("bjs_refitBench") public func _bjs_refitBench(_ bench: UnsafeMutableRawPointer, _ transform: Int32) -> UnsafeMutableRawPointer { #if arch(wasm32) - let ret = refitBench(_: Workshop.Bench.bridgeJSLiftParameter(bench), _: _BJS_Closure_10TestModule14Workshop.BenchC_14Workshop.BenchC.bridgeJSLift(transform)) + let ret = refitBench(_: Workshop.Bench.bridgeJSLiftParameter(bench), _: _BJS_Closure_10TestModule8Workshop5BenchC_8Workshop5BenchC.bridgeJSLift(transform)) return ret.bridgeJSLowerReturn() #else fatalError("Only available on WebAssembly") diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NamespacedClassSignature.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NamespacedClassSignature.js index e963771c4..082d85f65 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NamespacedClassSignature.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/NamespacedClassSignature.js @@ -233,7 +233,7 @@ export async function createInstantiator(options, swift) { const func = swift.memory.getObject(funcRef); func.__unregister(); } - bjs["invoke_js_callback_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC"] = function(callbackId, param0) { + bjs["invoke_js_callback_TestModule_10TestModule8Workshop5BenchC_8Workshop5BenchC"] = function(callbackId, param0) { try { const callback = swift.memory.getObject(callbackId); let ret = callback(_exports.Workshop.Bench.__construct(param0)); @@ -243,9 +243,9 @@ export async function createInstantiator(options, swift) { return 0 } } - bjs["make_swift_closure_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC"] = function(boxPtr, file, line) { - const lower_closure_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC = function(param0) { - const ret = instance.exports.invoke_swift_closure_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC(boxPtr, param0.pointer); + bjs["make_swift_closure_TestModule_10TestModule8Workshop5BenchC_8Workshop5BenchC"] = function(boxPtr, file, line) { + const lower_closure_TestModule_10TestModule8Workshop5BenchC_8Workshop5BenchC = function(param0) { + const ret = instance.exports.invoke_swift_closure_TestModule_10TestModule8Workshop5BenchC_8Workshop5BenchC(boxPtr, param0.pointer); if (tmpRetException) { const error = swift.memory.getObject(tmpRetException); swift.memory.release(tmpRetException); @@ -254,7 +254,7 @@ export async function createInstantiator(options, swift) { } return _exports.Workshop.Bench.__construct(ret); }; - return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModule14Workshop.BenchC_14Workshop.BenchC); + return makeClosure(boxPtr, file, line, lower_closure_TestModule_10TestModule8Workshop5BenchC_8Workshop5BenchC); } // Wrapper functions for module: TestModule if (!importObject["TestModule"]) { From 372fce2e04e829827e0b467a08d7c8dadb160eb5 Mon Sep 17 00:00:00 2001 From: Krzysztof Rodak Date: Mon, 17 Aug 2026 13:44:35 +0200 Subject: [PATCH 49/50] BridgeJS: Resolve qualified types relative to lexical scope --- .../BridgeJSCore/SwiftToSkeleton.swift | 4 +- .../BridgeJSCore/TypeDeclResolver.swift | 45 +- .../MacroSwift/RelativeQualifiedTypes.swift | 37 ++ .../RelativeQualifiedTypes.json | 239 ++++++++++ .../RelativeQualifiedTypes.swift | 399 ++++++++++++++++ .../RelativeQualifiedTypes.d.ts | 70 +++ .../RelativeQualifiedTypes.js | 440 ++++++++++++++++++ 7 files changed, 1211 insertions(+), 23 deletions(-) create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/RelativeQualifiedTypes.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/RelativeQualifiedTypes.json create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/RelativeQualifiedTypes.swift create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/RelativeQualifiedTypes.d.ts create mode 100644 Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/RelativeQualifiedTypes.js diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift index fb9cee01c..fb81d9089 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/SwiftToSkeleton.swift @@ -818,7 +818,7 @@ public final class SwiftToSkeleton { while let parent = currentNode { if let extensionDecl = parent.as(ExtensionDeclSyntax.self) { - if let extendedDecl = typeDeclResolver.resolve(extensionDecl.extendedType), + if let extendedDecl = typeDeclResolver.resolveExtensionTarget(extensionDecl.extendedType), visitedExtendedTypes.insert(extendedDecl.id).inserted { declarations.append(Syntax(extendedDecl)) @@ -1996,7 +1996,7 @@ private final class ExportSwiftAPICollector: SyntaxAnyVisitor { /// Walks extension members under the matching type’s state, returning whether the type was found. func resolveExtension(_ ext: ExtensionDeclSyntax) -> Bool { - guard let extendedDecl = parent.typeDeclResolver.resolve(ext.extendedType) else { + guard let extendedDecl = parent.typeDeclResolver.resolveExtensionTarget(ext.extendedType) else { return false } let swiftCallName = parent.computeSwiftCallName(for: extendedDecl, itemName: extendedDecl.name.text) diff --git a/Plugins/BridgeJS/Sources/BridgeJSCore/TypeDeclResolver.swift b/Plugins/BridgeJS/Sources/BridgeJSCore/TypeDeclResolver.swift index e5d77939b..4df546b8a 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSCore/TypeDeclResolver.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSCore/TypeDeclResolver.swift @@ -92,7 +92,7 @@ class TypeDeclResolver { } /// Builds the type name scope for a given type usage - private func buildScope(type: IdentifierTypeSyntax) -> QualifiedName { + private func buildScope(type: TypeSyntax) -> QualifiedName { var innerToOuter: [String] = [] var context: SyntaxProtocol = type while let parent = context.parent { @@ -108,25 +108,29 @@ class TypeDeclResolver { return innerToOuter.reversed() } - /// Looks up a qualified name of a type declaration by its unqualified type usage + /// Looks up a qualified name of a type declaration relative to its lexical scope /// Returns the qualified name hierarchy of the type declaration - /// If the type declaration is not found, returns the unqualified name - private func tryQualify(type: IdentifierTypeSyntax) -> QualifiedName { - let name = type.name.text + /// If the type declaration is not found, returns the original qualified name + private func tryQualify(type: TypeSyntax) -> QualifiedName? { + guard let components = type.qualifiedComponents else { + return nil + } let scope = buildScope(type: type) /// Search for the type declaration from the innermost scope to the outermost scope for i in (0...scope.count).reversed() { - let qualifiedName = Array(scope[0.. TypeDecl? { - let qualifiedName = tryQualify(type: type) + guard let qualifiedName = tryQualify(type: TypeSyntax(type)) else { + return nil + } return typeDeclByQualifiedName[qualifiedName] } @@ -139,36 +143,35 @@ class TypeDeclResolver { /// /// Supported inputs: /// - IdentifierTypeSyntax (e.g. `Method`) — resolved relative to the lexical scope, preferring the innermost enclosing type. - /// - MemberTypeSyntax (e.g. `Networking.API.Method`) — resolved by recursively building the fully qualified name. + /// - MemberTypeSyntax (e.g. `Networking.API.Method`) — resolved relative to the lexical scope before falling back to the fully qualified name. /// /// Resolution strategy: - /// 1. If the node is IdentifierTypeSyntax, call `lookupType(for:)` which attempts scope-aware qualification via `tryQualify`. - /// 2. Otherwise, attempt to build a fully qualified name with `qualifiedComponents` and look it up with `lookupType(fullyQualified:)`. + /// Build the qualified name with `qualifiedComponents`, then attempt scope-aware qualification via `tryQualify`. /// /// - Parameter type: The SwiftSyntax node representing a type appearance in source code. /// - Returns: The nominal declaration (enum/class/actor/struct) if found, otherwise nil. func resolve(_ type: TypeSyntax) -> TypeDecl? { - if let id = type.as(IdentifierTypeSyntax.self) { - return lookupType(for: id) - } - if let components = type.qualifiedComponents { - return lookupType(fullyQualified: components) + if let qualifiedName = tryQualify(type: type) { + return lookupType(fullyQualified: qualifiedName) } return nil } + func resolveExtensionTarget(_ type: TypeSyntax) -> TypeDecl? { + guard let qualifiedName = type.qualifiedComponents else { + return nil + } + return lookupType(fullyQualified: qualifiedName) + } + /// Resolves a type usage node to a type alias declaration /// /// - Parameter type: The SwiftSyntax node representing a type appearance in source code. /// - Returns: The type alias declaration if found, otherwise nil. func resolveTypeAlias(_ type: TypeSyntax) -> TypeAliasDeclSyntax? { - if let id = type.as(IdentifierTypeSyntax.self) { - let qualifiedName = tryQualify(type: id) + if let qualifiedName = tryQualify(type: type) { return typeAliasByQualifiedName[qualifiedName] } - if let components = type.qualifiedComponents { - return typeAliasByQualifiedName[components] - } return nil } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/RelativeQualifiedTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/RelativeQualifiedTypes.swift new file mode 100644 index 000000000..b1eae64dd --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/Inputs/MacroSwift/RelativeQualifiedTypes.swift @@ -0,0 +1,37 @@ +@JS class Library { + @JS struct Shelf { + @JS struct Divider { + var slot: Int + + @JS init(slot: Int) { + self.slot = slot + } + } + } + + @JS init() {} +} + +extension Library { + @JS func divider(_ value: Shelf.Divider) -> Shelf.Divider { + value + } +} + +@JS class Outer { + @JS struct Inner { + @JS struct Outer { + @JS struct Inner { + @JS init() {} + } + } + + @JS init() {} + } + + @JS init() {} +} + +extension Outer.Inner { + @JS func marker() -> Int { 1 } +} diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/RelativeQualifiedTypes.json b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/RelativeQualifiedTypes.json new file mode 100644 index 000000000..0872c6d79 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/RelativeQualifiedTypes.json @@ -0,0 +1,239 @@ +{ + "exported" : { + "aliases" : [ + + ], + "classes" : [ + { + "constructor" : { + "abiName" : "bjs_Library_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + { + "abiName" : "bjs_Library_divider", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "divider", + "parameters" : [ + { + "label" : "_", + "name" : "value", + "type" : { + "swiftStruct" : { + "_0" : "Library.Shelf.Divider" + } + } + } + ], + "returnType" : { + "swiftStruct" : { + "_0" : "Library.Shelf.Divider" + } + } + } + ], + "name" : "Library", + "properties" : [ + + ], + "swiftCallName" : "Library" + }, + { + "constructor" : { + "abiName" : "bjs_Outer_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + + ], + "name" : "Outer", + "properties" : [ + + ], + "swiftCallName" : "Outer" + } + ], + "enums" : [ + + ], + "exposeToGlobal" : false, + "functions" : [ + + ], + "protocols" : [ + + ], + "structs" : [ + { + "methods" : [ + + ], + "name" : "Shelf", + "namespace" : [ + "Library" + ], + "properties" : [ + + ], + "swiftCallName" : "Library.Shelf" + }, + { + "constructor" : { + "abiName" : "bjs_Library_Shelf_Divider_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + { + "label" : "slot", + "name" : "slot", + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ] + }, + "methods" : [ + + ], + "name" : "Divider", + "namespace" : [ + "Library", + "Shelf" + ], + "properties" : [ + { + "isReadonly" : true, + "isStatic" : false, + "name" : "slot", + "namespace" : [ + "Library", + "Shelf" + ], + "type" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "swiftCallName" : "Library.Shelf.Divider" + }, + { + "constructor" : { + "abiName" : "bjs_Outer_Inner_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + { + "abiName" : "bjs_Outer_Inner_marker", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "name" : "marker", + "parameters" : [ + + ], + "returnType" : { + "integer" : { + "_0" : { + "isSigned" : true, + "width" : "word" + } + } + } + } + ], + "name" : "Inner", + "namespace" : [ + "Outer" + ], + "properties" : [ + + ], + "swiftCallName" : "Outer.Inner" + }, + { + "methods" : [ + + ], + "name" : "Outer", + "namespace" : [ + "Outer", + "Inner" + ], + "properties" : [ + + ], + "swiftCallName" : "Outer.Inner.Outer" + }, + { + "constructor" : { + "abiName" : "bjs_Outer_Inner_Outer_Inner_init", + "effects" : { + "isAsync" : false, + "isStatic" : false, + "isThrows" : false + }, + "parameters" : [ + + ] + }, + "methods" : [ + + ], + "name" : "Inner", + "namespace" : [ + "Outer", + "Inner", + "Outer" + ], + "properties" : [ + + ], + "swiftCallName" : "Outer.Inner.Outer.Inner" + } + ] + }, + "moduleName" : "TestModule", + "usedExternalModules" : [ + + ] +} \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/RelativeQualifiedTypes.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/RelativeQualifiedTypes.swift new file mode 100644 index 000000000..0a6b272e9 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSCodegenTests/RelativeQualifiedTypes.swift @@ -0,0 +1,399 @@ +extension Library.Shelf: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Library.Shelf { + return Library.Shelf() + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_Library_Shelf(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Library_Shelf())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Library_Shelf") +fileprivate func _bjs_struct_lower_Library_Shelf_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_Library_Shelf_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_Library_Shelf(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Library_Shelf_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Library_Shelf") +fileprivate func _bjs_struct_lift_Library_Shelf_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_Library_Shelf_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_Library_Shelf() -> Int32 { + return _bjs_struct_lift_Library_Shelf_extern() +} + +extension Library.Shelf.Divider: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Library.Shelf.Divider { + let slot = Int.bridgeJSStackPop() + return Library.Shelf.Divider(slot: slot) + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + self.slot.bridgeJSStackPush() + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_Library_Shelf_Divider(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Library_Shelf_Divider())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Library_Shelf_Divider") +fileprivate func _bjs_struct_lower_Library_Shelf_Divider_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_Library_Shelf_Divider_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_Library_Shelf_Divider(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Library_Shelf_Divider_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Library_Shelf_Divider") +fileprivate func _bjs_struct_lift_Library_Shelf_Divider_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_Library_Shelf_Divider_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_Library_Shelf_Divider() -> Int32 { + return _bjs_struct_lift_Library_Shelf_Divider_extern() +} + +@_expose(wasm, "bjs_Library_Shelf_Divider_init") +@_cdecl("bjs_Library_Shelf_Divider_init") +public func _bjs_Library_Shelf_Divider_init(_ slot: Int32) -> Void { + #if arch(wasm32) + let ret = Library.Shelf.Divider(slot: Int.bridgeJSLiftParameter(slot)) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension Outer.Inner: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Outer.Inner { + return Outer.Inner() + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_Outer_Inner(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Outer_Inner())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Outer_Inner") +fileprivate func _bjs_struct_lower_Outer_Inner_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_Outer_Inner_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_Outer_Inner(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Outer_Inner_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Outer_Inner") +fileprivate func _bjs_struct_lift_Outer_Inner_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_Outer_Inner_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_Outer_Inner() -> Int32 { + return _bjs_struct_lift_Outer_Inner_extern() +} + +@_expose(wasm, "bjs_Outer_Inner_init") +@_cdecl("bjs_Outer_Inner_init") +public func _bjs_Outer_Inner_init() -> Void { + #if arch(wasm32) + let ret = Outer.Inner() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Outer_Inner_marker") +@_cdecl("bjs_Outer_Inner_marker") +public func _bjs_Outer_Inner_marker() -> Int32 { + #if arch(wasm32) + let ret = Outer.Inner.bridgeJSLiftParameter().marker() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension Outer.Inner.Outer: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Outer.Inner.Outer { + return Outer.Inner.Outer() + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_Outer_Inner_Outer(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Outer_Inner_Outer())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Outer_Inner_Outer") +fileprivate func _bjs_struct_lower_Outer_Inner_Outer_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_Outer_Inner_Outer_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_Outer_Inner_Outer(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Outer_Inner_Outer_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Outer_Inner_Outer") +fileprivate func _bjs_struct_lift_Outer_Inner_Outer_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_Outer_Inner_Outer_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_Outer_Inner_Outer() -> Int32 { + return _bjs_struct_lift_Outer_Inner_Outer_extern() +} + +extension Outer.Inner.Outer.Inner: _BridgedSwiftStruct { + @_spi(BridgeJS) @_transparent public static func bridgeJSStackPop() -> Outer.Inner.Outer.Inner { + return Outer.Inner.Outer.Inner() + } + + @_spi(BridgeJS) @_transparent public consuming func bridgeJSStackPush() { + } + + init(unsafelyCopying jsObject: JSObject) { + _bjs_struct_lower_Outer_Inner_Outer_Inner(jsObject.bridgeJSLowerParameter()) + self = Self.bridgeJSStackPop() + } + + func toJSObject() -> JSObject { + let __bjs_self = self + __bjs_self.bridgeJSStackPush() + return JSObject(id: UInt32(bitPattern: _bjs_struct_lift_Outer_Inner_Outer_Inner())) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lower_Outer_Inner_Outer_Inner") +fileprivate func _bjs_struct_lower_Outer_Inner_Outer_Inner_extern(_ objectId: Int32) -> Void +#else +fileprivate func _bjs_struct_lower_Outer_Inner_Outer_Inner_extern(_ objectId: Int32) -> Void { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lower_Outer_Inner_Outer_Inner(_ objectId: Int32) -> Void { + return _bjs_struct_lower_Outer_Inner_Outer_Inner_extern(objectId) +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "swift_js_struct_lift_Outer_Inner_Outer_Inner") +fileprivate func _bjs_struct_lift_Outer_Inner_Outer_Inner_extern() -> Int32 +#else +fileprivate func _bjs_struct_lift_Outer_Inner_Outer_Inner_extern() -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_struct_lift_Outer_Inner_Outer_Inner() -> Int32 { + return _bjs_struct_lift_Outer_Inner_Outer_Inner_extern() +} + +@_expose(wasm, "bjs_Outer_Inner_Outer_Inner_init") +@_cdecl("bjs_Outer_Inner_Outer_Inner_init") +public func _bjs_Outer_Inner_Outer_Inner_init() -> Void { + #if arch(wasm32) + let ret = Outer.Inner.Outer.Inner() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Library_init") +@_cdecl("bjs_Library_init") +public func _bjs_Library_init() -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = Library() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Library_divider") +@_cdecl("bjs_Library_divider") +public func _bjs_Library_divider(_ _self: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + let ret = Library.bridgeJSLiftParameter(_self).divider(_: Library.Shelf.Divider.bridgeJSLiftParameter()) + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Library_deinit") +@_cdecl("bjs_Library_deinit") +public func _bjs_Library_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension Library: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_Library_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_Library_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_Library_wrap") +fileprivate func _bjs_Library_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_Library_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_Library_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Library_wrap_extern(pointer) +} + +@_expose(wasm, "bjs_Outer_init") +@_cdecl("bjs_Outer_init") +public func _bjs_Outer_init() -> UnsafeMutableRawPointer { + #if arch(wasm32) + let ret = Outer() + return ret.bridgeJSLowerReturn() + #else + fatalError("Only available on WebAssembly") + #endif +} + +@_expose(wasm, "bjs_Outer_deinit") +@_cdecl("bjs_Outer_deinit") +public func _bjs_Outer_deinit(_ pointer: UnsafeMutableRawPointer) -> Void { + #if arch(wasm32) + Unmanaged.fromOpaque(pointer).release() + #else + fatalError("Only available on WebAssembly") + #endif +} + +extension Outer: ConvertibleToJSValue, _BridgedSwiftHeapObject, _BridgedSwiftProtocolExportable { + var jsValue: JSValue { + return .object(JSObject(id: UInt32(bitPattern: _bjs_Outer_wrap(Unmanaged.passRetained(self).toOpaque())))) + } + consuming func bridgeJSLowerAsProtocolReturn() -> Int32 { + _bjs_Outer_wrap(Unmanaged.passRetained(self).toOpaque()) + } +} + +#if arch(wasm32) +@_extern(wasm, module: "TestModule", name: "bjs_Outer_wrap") +fileprivate func _bjs_Outer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 +#else +fileprivate func _bjs_Outer_wrap_extern(_ pointer: UnsafeMutableRawPointer) -> Int32 { + fatalError("Only available on WebAssembly") +} +#endif +@inline(never) fileprivate func _bjs_Outer_wrap(_ pointer: UnsafeMutableRawPointer) -> Int32 { + return _bjs_Outer_wrap_extern(pointer) +} + +extension Library.Shelf: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Library.Shelf.bridgeJSMakeTypeHandle() +} + +extension Library.Shelf.Divider: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Library.Shelf.Divider.bridgeJSMakeTypeHandle() +} + +extension Outer.Inner: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Outer.Inner.bridgeJSMakeTypeHandle() +} + +extension Outer.Inner.Outer: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Outer.Inner.Outer.bridgeJSMakeTypeHandle() +} + +extension Outer.Inner.Outer.Inner: BridgedSwiftGenericBridgeable { + @_spi(BridgeJS) public static let bridgeJSTypeHandle = Outer.Inner.Outer.Inner.bridgeJSMakeTypeHandle() +} + +#if arch(wasm32) +@_extern(wasm, module: "bjs", name: "bjs_TestModule_register_type_handles") +fileprivate func _bjs_TestModule_register_type_handles_extern(_ base: UnsafePointer?, _ count: Int32) + +@_expose(wasm, "bjs_TestModule_register_type_handles") +public func _bjs_TestModule_register_type_handles() { + let typeIds: [Int32] = [ + Library.Shelf.bridgeJSTypeID, + Library.Shelf.Divider.bridgeJSTypeID, + Outer.Inner.bridgeJSTypeID, + Outer.Inner.Outer.bridgeJSTypeID, + Outer.Inner.Outer.Inner.bridgeJSTypeID, + ] + typeIds.withUnsafeBufferPointer { buffer in + _bjs_TestModule_register_type_handles_extern(buffer.baseAddress, Int32(buffer.count)) + } +} +#endif \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/RelativeQualifiedTypes.d.ts b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/RelativeQualifiedTypes.d.ts new file mode 100644 index 000000000..1297973a9 --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/RelativeQualifiedTypes.d.ts @@ -0,0 +1,70 @@ +// 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`. + +export namespace Library { + export interface Shelf { + } + export namespace Shelf { + export interface Divider { + slot: number; + } + } +} +export namespace Outer { + export interface Inner { + marker(): number; + } + export namespace Inner { + export interface Outer { + } + export namespace Outer { + export interface Inner { + } + } + } +} +/// Represents a Swift heap object like a class instance or an actor instance. +export interface SwiftHeapObject { + /// Release the heap object. + /// + /// Note: Calling this method will release the heap object and it will no longer be accessible. + release(): void; +} +export interface Library extends SwiftHeapObject { + divider(value: Library.Shelf.Divider): Library.Shelf.Divider; +} +export interface Outer extends SwiftHeapObject { +} +export type Exports = { + Library: { + new(): Library; + Shelf: { + Divider: { + init(slot: number): Library.Shelf.Divider; + }, + }, + }, + Outer: { + new(): Outer; + Inner: { + init(): Outer.Inner; + Outer: { + Inner: { + init(): Outer.Inner.Outer.Inner; + }, + }, + }, + }, +} +export type Imports = { +} +export function createInstantiator(options: { + imports: Imports; +}, swift: any): Promise<{ + addImports: (importObject: WebAssembly.Imports) => void; + setInstance: (instance: WebAssembly.Instance) => void; + createExports: (instance: WebAssembly.Instance) => Exports; +}>; \ No newline at end of file diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/RelativeQualifiedTypes.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/RelativeQualifiedTypes.js new file mode 100644 index 000000000..2765d709f --- /dev/null +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/RelativeQualifiedTypes.js @@ -0,0 +1,440 @@ +// 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`. + +export async function createInstantiator(options, swift) { + let instance; + let memory; + let setException; + let decodeString; + const textDecoder = new TextDecoder("utf-8"); + const textEncoder = new TextEncoder("utf-8"); + let tmpRetString; + let tmpRetBytes; + let tmpRetException; + let tmpRetOptionalBool; + let tmpRetOptionalInt; + let tmpRetOptionalFloat; + let tmpRetOptionalDouble; + let tmpRetOptionalHeapObject; + let strStack = []; + let i32Stack = []; + let i64Stack = []; + let f32Stack = []; + let f64Stack = []; + let ptrStack = []; + let taStack = []; + const enumHelpers = {}; + const structHelpers = {}; + + let _exports = null; + let bjs = null; + const __bjs_createStructHelpers_M10TestModuleT7LibraryT5Shelf = () => ({ + lower: (value) => { + }, + lift: () => { + return { }; + } + }); + const __bjs_createStructHelpers_M10TestModuleT7LibraryT5ShelfT7Divider = () => ({ + lower: (value) => { + i32Stack.push((value.slot | 0)); + }, + lift: () => { + const int = i32Stack.pop(); + return { slot: int }; + } + }); + const __bjs_createStructHelpers_M10TestModuleT5OuterT5Inner = () => ({ + lower: (value) => { + }, + lift: () => { + const instance1 = { }; + instance1.marker = function() { + structHelpers.M10TestModuleT5OuterT5Inner.lower(this); + const ret = instance.exports.bjs_Outer_Inner_marker(); + return ret; + }.bind(instance1); + return instance1; + } + }); + const __bjs_createStructHelpers_M10TestModuleT5OuterT5InnerT5Outer = () => ({ + lower: (value) => { + }, + lift: () => { + return { }; + } + }); + const __bjs_createStructHelpers_M10TestModuleT5OuterT5InnerT5OuterT5Inner = () => ({ + lower: (value) => { + }, + lift: () => { + return { }; + } + }); + + return { + /** + * @param {WebAssembly.Imports} importObject + */ + addImports: (importObject, importsContext) => { + bjs = {}; + importObject["bjs"] = bjs; + bjs["swift_js_return_string"] = function(ptr, len) { + tmpRetString = decodeString(ptr, len); + } + bjs["swift_js_init_memory"] = function(sourceId, bytesPtr) { + const source = swift.memory.getObject(sourceId); + swift.memory.release(sourceId); + const bytes = new Uint8Array(memory.buffer, bytesPtr >>> 0); + bytes.set(source); + } + bjs["swift_js_make_js_string"] = function(ptr, len) { + return swift.memory.retain(decodeString(ptr, len)); + } + bjs["swift_js_init_memory_with_result"] = function(ptr, len) { + const target = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); + target.set(tmpRetBytes); + tmpRetBytes = undefined; + } + bjs["swift_js_throw"] = function(id) { + tmpRetException = swift.memory.retainByRef(id); + } + bjs["swift_js_retain"] = function(id) { + return swift.memory.retainByRef(id); + } + bjs["swift_js_release"] = function(id) { + swift.memory.release(id); + } + bjs["swift_js_push_i32"] = function(v) { + i32Stack.push(v | 0); + } + bjs["swift_js_push_f32"] = function(v) { + f32Stack.push(Math.fround(v)); + } + bjs["swift_js_push_f64"] = function(v) { + f64Stack.push(v); + } + bjs["swift_js_push_string"] = function(ptr, len) { + const value = decodeString(ptr, len); + strStack.push(value); + } + bjs["swift_js_pop_i32"] = function() { + return i32Stack.pop(); + } + bjs["swift_js_pop_f32"] = function() { + return f32Stack.pop(); + } + bjs["swift_js_pop_f64"] = function() { + return f64Stack.pop(); + } + bjs["swift_js_push_pointer"] = function(pointer) { + ptrStack.push(pointer); + } + bjs["swift_js_pop_pointer"] = function() { + return ptrStack.pop(); + } + bjs["swift_js_push_i64"] = function(v) { + i64Stack.push(v); + } + bjs["swift_js_pop_i64"] = function() { + return i64Stack.pop(); + } + const taCtors = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array]; + bjs["swift_js_push_typed_array"] = function(kind, ptr, count) { + const Ctor = taCtors[kind]; + const byteLen = count * Ctor.BYTES_PER_ELEMENT; + const copy = memory.buffer.slice(ptr, ptr + byteLen); + taStack.push(Array.from(new Ctor(copy))); + } + bjs["swift_js_struct_lower_Library_Shelf"] = function(objectId) { + structHelpers.M10TestModuleT7LibraryT5Shelf.lower(swift.memory.getObject(objectId)); + } + bjs["swift_js_struct_lift_Library_Shelf"] = function() { + const value = structHelpers.M10TestModuleT7LibraryT5Shelf.lift(); + return swift.memory.retain(value); + } + bjs["swift_js_struct_lower_Library_Shelf_Divider"] = function(objectId) { + structHelpers.M10TestModuleT7LibraryT5ShelfT7Divider.lower(swift.memory.getObject(objectId)); + } + bjs["swift_js_struct_lift_Library_Shelf_Divider"] = function() { + const value = structHelpers.M10TestModuleT7LibraryT5ShelfT7Divider.lift(); + return swift.memory.retain(value); + } + bjs["swift_js_struct_lower_Outer_Inner"] = function(objectId) { + structHelpers.M10TestModuleT5OuterT5Inner.lower(swift.memory.getObject(objectId)); + } + bjs["swift_js_struct_lift_Outer_Inner"] = function() { + const value = structHelpers.M10TestModuleT5OuterT5Inner.lift(); + return swift.memory.retain(value); + } + bjs["swift_js_struct_lower_Outer_Inner_Outer"] = function(objectId) { + structHelpers.M10TestModuleT5OuterT5InnerT5Outer.lower(swift.memory.getObject(objectId)); + } + bjs["swift_js_struct_lift_Outer_Inner_Outer"] = function() { + const value = structHelpers.M10TestModuleT5OuterT5InnerT5Outer.lift(); + return swift.memory.retain(value); + } + bjs["swift_js_struct_lower_Outer_Inner_Outer_Inner"] = function(objectId) { + structHelpers.M10TestModuleT5OuterT5InnerT5OuterT5Inner.lower(swift.memory.getObject(objectId)); + } + bjs["swift_js_struct_lift_Outer_Inner_Outer_Inner"] = function() { + const value = structHelpers.M10TestModuleT5OuterT5InnerT5OuterT5Inner.lift(); + return swift.memory.retain(value); + } + bjs["bjs_core_register_type_handles"] = function() {}; + bjs["bjs_TestModule_register_type_handles"] = function() {}; + const __bjs_promiseSettlers = Symbol("JavaScriptKit.promiseSettlers"); + bjs["swift_js_make_promise"] = function() { + let resolve, reject; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + promise[__bjs_promiseSettlers] = { resolve, reject }; + return swift.memory.retain(promise); + } + bjs["swift_js_return_optional_bool"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalBool = null; + } else { + tmpRetOptionalBool = value !== 0; + } + } + bjs["swift_js_return_optional_int"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalInt = null; + } else { + tmpRetOptionalInt = value | 0; + } + } + bjs["swift_js_return_optional_float"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalFloat = null; + } else { + tmpRetOptionalFloat = Math.fround(value); + } + } + bjs["swift_js_return_optional_double"] = function(isSome, value) { + if (isSome === 0) { + tmpRetOptionalDouble = null; + } else { + tmpRetOptionalDouble = value; + } + } + bjs["swift_js_return_optional_string"] = function(isSome, ptr, len) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = decodeString(ptr, len); + } + } + bjs["swift_js_return_optional_object"] = function(isSome, objectId) { + if (isSome === 0) { + tmpRetString = null; + } else { + tmpRetString = swift.memory.getObject(objectId); + } + } + bjs["swift_js_return_optional_heap_object"] = function(isSome, pointer) { + if (isSome === 0) { + tmpRetOptionalHeapObject = null; + } else { + tmpRetOptionalHeapObject = pointer; + } + } + bjs["swift_js_get_optional_int_presence"] = function() { + return tmpRetOptionalInt != null ? 1 : 0; + } + bjs["swift_js_get_optional_int_value"] = function() { + const value = tmpRetOptionalInt; + tmpRetOptionalInt = undefined; + return value; + } + bjs["swift_js_get_optional_string"] = function() { + const str = tmpRetString; + tmpRetString = undefined; + if (str == null) { + return -1; + } else { + const bytes = textEncoder.encode(str); + tmpRetBytes = bytes; + return bytes.length; + } + } + bjs["swift_js_get_optional_float_presence"] = function() { + return tmpRetOptionalFloat != null ? 1 : 0; + } + bjs["swift_js_get_optional_float_value"] = function() { + const value = tmpRetOptionalFloat; + tmpRetOptionalFloat = undefined; + return value; + } + bjs["swift_js_get_optional_double_presence"] = function() { + return tmpRetOptionalDouble != null ? 1 : 0; + } + bjs["swift_js_get_optional_double_value"] = function() { + const value = tmpRetOptionalDouble; + tmpRetOptionalDouble = undefined; + return value; + } + bjs["swift_js_get_optional_heap_object_pointer"] = function() { + const pointer = tmpRetOptionalHeapObject; + tmpRetOptionalHeapObject = undefined; + return pointer || 0; + } + bjs["swift_js_closure_unregister"] = function(funcRef) {} + // Wrapper functions for module: TestModule + if (!importObject["TestModule"]) { + importObject["TestModule"] = {}; + } + importObject["TestModule"]["bjs_Library_wrap"] = function(pointer) { + const obj = _exports['Library'].__construct(pointer); + return swift.memory.retain(obj); + }; + importObject["TestModule"]["bjs_Outer_wrap"] = function(pointer) { + const obj = _exports['Outer'].__construct(pointer); + return swift.memory.retain(obj); + }; + }, + setInstance: (i) => { + instance = i; + memory = instance.exports.memory; + + decodeString = (ptr, len) => { const bytes = new Uint8Array(memory.buffer, ptr >>> 0, len >>> 0); return textDecoder.decode(bytes); } + + setException = (error) => { + instance.exports._swift_js_exception.value = swift.memory.retain(error) + } + }, + /** @param {WebAssembly.Instance} instance */ + createExports: (instance) => { + const js = swift.memory.heap; + const swiftHeapObjectFinalizationRegistry = (typeof FinalizationRegistry === "undefined") ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry((state) => { + if (state.hasReleased) { + return; + } + state.hasReleased = true; + state.identityMap?.delete(state.pointer); + state.deinit(state.pointer); + }); + + /// Represents a Swift heap object like a class instance or an actor instance. + class SwiftHeapObject { + static __wrap(pointer, deinit, prototype, identityCache) { + pointer = pointer >>> 0; + const makeFresh = (identityMap) => { + const obj = Object.create(prototype); + const state = { pointer, deinit, hasReleased: false, identityMap }; + obj.pointer = pointer; + obj.__swiftHeapObjectState = state; + swiftHeapObjectFinalizationRegistry.register(obj, state, state); + if (identityMap) { + identityMap.set(pointer, new WeakRef(obj)); + } + return obj; + }; + + if (!identityCache) { + return makeFresh(null); + } + + const cached = identityCache.get(pointer)?.deref(); + if (cached && !cached.__swiftHeapObjectState.hasReleased) { + deinit(pointer); + return cached; + } + if (identityCache.has(pointer)) { + identityCache.delete(pointer); + } + + return makeFresh(identityCache); + } + + release() { + const state = this.__swiftHeapObjectState; + if (state.hasReleased) { + return; + } + state.hasReleased = true; + swiftHeapObjectFinalizationRegistry.unregister(state); + state.identityMap?.delete(state.pointer); + state.deinit(state.pointer); + } + } + class Library extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Library_deinit, Library.prototype, null); + } + + constructor() { + const ret = instance.exports.bjs_Library_init(); + return Library.__construct(ret); + } + divider(value) { + structHelpers.M10TestModuleT7LibraryT5ShelfT7Divider.lower(value); + instance.exports.bjs_Library_divider(this.pointer); + const structValue = structHelpers.M10TestModuleT7LibraryT5ShelfT7Divider.lift(); + return structValue; + } + } + class Outer extends SwiftHeapObject { + static __construct(ptr) { + return SwiftHeapObject.__wrap(ptr, instance.exports.bjs_Outer_deinit, Outer.prototype, null); + } + + constructor() { + const ret = instance.exports.bjs_Outer_init(); + return Outer.__construct(ret); + } + } + const __bjs_helpers_M10TestModuleT7LibraryT5Shelf = __bjs_createStructHelpers_M10TestModuleT7LibraryT5Shelf(); + structHelpers.M10TestModuleT7LibraryT5Shelf = __bjs_helpers_M10TestModuleT7LibraryT5Shelf; + + const __bjs_helpers_M10TestModuleT7LibraryT5ShelfT7Divider = __bjs_createStructHelpers_M10TestModuleT7LibraryT5ShelfT7Divider(); + structHelpers.M10TestModuleT7LibraryT5ShelfT7Divider = __bjs_helpers_M10TestModuleT7LibraryT5ShelfT7Divider; + + const __bjs_helpers_M10TestModuleT5OuterT5Inner = __bjs_createStructHelpers_M10TestModuleT5OuterT5Inner(); + structHelpers.M10TestModuleT5OuterT5Inner = __bjs_helpers_M10TestModuleT5OuterT5Inner; + + const __bjs_helpers_M10TestModuleT5OuterT5InnerT5Outer = __bjs_createStructHelpers_M10TestModuleT5OuterT5InnerT5Outer(); + structHelpers.M10TestModuleT5OuterT5InnerT5Outer = __bjs_helpers_M10TestModuleT5OuterT5InnerT5Outer; + + const __bjs_helpers_M10TestModuleT5OuterT5InnerT5OuterT5Inner = __bjs_createStructHelpers_M10TestModuleT5OuterT5InnerT5OuterT5Inner(); + structHelpers.M10TestModuleT5OuterT5InnerT5OuterT5Inner = __bjs_helpers_M10TestModuleT5OuterT5InnerT5OuterT5Inner; + + const exports = { + Library: Object.assign(Library, { + Shelf: { + Divider: { + init: function(slot) { + instance.exports.bjs_Library_Shelf_Divider_init(slot); + const structValue = structHelpers.M10TestModuleT7LibraryT5ShelfT7Divider.lift(); + return structValue; + }, + }, + }, + }), + Outer: Object.assign(Outer, { + Inner: { + init: function() { + instance.exports.bjs_Outer_Inner_init(); + const structValue = structHelpers.M10TestModuleT5OuterT5Inner.lift(); + return structValue; + }, + Outer: { + Inner: { + init: function() { + instance.exports.bjs_Outer_Inner_Outer_Inner_init(); + const structValue = structHelpers.M10TestModuleT5OuterT5InnerT5OuterT5Inner.lift(); + return structValue; + }, + }, + }, + }, + }), + }; + _exports = exports; + return exports; + }, + } +} \ No newline at end of file From cadafdcf9a1946ed60dfd22407e7e8dd189920e8 Mon Sep 17 00:00:00 2001 From: Yuta Saito Date: Sat, 22 Aug 2026 17:46:33 +0900 Subject: [PATCH 50/50] PackageToJS: Derive WASI and shared memory support from wasm imports (#807) * PackageToJS: Derive WASI and shared memory support from wasm imports The SwiftBuild backend's build directory doesn't encode the target triple, so detect the traits derived from it by parsing the imports of the product binary instead. The imports are now parsed as a part of the packaging build graph. * Avoid `import var Foundation.stderr` ``` $ echo "@preconcurrency import var Foundation.stderr" | swiftly run +main-snapshot-2026-08-11 swiftc - -o /dev/null :1:28: error: ambiguous name 'stderr' in module 'Foundation' 1 | @preconcurrency import var Foundation.stderr | `- error: ambiguous name 'stderr' in module 'Foundation' 2 | Glibc.stderr:1:32: note: found this candidate 1 | nonisolated(unsafe) public var stderr: UnsafeMutablePointer! { get } | `- note: found this candidate /usr/include/stdio.h:151:14: note: found this candidate 149 | extern FILE *stdin; /* Standard input stream. */ 150 | extern FILE *stdout; /* Standard output stream. */ 151 | extern FILE *stderr; /* Standard error output stream. */ | `- note: found this candidate 152 | /* C89/C99 say they're macros. Make them happy. */ 153 | #define stdin stdin ``` https://github.com/swiftlang/swift/pull/89891 * CI: Install Swift toolchain preserving its usr/bin layout Flattening the tarball into /usr/local makes SwiftPM derive a bogus toolchain root, so the swiftbuild build system cannot find swiftc. * PackageToJS: Record every import kind while parsing wasm imports Only memory imports were collected, so `WasmFeatures.isWASI` never saw `wasi_snapshot_preview1` and the generated node.js dropped the WASI import while still constructing a WASI instance. * PackageToJS: run per-target test runners under the swiftbuild build system `swift package js test` assumed the native build system's single combined `PackageTests` binary: it looked for one `.wasm`/`.xctest` under `.build//`, packaged it, and ran it. SwiftBuild produces no combined test binary. It emits one `-test-runner.wasm` per test target under `.build/out/Products/`, plus an aggregate target that only orchestrates building them, so the old lookup failed with "Failed to find 'JavaScriptKitPackageTests.wasm'". (cherry picked from commit c12c7e9bab5f30885eb14bf25aca94190ac99696) * Install the JS event loop executor in async test targets Because SwiftBuild mode produces a linked executable for each test target. (cherry picked from commit 0a1f926e35a043e27938ef8933d1b23f864097a7) * BridgeJS: Skip type handle registration for unlinked modules `js test` generates the glue from every test target's skeletons, but the SwiftBuild build system links one binary per test target, so the eager registration hit a missing export. * PackageToJS: Share the linked JS modules with the aggregated glue The per-runner `bridge-js.js` copied to the base output directory for test preludes imports its JavaScript modules relative to itself, so copy the `bridge-js-modules` directory next to it. * BridgeJS: Require the imports object for static-only imported types An imported type looked up from `getImports` contributes its static methods too, but only a constructor marked the imports object as needed, so the glue referenced an undeclared `imports`. * PackageToJS: Generate each test bundle's glue from what its binary links in `js test` generated the glue from every test target's skeletons and handed the same copy to each SwiftBuild per-target runner, which described exports those binaries don't have. Package the aggregated glue once into the shared base directory, where preludes import it by a fixed path, and give each runner glue scoped to the target it links in. This supersedes the registration guard in the JS code generator. --- .github/actions/install-swift/action.yml | 8 +- .github/workflows/test.yml | 15 +- .../Sources/PlayBridgeJS/main.swift | 2 +- Makefile | 3 +- Package.swift | 6 +- .../Sources/BridgeJSLink/BridgeJSLink.swift | 15 +- .../Sources/BridgeJSTool/BridgeJSTool.swift | 12 +- .../BridgeJSToolInternal.swift | 2 +- .../BridgeJSToolTests/BridgeJSLinkTests.swift | 14 +- .../ImportedJSModuleRegistryTests.swift | 2 +- .../BridgeJSLinkTests/AsyncStaticImport.js | 1 + .../EnumAssociatedValueImport.js | 1 + .../BridgeJSLinkTests/EnumCaseImport.js | 1 + Plugins/PackageToJS/Sources/PackageToJS.swift | 383 ++++++++++++------ .../Sources/PackageToJSPlugin.swift | 271 ++++++++++--- Plugins/PackageToJS/Sources/ParseWasm.swift | 10 +- .../Tests/PackagingPlannerTests.swift | 59 ++- .../PackageToJS/Tests/ParseWasmTests.swift | 52 +++ .../planBuild_debug.json | 80 ++-- .../planBuild_release.json | 80 ++-- .../planBuild_release_dwarf.json | 80 ++-- .../planBuild_release_name.json | 80 ++-- .../planBuild_release_no_optimize.json | 80 ++-- .../PackagingPlannerTests/planTestBuild.json | 104 ++--- 24 files changed, 902 insertions(+), 459 deletions(-) create mode 100644 Plugins/PackageToJS/Tests/ParseWasmTests.swift diff --git a/.github/actions/install-swift/action.yml b/.github/actions/install-swift/action.yml index d6fbcc969..c2803206c 100644 --- a/.github/actions/install-swift/action.yml +++ b/.github/actions/install-swift/action.yml @@ -32,6 +32,12 @@ runs: zlib1g-dev curl + # Keep the toolchain's `/usr/bin` layout intact. Flattening it into + # /usr/local breaks toolchain discovery in the swiftbuild build system, + # which derives the toolchain root by stripping `usr/bin` from `swiftc`. - name: Install Swift shell: bash - run: curl -fL ${{ inputs.download-url }} | sudo tar xfz - --strip-components=2 -C /usr/local + run: | + sudo mkdir -p /opt/swift + curl -fL ${{ inputs.download-url }} | sudo tar xfz - --strip-components=1 -C /opt/swift + echo "/opt/swift/usr/bin" >> "$GITHUB_PATH" diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 0458dec5d..a9e90c175 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -14,9 +14,10 @@ jobs: entry: - os: ubuntu-24.04 toolchain: - download-url: https://download.swift.org/development/ubuntu2404/swift-DEVELOPMENT-SNAPSHOT-2026-05-27-a/swift-DEVELOPMENT-SNAPSHOT-2026-05-27-a-ubuntu24.04.tar.gz + download-url: https://download.swift.org/development/ubuntu2404/swift-DEVELOPMENT-SNAPSHOT-2026-08-11-a/swift-DEVELOPMENT-SNAPSHOT-2026-08-11-a-ubuntu24.04.tar.gz wasi-backend: Node target: "wasm32-unknown-wasip1" + build-system: swiftbuild env: | JAVASCRIPTKIT_DISABLE_TRACING_TRAIT=1 - os: ubuntu-24.04 @@ -24,11 +25,13 @@ jobs: download-url: https://download.swift.org/swift-6.3-branch/ubuntu2404/swift-6.3-DEVELOPMENT-SNAPSHOT-2026-03-05-a/swift-6.3-DEVELOPMENT-SNAPSHOT-2026-03-05-a-ubuntu24.04.tar.gz wasi-backend: Node target: "wasm32-unknown-wasip1" + build-system: native - os: ubuntu-22.04 toolchain: - download-url: https://download.swift.org/development/ubuntu2204/swift-DEVELOPMENT-SNAPSHOT-2026-05-27-a/swift-DEVELOPMENT-SNAPSHOT-2026-05-27-a-ubuntu22.04.tar.gz + download-url: https://download.swift.org/development/ubuntu2204/swift-DEVELOPMENT-SNAPSHOT-2026-08-11-a/swift-DEVELOPMENT-SNAPSHOT-2026-08-11-a-ubuntu22.04.tar.gz wasi-backend: Node target: "wasm32-unknown-wasip1-threads" + build-system: swiftbuild runs-on: ${{ matrix.entry.os }} env: @@ -55,7 +58,7 @@ jobs: echo "SWIFT_BIN_PATH=$(dirname $(which swiftc))" >> $GITHUB_ENV - run: make bootstrap - run: npm run test:runtime - - run: make unittest + - run: make unittest BUILD_SYSTEM=${{ matrix.entry.build-system }} # Skip unit tests with uwasi because its proc_exit throws # unhandled promise rejection. if: ${{ matrix.entry.wasi-backend != 'MicroWASI' }} @@ -144,7 +147,7 @@ jobs: - uses: actions/checkout@v7 - uses: ./.github/actions/install-swift with: - download-url: https://download.swift.org/development/ubuntu2204/swift-DEVELOPMENT-SNAPSHOT-2026-05-27-a/swift-DEVELOPMENT-SNAPSHOT-2026-05-27-a-ubuntu22.04.tar.gz + download-url: https://download.swift.org/development/ubuntu2204/swift-DEVELOPMENT-SNAPSHOT-2026-08-11-a/swift-DEVELOPMENT-SNAPSHOT-2026-08-11-a-ubuntu22.04.tar.gz - run: make bootstrap - run: ./Utilities/bridge-js-generate.sh - name: Check if BridgeJS generated files are up-to-date @@ -175,7 +178,7 @@ jobs: - uses: actions/checkout@v7 - uses: ./.github/actions/install-swift with: - download-url: https://download.swift.org/development/ubuntu2204/swift-DEVELOPMENT-SNAPSHOT-2026-05-27-a/swift-DEVELOPMENT-SNAPSHOT-2026-05-27-a-ubuntu22.04.tar.gz + download-url: https://download.swift.org/development/ubuntu2204/swift-DEVELOPMENT-SNAPSHOT-2026-08-11-a/swift-DEVELOPMENT-SNAPSHOT-2026-08-11-a-ubuntu22.04.tar.gz - uses: swiftwasm/setup-swiftwasm@v2 id: setup-wasm32-unknown-wasip1 with: { target: wasm32-unknown-wasip1 } @@ -198,7 +201,7 @@ jobs: - uses: actions/checkout@v7 - uses: ./.github/actions/install-swift with: - download-url: https://download.swift.org/development/ubuntu2204/swift-DEVELOPMENT-SNAPSHOT-2026-05-27-a/swift-DEVELOPMENT-SNAPSHOT-2026-05-27-a-ubuntu22.04.tar.gz + download-url: https://download.swift.org/development/ubuntu2204/swift-DEVELOPMENT-SNAPSHOT-2026-08-11-a/swift-DEVELOPMENT-SNAPSHOT-2026-08-11-a-ubuntu22.04.tar.gz - uses: swiftwasm/setup-swiftwasm@v2 id: setup-wasm32-unknown-wasip1 with: { target: wasm32-unknown-wasip1 } diff --git a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/main.swift b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/main.swift index a30eb3b06..3a4063945 100644 --- a/Examples/PlayBridgeJS/Sources/PlayBridgeJS/main.swift +++ b/Examples/PlayBridgeJS/Sources/PlayBridgeJS/main.swift @@ -70,7 +70,7 @@ import class Foundation.JSONDecoder let importTS = ImportTS(progress: .silent, moduleName: moduleName, skeleton: $0) return try importTS.finalize() } - let linker = BridgeJSLink(skeletons: [skeleton], sharedMemory: false) + let linker = BridgeJSLink(skeletons: [skeleton]) let linked = try linker.link() return PlayBridgeJSOutput( diff --git a/Makefile b/Makefile index 4b174e347..bbf031a00 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,5 @@ SWIFT_SDK_ID ?= +BUILD_SYSTEM ?= swiftbuild ifeq ($(JAVASCRIPTKIT_DISABLE_TRACING_TRAIT),1) TRACING_ARGS := else @@ -16,7 +17,7 @@ unittest: echo "SWIFT_SDK_ID is not set. Run 'swift sdk list' and pass a matching SDK, e.g. 'make unittest SWIFT_SDK_ID='."; \ exit 2; \ } - swift package --build-system native --swift-sdk "$(SWIFT_SDK_ID)" \ + swift package --build-system "$(BUILD_SYSTEM)" --swift-sdk "$(SWIFT_SDK_ID)" \ $(TRACING_ARGS) \ --disable-sandbox \ js test --prelude ./Tests/prelude.mjs -Xnode --expose-gc diff --git a/Package.swift b/Package.swift index 63eacf6be..0504d4505 100644 --- a/Package.swift +++ b/Package.swift @@ -82,7 +82,7 @@ let package = Package( .testTarget( name: "JavaScriptKitTests", - dependencies: ["JavaScriptKit"], + dependencies: ["JavaScriptKit", "JavaScriptEventLoopTestSupport"], swiftSettings: [ .enableExperimentalFeature("Extern"), .define("Tracing", .when(traits: ["Tracing"])), @@ -191,7 +191,7 @@ let package = Package( ), .testTarget( name: "BridgeJSRuntimeTests", - dependencies: ["JavaScriptKit", "JavaScriptEventLoop"], + dependencies: ["JavaScriptKit", "JavaScriptEventLoop", "JavaScriptEventLoopTestSupport"], exclude: [ "bridge-js.config.json", "bridge-js.d.ts", @@ -220,7 +220,7 @@ let package = Package( ), .testTarget( name: "BridgeJSIdentityTests", - dependencies: ["JavaScriptKit", "JavaScriptEventLoop"], + dependencies: ["JavaScriptKit", "JavaScriptEventLoop", "JavaScriptEventLoopTestSupport"], exclude: [ "bridge-js.config.json", "Generated/JavaScript", diff --git a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift index 0e5bdc221..163b7db6b 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSLink/BridgeJSLink.swift @@ -9,7 +9,6 @@ import BridgeJSUtilities public struct BridgeJSLink { var skeletons: [BridgeJSSkeleton] = [] - let sharedMemory: Bool /// Whether to track the lifetime of Swift objects. /// /// This is useful for debugging memory issues. @@ -19,11 +18,9 @@ public struct BridgeJSLink { private let importedModuleRegistry = ImportedJSModuleRegistry() public init( - skeletons: [BridgeJSSkeleton] = [], - sharedMemory: Bool = false + skeletons: [BridgeJSSkeleton] = [] ) { self.skeletons = skeletons - self.sharedMemory = sharedMemory } /// The identity mode from the config file, resolved from skeletons. @@ -270,7 +267,9 @@ public struct BridgeJSLink { try renderImportedFunction(importObjectBuilder: importObjectBuilder, function: function) } for type in fileSkeleton.types { - if type.constructor != nil, type.from == nil { + // Matches the condition rendering the type into the `getImports` result + // type: both its constructor and its static methods are looked up there. + if type.from == nil, type.constructor != nil || !type.staticMethods.isEmpty { data.needsImportsObject = true } try renderImportedType(importObjectBuilder: importObjectBuilder, type: type) @@ -1173,7 +1172,7 @@ public struct BridgeJSLink { } /// Generates JavaScript output using CodeFragmentPrinter for better maintainability - private func generateJavaScript(data: LinkData) throws -> String { + private func generateJavaScript(data: LinkData, sharedMemory: Bool) throws -> String { let header = """ // NOTICE: This is auto-generated code by BridgeJS from JavaScriptKit, // DO NOT EDIT. @@ -1346,7 +1345,7 @@ public struct BridgeJSLink { return printer.lines.joined(separator: "\n") } - public func link() throws -> (outputJs: String, outputDts: String) { + public func link(sharedMemory: Bool = false) throws -> (outputJs: String, outputDts: String) { intrinsicRegistry.reset() importedModuleRegistry.configure(skeletons: skeletons) intrinsicRegistry.classNamespaces = skeletons.reduce(into: [:]) { result, unified in @@ -1359,7 +1358,7 @@ public struct BridgeJSLink { } intrinsicRegistry.typeOwnerModules = collectTypeOwnerModules() let data = try collectLinkData() - let outputJs = try generateJavaScript(data: data) + let outputJs = try generateJavaScript(data: data, sharedMemory: sharedMemory) let outputDts = generateTypeScript(data: data) return (outputJs, outputDts) } diff --git a/Plugins/BridgeJS/Sources/BridgeJSTool/BridgeJSTool.swift b/Plugins/BridgeJS/Sources/BridgeJSTool/BridgeJSTool.swift index 96d9c4705..d3d9a484e 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSTool/BridgeJSTool.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSTool/BridgeJSTool.swift @@ -2,7 +2,6 @@ @preconcurrency import func Foundation.fputs @preconcurrency import func Foundation.open @preconcurrency import func Foundation.strerror -@preconcurrency import var Foundation.stderr @preconcurrency import var Foundation.errno @preconcurrency import var Foundation.O_WRONLY @preconcurrency import var Foundation.O_CREAT @@ -15,6 +14,17 @@ @preconcurrency import class Foundation.FileManager @preconcurrency import class Foundation.JSONDecoder @preconcurrency import class Foundation.ProcessInfo + +#if canImport(Darwin) +@preconcurrency import var Darwin.stderr +#elseif canImport(Glibc) +@preconcurrency import var Glibc.stderr +#elseif canImport(Musl) +@preconcurrency import var Musl.stderr +#elseif canImport(Android) +@preconcurrency import var Android.stderr +#endif + import SwiftParser import SwiftSyntax diff --git a/Plugins/BridgeJS/Sources/BridgeJSToolInternal/BridgeJSToolInternal.swift b/Plugins/BridgeJS/Sources/BridgeJSToolInternal/BridgeJSToolInternal.swift index 971c9608e..f57f50756 100644 --- a/Plugins/BridgeJS/Sources/BridgeJSToolInternal/BridgeJSToolInternal.swift +++ b/Plugins/BridgeJS/Sources/BridgeJSToolInternal/BridgeJSToolInternal.swift @@ -110,7 +110,7 @@ import ArgumentParser let skeletonData = try readData(from: skeletonFile) skeletons.append(try JSONDecoder().decode(BridgeJSSkeleton.self, from: skeletonData)) } - let link = BridgeJSLink(skeletons: skeletons, sharedMemory: false) + let link = BridgeJSLink(skeletons: skeletons) return try link.link() } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSLinkTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSLinkTests.swift index cab2aca6f..f96ec2d8d 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSLinkTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/BridgeJSLinkTests.swift @@ -70,7 +70,7 @@ import Testing ) importSwift.addSourceFile(sourceFile, inputFilePath: "\(name).swift") let importResult = try importSwift.finalize() - var bridgeJSLink = BridgeJSLink(sharedMemory: false) + var bridgeJSLink = BridgeJSLink() let encoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted, .sortedKeys] let unifiedData = try encoder.encode(importResult) @@ -99,8 +99,7 @@ import Testing let bridgeJSLink: BridgeJSLink = BridgeJSLink( skeletons: [ outputSkeleton - ], - sharedMemory: false + ] ) try snapshot(bridgeJSLink: bridgeJSLink, name: name + ".Global") } @@ -133,8 +132,7 @@ import Testing skeletons: [ globalSkeleton, privateSkeleton, - ], - sharedMemory: false + ] ) try snapshot(bridgeJSLink: bridgeJSLink, name: "MixedModules") } @@ -151,7 +149,7 @@ import Testing ) importSwift.addSourceFile(sourceFile, inputFilePath: "\(name).swift") let importResult = try importSwift.finalize() - var bridgeJSLink = BridgeJSLink(sharedMemory: false) + var bridgeJSLink = BridgeJSLink() let encoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted, .sortedKeys] let unifiedData = try encoder.encode(importResult) @@ -182,7 +180,7 @@ import Testing #expect(explicitlyUncachedClass?.identityMode == false) // Verify generated JS via snapshot - let bridgeJSLink = BridgeJSLink(skeletons: [outputSkeleton], sharedMemory: false) + let bridgeJSLink = BridgeJSLink(skeletons: [outputSkeleton]) try snapshot(bridgeJSLink: bridgeJSLink, name: "IdentityModeClass.PerClass") } @@ -206,7 +204,7 @@ import Testing #expect(explicitlyUncachedClass?.identityMode == false) // Verify generated JS via snapshot - let bridgeJSLink = BridgeJSLink(skeletons: [outputSkeleton], sharedMemory: false) + let bridgeJSLink = BridgeJSLink(skeletons: [outputSkeleton]) try snapshot(bridgeJSLink: bridgeJSLink, name: "IdentityModeClass.ConfigPointer") } } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/ImportedJSModuleRegistryTests.swift b/Plugins/BridgeJS/Tests/BridgeJSToolTests/ImportedJSModuleRegistryTests.swift index 16c28be95..7c5d168d2 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/ImportedJSModuleRegistryTests.swift +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/ImportedJSModuleRegistryTests.swift @@ -35,7 +35,7 @@ import Testing } private func importLines(_ skeletons: [BridgeJSSkeleton]) throws -> [String] { - var link = BridgeJSLink(sharedMemory: false) + var link = BridgeJSLink() let encoder = JSONEncoder() for skeleton in skeletons { _ = try link.addSkeletonFile(data: try encoder.encode(skeleton)) diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js index 47dd161a2..eea340c35 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/AsyncStaticImport.js @@ -153,6 +153,7 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; + const imports = options.getImports(importsContext); bjs["swift_js_return_string"] = function(ptr, len) { tmpRetString = decodeString(ptr, len); } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js index 07fe91654..2b36953bb 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumAssociatedValueImport.js @@ -83,6 +83,7 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; + const imports = options.getImports(importsContext); bjs["swift_js_return_string"] = function(ptr, len) { tmpRetString = decodeString(ptr, len); } diff --git a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js index b4e67b6b8..bde5fc31f 100644 --- a/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js +++ b/Plugins/BridgeJS/Tests/BridgeJSToolTests/__Snapshots__/BridgeJSLinkTests/EnumCaseImport.js @@ -44,6 +44,7 @@ export async function createInstantiator(options, swift) { addImports: (importObject, importsContext) => { bjs = {}; importObject["bjs"] = bjs; + const imports = options.getImports(importsContext); bjs["swift_js_return_string"] = function(ptr, len) { tmpRetString = decodeString(ptr, len); } diff --git a/Plugins/PackageToJS/Sources/PackageToJS.swift b/Plugins/PackageToJS/Sources/PackageToJS.swift index c1d09af0a..c8adb9346 100644 --- a/Plugins/PackageToJS/Sources/PackageToJS.swift +++ b/Plugins/PackageToJS/Sources/PackageToJS.swift @@ -69,15 +69,31 @@ struct PackageToJS { var packageOptions: PackageOptions } - static func deriveBuildConfiguration(wasmProductArtifact: URL) -> (configuration: String, triple: String) { + /// Derives the build configuration from the path of the wasm product artifact. + /// Returns "debug" or "release" + static func deriveBuildConfiguration(wasmProductArtifact: URL) -> String { + // For "--build-system swiftbuild" + // e.g. path/to/.build/out/Products/Debug-webassembly-wasm32/Basic.wasm + // ref: https://github.com/swiftlang/swift-build/blob/48498f5450c85da3f8c09808168f0286d207329b/Sources/SWBCore/Core.swift#L631-L643 + // + // For "--build-system native" // e.g. path/to/.build/wasm32-unknown-wasi/debug/Basic.wasm -> ("debug", "wasm32-unknown-wasi") // First, resolve symlink to get the actual path as SwiftPM 6.0 and earlier returns unresolved // symlink path for product artifact. let wasmProductArtifact = wasmProductArtifact.resolvingSymlinksInPath() - let buildConfiguration = wasmProductArtifact.deletingLastPathComponent().lastPathComponent - let triple = wasmProductArtifact.deletingLastPathComponent().deletingLastPathComponent().lastPathComponent - return (buildConfiguration, triple) + let swiftBuildSuffix = "-webassembly-wasm32" + let parentDirName = wasmProductArtifact.deletingLastPathComponent().lastPathComponent + if parentDirName.hasSuffix(swiftBuildSuffix) { + // This is SwiftBuild backend mode + let swiftBuildConfig = String(parentDirName.dropLast(swiftBuildSuffix.count)) + guard let mappedConfig = ["Debug": "debug", "Release": "release"][swiftBuildConfig] else { + fatalError("Unknown SwiftPM build configuration: \(swiftBuildConfig)") + } + return mappedConfig + } + // This is native backend mode, the parent directory name is the build configuration + return parentDirName } static func runTest(testRunner: URL, currentDirectoryURL: URL, outputDir: URL, testOptions: TestOptions) throws { @@ -426,8 +442,6 @@ struct PackagingPlanner { let wasmProductArtifact: BuildPath /// The build configuration let configuration: String - /// The target triple - let triple: String /// The system interface to use let system: any PackagingSystem @@ -441,7 +455,6 @@ struct PackagingPlanner { wasmProductArtifact: BuildPath, wasmFilename: String, configuration: String, - triple: String, // NOTE: We should use `ProcessInfo.processInfo.arguments[0]` instead of `CommandLine.arguments[0]` // because the latter may not always be the full executable path (e.g. when invoked through PATH lookup). // https://github.com/swiftlang/swift-foundation/blob/f5143f96d01cdb6d280665de8221b75fc8631d95/Sources/FoundationEssentials/ProcessInfo/ProcessInfo.swift#L47 @@ -458,7 +471,6 @@ struct PackagingPlanner { self.selfPath = selfPath self.wasmProductArtifact = wasmProductArtifact self.configuration = configuration - self.triple = triple self.system = system } @@ -469,7 +481,7 @@ struct PackagingPlanner { make: inout MiniMake, buildOptions: PackageToJS.BuildOptions ) throws -> MiniMake.TaskKey { - let (allTasks, _, _, _) = try planBuildInternal( + let (allTasks, _, _, _, _) = try planBuildInternal( make: &make, noOptimize: buildOptions.noOptimize, debugInfoFormat: buildOptions.debugInfoFormat @@ -489,7 +501,8 @@ struct PackagingPlanner { allTasks: [MiniMake.TaskKey], outputDirTask: MiniMake.TaskKey, intermediatesDirTask: MiniMake.TaskKey, - packageJsonTask: MiniMake.TaskKey + packageJsonTask: MiniMake.TaskKey, + wasmImportsTask: MiniMake.TaskKey ) { // Prepare output directory let outputDirTask = make.addTask( @@ -575,20 +588,8 @@ struct PackagingPlanner { } packageInputs.append(wasm) - let wasmImportsPath = intermediatesDir.appending(path: "wasm-imports.json") - let wasmImportsTask = make.addTask( - inputFiles: [selfPath, finalWasmPath], - inputTasks: [outputDirTask, intermediatesDirTask, wasm], - output: wasmImportsPath - ) { - let metadata = try parseImports( - moduleBytes: try Data(contentsOf: URL(fileURLWithPath: $1.resolve(path: finalWasmPath).path)) - ) - let jsonEncoder = JSONEncoder() - jsonEncoder.outputFormatting = .prettyPrinted - let jsonData = try jsonEncoder.encode(metadata) - try system.writeFile(atPath: $1.resolve(path: $0.output).path, content: jsonData) - } + let wasmImportsPath = self.wasmImportsPath + let wasmImportsTask = planWasmImports(make: &make, intermediatesDirTask: intermediatesDirTask) packageInputs.append(wasmImportsTask) @@ -606,55 +607,20 @@ struct PackagingPlanner { file: "Plugins/PackageToJS/Templates/package.json", output: "package.json", outputDirTask: outputDirTask, + wasmImportsTask: wasmImportsTask, inputFiles: [], inputTasks: [] ) packageInputs.append(packageJsonTask) if !skeletons.isEmpty { - let bridge = try loadBridgeJS() - let skeletonFiles = skeletons.map { BuildPath(absolute: $0.source.path) } - let bridgeJs = outputDir.appending(path: "bridge-js.js") - let bridgeDts = outputDir.appending(path: "bridge-js.d.ts") - let bridgeModules = outputDir.appending(path: "bridge-js-modules") packageInputs.append( - make.addTask(inputFiles: skeletonFiles + [selfPath], output: bridgeJs) { _, scope in - let output = try bridge.link.link() - try system.writeFile( - atPath: scope.resolve(path: bridgeJs).path, - content: Data(output.outputJs.utf8) - ) - try system.writeFile( - atPath: scope.resolve(path: bridgeDts).path, - content: Data(output.outputDts.utf8) - ) - } - ) - let bridgeModulesStamp = intermediatesDir.appending(path: "bridge-js-modules.stamp") - packageInputs.append( - make.addTask( - inputFiles: skeletonFiles + bridge.modules.map(\.source) + [selfPath], - inputTasks: [outputDirTask, intermediatesDirTask], - output: bridgeModulesStamp - ) { _, scope in - let modulesDirectory = scope.resolve(path: bridgeModules) - try system.removeItemIfExists(atPath: modulesDirectory.path) - if !bridge.modules.isEmpty { - try system.createDirectory(atPath: modulesDirectory.path) - } - for module in bridge.modules { - let destination = scope.resolve(path: outputDir.appending(path: module.relativeOutputPath)) - try system.createDirectory(atPath: destination.deletingLastPathComponent().path) - try system.syncFile( - from: scope.resolve(path: module.source).path, - to: destination.path - ) - } - try system.writeFile( - atPath: scope.resolve(path: bridgeModulesStamp).path, - content: Data() - ) - } + contentsOf: try planBridgeJS( + make: &make, + outputDirTask: outputDirTask, + intermediatesDirTask: intermediatesDirTask, + wasmImportsTask: wasmImportsTask + ) ) } @@ -678,22 +644,20 @@ struct PackagingPlanner { file: file, output: output, outputDirTask: outputDirTask, - inputFiles: [wasmImportsPath], - inputTasks: [platformsDirTask, wasmImportsTask], - wasmImportsPath: wasmImportsPath + wasmImportsTask: wasmImportsTask, + inputFiles: [], + inputTasks: [platformsDirTask] ) ) } - return (packageInputs, outputDirTask, intermediatesDirTask, packageJsonTask) + return (packageInputs, outputDirTask, intermediatesDirTask, packageJsonTask, wasmImportsTask) } private func loadBridgeJS() throws -> ( link: BridgeJSLink, modules: [JavaScriptModuleInput] ) { - var link = BridgeJSLink( - sharedMemory: Self.isSharedMemoryEnabled(triple: triple) - ) + var link = BridgeJSLink() var moduleSources: [String: BuildPath] = [:] for input in skeletons { @@ -731,30 +695,195 @@ struct PackagingPlanner { ) } + /// Plan the artifacts that several per-runner test bundles packaged as subdirectories + /// share. + /// + /// Node resolves `node_modules` by walking up the directory tree, so a single install + /// here serves every runner underneath, avoiding one install per test target. The glue + /// generated here describes every test target rather than the one target a runner links + /// in, so that test preludes - which are loaded for every runner and import it by a + /// fixed path - see the whole package's API. + func planSharedTestArtifacts(make: inout MiniMake) throws -> MiniMake.TaskKey { + let outputDirTask = make.addTask( + inputFiles: [selfPath], + output: outputDir, + attributes: [.silent] + ) { + try system.createDirectory(atPath: $1.resolve(path: $0.output).path) + } + let intermediatesDirTask = make.addTask( + inputFiles: [selfPath], + output: intermediatesDir, + attributes: [.silent] + ) { + try system.createDirectory(atPath: $1.resolve(path: $0.output).path) + } + let wasmImportsTask = planWasmImports(make: &make, intermediatesDirTask: intermediatesDirTask) + let packageJsonTask = planCopyTemplateFile( + make: &make, + file: "Plugins/PackageToJS/Templates/package.json", + output: "package.json", + outputDirTask: outputDirTask, + wasmImportsTask: wasmImportsTask, + inputFiles: [], + inputTasks: [] + ) + var tasks = [ + planNpmInstall( + make: &make, + intermediatesDirTask: intermediatesDirTask, + packageJsonTask: packageJsonTask + ) + ] + if !skeletons.isEmpty { + tasks.append( + contentsOf: try planBridgeJS( + make: &make, + outputDirTask: outputDirTask, + intermediatesDirTask: intermediatesDirTask, + wasmImportsTask: wasmImportsTask + ) + ) + } + return make.addTask( + inputTasks: tasks, + output: BuildPath(phony: "shared-test-artifacts"), + attributes: [.phony, .silent] + ) + } + + /// Plan the tasks generating the BridgeJS glue and syncing the JavaScript modules it + /// imports into the output directory + private func planBridgeJS( + make: inout MiniMake, + outputDirTask: MiniMake.TaskKey, + intermediatesDirTask: MiniMake.TaskKey, + wasmImportsTask: MiniMake.TaskKey + ) throws -> [MiniMake.TaskKey] { + let bridge = try loadBridgeJS() + let skeletonFiles = skeletons.map { BuildPath(absolute: $0.source.path) } + let wasmImportsPath = self.wasmImportsPath + let bridgeJs = outputDir.appending(path: "bridge-js.js") + let bridgeDts = outputDir.appending(path: "bridge-js.d.ts") + let bridgeModules = outputDir.appending(path: "bridge-js-modules") + let bridgeJsTask = make.addTask( + inputFiles: skeletonFiles + [selfPath, wasmImportsPath], + inputTasks: [outputDirTask, wasmImportsTask], + output: bridgeJs + ) { _, scope in + let features = try Self.loadWasmFeatures(at: scope.resolve(path: wasmImportsPath)) + let output = try bridge.link.link(sharedMemory: features.sharedMemory) + try system.writeFile( + atPath: scope.resolve(path: bridgeJs).path, + content: Data(output.outputJs.utf8) + ) + try system.writeFile( + atPath: scope.resolve(path: bridgeDts).path, + content: Data(output.outputDts.utf8) + ) + } + let bridgeModulesStamp = intermediatesDir.appending(path: "bridge-js-modules.stamp") + let bridgeModulesTask = make.addTask( + inputFiles: skeletonFiles + bridge.modules.map(\.source) + [selfPath], + inputTasks: [outputDirTask, intermediatesDirTask], + output: bridgeModulesStamp + ) { _, scope in + let modulesDirectory = scope.resolve(path: bridgeModules) + try system.removeItemIfExists(atPath: modulesDirectory.path) + if !bridge.modules.isEmpty { + try system.createDirectory(atPath: modulesDirectory.path) + } + for module in bridge.modules { + let destination = scope.resolve(path: outputDir.appending(path: module.relativeOutputPath)) + try system.createDirectory(atPath: destination.deletingLastPathComponent().path) + try system.syncFile( + from: scope.resolve(path: module.source).path, + to: destination.path + ) + } + try system.writeFile( + atPath: scope.resolve(path: bridgeModulesStamp).path, + content: Data() + ) + } + return [bridgeJsTask, bridgeModulesTask] + } + + /// Plan the task parsing the imports of the product .wasm file + /// + /// NOTE: The imports are parsed from the product artifact instead of the final .wasm + /// file because wasm-opt removes unreferenced imports, and the presence of an import + /// decides how the JavaScript glue code is generated. + private func planWasmImports( + make: inout MiniMake, + intermediatesDirTask: MiniMake.TaskKey + ) -> MiniMake.TaskKey { + make.addTask( + inputFiles: [selfPath, wasmProductArtifact], + inputTasks: [intermediatesDirTask], + output: wasmImportsPath + ) { + let metadata = try parseImports( + moduleBytes: try Data(contentsOf: URL(fileURLWithPath: $1.resolve(path: wasmProductArtifact).path)) + ) + let jsonEncoder = JSONEncoder() + jsonEncoder.outputFormatting = .prettyPrinted + let jsonData = try jsonEncoder.encode(metadata) + let outputPath = $1.resolve(path: $0.output) + // Every task consuming the imports depends on this file, so leave it untouched + // when the imports are unchanged. Rewriting it would give it a newer timestamp + // and re-run them (including `npm install`) for unrelated Swift source changes. + if let lastImports = try? Data(contentsOf: outputPath), lastImports == jsonData { + return + } + try system.writeFile(atPath: outputPath.path, content: jsonData) + } + } + + private func planNpmInstall( + make: inout MiniMake, + intermediatesDirTask: MiniMake.TaskKey, + packageJsonTask: MiniMake.TaskKey + ) -> MiniMake.TaskKey { + make.addTask( + inputFiles: [ + selfPath, + outputDir.appending(path: "package.json"), + ], + inputTasks: [intermediatesDirTask, packageJsonTask], + output: intermediatesDir.appending(path: "npm-install.stamp") + ) { + try system.npmInstall(packageDir: $1.resolve(path: outputDir).path) + try system.writeFile(atPath: $1.resolve(path: $0.output).path, content: Data()) + } + } + /// Construct the test build plan and return the root task key + /// + /// - Parameter installNodeModules: whether to install the test harness's npm + /// dependencies into this bundle's directory. Pass `false` when several runners share + /// a single `node_modules` planned once via `planSharedNodeModules`. func planTestBuild( - make: inout MiniMake + make: inout MiniMake, + installNodeModules: Bool = true ) throws -> (rootTask: MiniMake.TaskKey, binDir: BuildPath) { - var (allTasks, outputDirTask, intermediatesDirTask, packageJsonTask) = try planBuildInternal( + var (allTasks, outputDirTask, intermediatesDirTask, packageJsonTask, wasmImportsTask) = try planBuildInternal( make: &make, noOptimize: false, debugInfoFormat: .dwarf ) - // Install npm dependencies used in the test harness - allTasks.append( - make.addTask( - inputFiles: [ - selfPath, - outputDir.appending(path: "package.json"), - ], - inputTasks: [intermediatesDirTask, packageJsonTask], - output: intermediatesDir.appending(path: "npm-install.stamp") - ) { - try system.npmInstall(packageDir: $1.resolve(path: outputDir).path) - try system.writeFile(atPath: $1.resolve(path: $0.output).path, content: Data()) - } - ) + // Install npm dependencies used in the test harness, unless a shared node_modules is + // provided in a parent directory (see planSharedNodeModules). + if installNodeModules { + allTasks.append( + planNpmInstall( + make: &make, + intermediatesDirTask: intermediatesDirTask, + packageJsonTask: packageJsonTask + ) + ) + } let binDir = outputDir.appending(path: "bin") let binDirTask = make.addTask( @@ -779,6 +908,7 @@ struct PackagingPlanner { file: file, output: output, outputDirTask: outputDirTask, + wasmImportsTask: wasmImportsTask, inputFiles: [], inputTasks: [binDirTask] ) @@ -797,9 +927,9 @@ struct PackagingPlanner { file: String, output: String, outputDirTask: MiniMake.TaskKey, + wasmImportsTask: MiniMake.TaskKey, inputFiles: [BuildPath], - inputTasks: [MiniMake.TaskKey], - wasmImportsPath: BuildPath? = nil + inputTasks: [MiniMake.TaskKey] ) -> MiniMake.TaskKey { struct Salt: Encodable { @@ -808,9 +938,10 @@ struct PackagingPlanner { } let inputPath = selfPackageDir.appending(path: file) - let conditions: [String: Bool] = [ - "USE_SHARED_MEMORY": Self.isSharedMemoryEnabled(triple: triple), - "IS_WASI": triple.hasPrefix("wasm32-unknown-wasi"), + // NOTE: The conditions derived from the .wasm binary are not part of the salt because + // they are not known until the imports are parsed. The imports file is an input of + // this task instead, so a change in them still re-runs the preprocessing. + let staticConditions: [String: Bool] = [ "USE_WASI_CDN": options.useCDN, "HAS_BRIDGE": skeletons.count > 0, "HAS_IMPORTS": skeletons.count > 0, @@ -821,30 +952,26 @@ struct PackagingPlanner { "PACKAGE_TO_JS_MODULE_PATH": wasmFilename, "PACKAGE_TO_JS_PACKAGE_NAME": options.packageName ?? packageId.lowercased(), ] - let salt = Salt(conditions: conditions, substitutions: constantSubstitutions) + let salt = Salt(conditions: staticConditions, substitutions: constantSubstitutions) + let wasmImportsPath = self.wasmImportsPath return make.addTask( - inputFiles: [selfPath, inputPath] + inputFiles, - inputTasks: [outputDirTask] + inputTasks, + inputFiles: [selfPath, inputPath, wasmImportsPath] + inputFiles, + inputTasks: [outputDirTask, wasmImportsTask] + inputTasks, output: outputDir.appending(path: output), salt: salt ) { var substitutions = constantSubstitutions + let features = try Self.loadWasmFeatures(at: $1.resolve(path: wasmImportsPath)) - if let wasmImportsPath = wasmImportsPath { - let wasmImportsPath = $1.resolve(path: wasmImportsPath) - let importEntries = try JSONDecoder().decode( - [ImportEntry].self, - from: Data(contentsOf: wasmImportsPath) - ) - let memoryImport = importEntries.first { - $0.module == "env" && $0.name == "memory" - } - if case .memory(let type) = memoryImport?.kind { - substitutions["PACKAGE_TO_JS_MEMORY_INITIAL"] = type.minimum.description - substitutions["PACKAGE_TO_JS_MEMORY_MAXIMUM"] = (type.maximum ?? type.minimum).description - substitutions["PACKAGE_TO_JS_MEMORY_SHARED"] = type.shared.description - } + var conditions = staticConditions + conditions["USE_SHARED_MEMORY"] = features.sharedMemory + conditions["IS_WASI"] = features.isWASI + + if let memory = features.importedMemory { + substitutions["PACKAGE_TO_JS_MEMORY_INITIAL"] = memory.minimum.description + substitutions["PACKAGE_TO_JS_MEMORY_MAXIMUM"] = (memory.maximum ?? memory.minimum).description + substitutions["PACKAGE_TO_JS_MEMORY_SHARED"] = memory.shared.description } let inputPath = $1.resolve(path: inputPath) @@ -855,8 +982,38 @@ struct PackagingPlanner { } } - private static func isSharedMemoryEnabled(triple: String) -> Bool { - return triple == "wasm32-unknown-wasip1-threads" + /// The path to the JSON file describing the imports of the product .wasm file + var wasmImportsPath: BuildPath { + intermediatesDir.appending(path: "wasm-imports.json") + } + + static func loadWasmFeatures(at wasmImportsPath: URL) throws -> WasmFeatures { + let importEntries = try JSONDecoder().decode( + [ImportEntry].self, + from: Data(contentsOf: wasmImportsPath) + ) + return WasmFeatures(imports: importEntries) + } +} + +/// The traits of a .wasm binary that affect the JavaScript code generated for it +struct WasmFeatures { + /// Whether the module requires a WASI implementation to be instantiated + let isWASI: Bool + /// Whether the module uses shared memory + let sharedMemory: Bool + /// The type of the memory imported by the module if any + let importedMemory: MemoryType? + + init(imports: [ImportEntry]) { + self.isWASI = imports.contains { $0.module == "wasi_snapshot_preview1" } + let memoryImport = imports.first { $0.module == "env" && $0.name == "memory" } + if case .memory(let type) = memoryImport?.kind { + self.importedMemory = type + } else { + self.importedMemory = nil + } + self.sharedMemory = self.importedMemory?.shared ?? false } } diff --git a/Plugins/PackageToJS/Sources/PackageToJSPlugin.swift b/Plugins/PackageToJS/Sources/PackageToJSPlugin.swift index cc16de20a..560b3e980 100644 --- a/Plugins/PackageToJS/Sources/PackageToJSPlugin.swift +++ b/Plugins/PackageToJS/Sources/PackageToJSPlugin.swift @@ -8,7 +8,17 @@ @preconcurrency import struct Foundation.CocoaError @preconcurrency import func Foundation.fputs @preconcurrency import func Foundation.exit -@preconcurrency import var Foundation.stderr + +#if canImport(Darwin) +@preconcurrency import var Darwin.stderr +#elseif canImport(Glibc) +@preconcurrency import var Glibc.stderr +#elseif canImport(Musl) +@preconcurrency import var Musl.stderr +#elseif canImport(Android) +@preconcurrency import var Android.stderr +#endif + import PackagePlugin /// The main entry point for the PackageToJS plugin. @@ -264,69 +274,202 @@ struct PackageToJSPlugin: CommandPlugin { let skeletonCollector = SkeletonCollector(context: context) let skeletons = skeletonCollector.collectFromTests() - // NOTE: Find the product artifact from the default build directory + // NOTE: Find the product artifact(s) from the default build directory // because PackageManager.BuildResult doesn't include the // product artifact for tests. // This doesn't work when `--scratch-path` is used but // we don't have a way to guess the correct path. (we can find // the path by building a dummy executable product but it's // not worth the overhead) - var productArtifact: URL? - for fileExtension in ["wasm", "xctest"] { - let packageDir = context.package.directoryURL - let path = packageDir.appending(path: ".build/debug/\(productName).\(fileExtension)").path - if FileManager.default.fileExists(atPath: path) { - productArtifact = URL(fileURLWithPath: path) - break - } - } - guard let productArtifact = productArtifact else { - throw PackageToJSError( - "Failed to find '\(productName).wasm' or '\(productName).xctest'" - ) - } - let outputDir = + let productArtifacts = try findTestProductArtifacts( + productName: productName, + context: context, + options: testOptions.packageOptions + ) + + let baseOutputDir = if let outputPath = testOptions.packageOptions.outputPath { URL(fileURLWithPath: outputPath) } else { context.pluginWorkDirectoryURL.appending(path: "PackageTests") } - var make = MiniMake( - explain: testOptions.packageOptions.explain, - printProgress: self.printProgress - ) - let planner = PackagingPlanner( - options: testOptions.packageOptions, - context: context, - selfPackage: selfPackage, - skeletons: skeletons, - outputDir: outputDir, - wasmProductArtifact: productArtifact, - // If the product artifact doesn't have a .wasm extension, add it - // to deliver it with the correct MIME type when serving the test - // files for browser tests. - wasmFilename: productArtifact.lastPathComponent.hasSuffix(".wasm") - ? productArtifact.lastPathComponent - : productArtifact.lastPathComponent + ".wasm" - ) - let (rootTask, binDir) = try planner.planTestBuild( - make: &make - ) - cleanIfBuildGraphChanged(root: rootTask, make: make, context: context) - print("Packaging tests...") - let scope = MiniMake.VariableScope(variables: [:]) - try make.build(output: rootTask, scope: scope) - print("Packaging tests finished") - if !testOptions.buildOnly { - let testRunner = scope.resolve(path: binDir.appending(path: "test.js")) - try PackageToJS.runTest( - testRunner: testRunner, - currentDirectoryURL: context.pluginWorkDirectoryURL, + // With multiple runners, package what they share into the base directory once: the + // test harness's npm dependencies, and the glue describing every test target that + // preludes import by a fixed path. Each runner is packaged into a subdirectory of + // it. + let hasSharedArtifacts = productArtifacts.count > 1 + if hasSharedArtifacts, let firstArtifact = productArtifacts.first { + var make = MiniMake( + explain: testOptions.packageOptions.explain, + printProgress: self.printProgress + ) + let planner = PackagingPlanner( + options: testOptions.packageOptions, + context: context, + selfPackage: selfPackage, + skeletons: skeletons, + outputDir: baseOutputDir, + wasmProductArtifact: firstArtifact, + wasmFilename: firstArtifact.lastPathComponent.hasSuffix(".wasm") + ? firstArtifact.lastPathComponent + : firstArtifact.lastPathComponent + ".wasm" + ) + let rootTask = try planner.planSharedTestArtifacts(make: &make) + print("Packaging shared test artifacts...") + try make.build(output: rootTask, scope: MiniMake.VariableScope(variables: [:])) + } + + // The native build system links every test target into a single combined + // `PackageTests` binary, but SwiftBuild produces one runner per test + // target. Package and run each artifact. When there is more than one, give each its + // own output subdirectory and build fingerprint so their harnesses don't clobber one + // another, and keep going after a failure so every target's results are reported. + var anyTestFailed = false + for productArtifact in productArtifacts { + let runnerName = productArtifact.deletingPathExtension().lastPathComponent + let outputDir = + productArtifacts.count == 1 + ? baseOutputDir + : baseOutputDir.appending(path: runnerName) + + var make = MiniMake( + explain: testOptions.packageOptions.explain, + printProgress: self.printProgress + ) + let planner = PackagingPlanner( + options: testOptions.packageOptions, + context: context, + selfPackage: selfPackage, + // Generate the glue from what this binary actually links in: the combined + // binary holds every test target, while a per-target runner holds one. + skeletons: runnerSkeletons( + runnerName: runnerName, + isCombinedBinary: !hasSharedArtifacts, + context: context, + aggregated: skeletons + ), outputDir: outputDir, - testOptions: testOptions + wasmProductArtifact: productArtifact, + // If the product artifact doesn't have a .wasm extension, add it + // to deliver it with the correct MIME type when serving the test + // files for browser tests. + wasmFilename: productArtifact.lastPathComponent.hasSuffix(".wasm") + ? productArtifact.lastPathComponent + : productArtifact.lastPathComponent + ".wasm" + ) + let (rootTask, binDir) = try planner.planTestBuild( + make: &make, + installNodeModules: !hasSharedArtifacts ) + cleanIfBuildGraphChanged( + root: rootTask, + make: make, + context: context, + fingerprintName: productArtifacts.count == 1 ? "minimake.json" : "minimake-\(runnerName).json" + ) + if productArtifacts.count == 1 { + print("Packaging tests...") + } else { + print("Packaging tests for '\(runnerName)'...") + } + let scope = MiniMake.VariableScope(variables: [:]) + try make.build(output: rootTask, scope: scope) + print("Packaging tests finished") + + if !testOptions.buildOnly { + let testRunner = scope.resolve(path: binDir.appending(path: "test.js")) + do { + try PackageToJS.runTest( + testRunner: testRunner, + currentDirectoryURL: context.pluginWorkDirectoryURL, + outputDir: outputDir, + testOptions: testOptions + ) + } catch { + // Keep running the remaining test runners, but remember the failure so + // the overall command still exits non-zero. + printStderr("\(runnerName): \(error)") + anyTestFailed = true + } + } } + + if anyTestFailed { + exit(1) + } + } + + /// The skeletons describing the API a single test binary exposes. + /// + /// The native build system links every test target into one binary, so it gets the + /// skeletons of all of them. SwiftBuild produces a `-test-runner` per test + /// target, which only exposes that target and its dependencies. + private func runnerSkeletons( + runnerName: String, + isCombinedBinary: Bool, + context: PluginContext, + aggregated: [BridgeJSSkeletonInput] + ) -> [BridgeJSSkeletonInput] { + let testRunnerSuffix = "-test-runner" + guard !isCombinedBinary, runnerName.hasSuffix(testRunnerSuffix) else { + return aggregated + } + let targetName = String(runnerName.dropLast(testRunnerSuffix.count)) + return SkeletonCollector(context: context).collectFromTest(targetName: targetName) + } + + /// Locate the test product artifact(s) to run. + /// + /// The native build system links all test targets into a single combined + /// `PackageTests` binary. SwiftBuild instead emits one + /// `-test-runner.wasm` per test target and only an aggregate + /// orchestration product, so fall back to discovering those runners. + private func findTestProductArtifacts( + productName: String, + context: PluginContext, + options: PackageToJS.PackageOptions + ) throws -> [URL] { + let fileManager = FileManager.default + let packageDir = context.package.directoryURL + let configuration = (options.configuration ?? "debug").lowercased() + + // Native combined test binary. + for fileExtension in ["wasm", "xctest"] { + let path = packageDir.appending(path: ".build/\(configuration)/\(productName).\(fileExtension)").path + if fileManager.fileExists(atPath: path) { + return [URL(fileURLWithPath: path)] + } + } + + // SwiftBuild per-test-target runners: + // .build/out/Products/-webassembly-wasm32/-test-runner.wasm + let productsDir = packageDir.appending(path: ".build/out/Products") + if let configDirs = try? fileManager.contentsOfDirectory( + at: productsDir, + includingPropertiesForKeys: nil + ) { + let wasmConfigDirs = configDirs.filter { $0.lastPathComponent.hasSuffix("-webassembly-wasm32") } + let chosenDir = + wasmConfigDirs.first { $0.lastPathComponent.lowercased().hasPrefix(configuration) } + ?? wasmConfigDirs.first + if let chosenDir, + let entries = try? fileManager.contentsOfDirectory(at: chosenDir, includingPropertiesForKeys: nil) + { + let runners = + entries + .filter { $0.lastPathComponent.hasSuffix("-test-runner.wasm") } + .sorted { $0.lastPathComponent < $1.lastPathComponent } + if !runners.isEmpty { + return runners + } + } + } + + throw PackageToJSError( + "Failed to find '\(productName).wasm' or '\(productName).xctest' (native build system), " + + "or any '*-test-runner.wasm' under .build/out/Products (swiftbuild build system)" + ) } private func buildWasm( @@ -414,9 +557,10 @@ struct PackageToJSPlugin: CommandPlugin { private func cleanIfBuildGraphChanged( root: MiniMake.TaskKey, make: MiniMake, - context: PluginContext + context: PluginContext, + fingerprintName: String = "minimake.json" ) { - let buildFingerprint = context.pluginWorkDirectoryURL.appending(path: "minimake.json") + let buildFingerprint = context.pluginWorkDirectoryURL.appending(path: fingerprintName) let lastBuildFingerprint = try? Data(contentsOf: buildFingerprint) let currentBuildFingerprint = try? make.computeFingerprint(root: root) if lastBuildFingerprint != currentBuildFingerprint { @@ -721,16 +865,28 @@ class SkeletonCollector { } func collectFromTests() -> [BridgeJSSkeletonInput] { - let tests = context.package.targets.filter { - guard let target = $0 as? SwiftSourceModuleTarget else { return false } - return target.kind == .test - } - for test in tests { + for test in testTargets { visit(target: test, package: context.package) } return skeletons } + /// Collect the skeletons of a single test target and everything it links in. + func collectFromTest(targetName: String) -> [BridgeJSSkeletonInput] { + guard let test = testTargets.first(where: { $0.name == targetName }) else { + return [] + } + visit(target: test, package: context.package) + return skeletons + } + + private var testTargets: [Target] { + context.package.targets.filter { + guard let target = $0 as? SwiftSourceModuleTarget else { return false } + return target.kind == .test + } + } + private func visit(product: Product, package: Package) { if visitedProducts.contains(product.id) { return } visitedProducts.insert(product.id) @@ -799,7 +955,7 @@ extension PackagingPlanner { wasmFilename: String ) { let outputBaseName = outputDir.lastPathComponent - let (configuration, triple) = PackageToJS.deriveBuildConfiguration(wasmProductArtifact: wasmProductArtifact) + let configuration = PackageToJS.deriveBuildConfiguration(wasmProductArtifact: wasmProductArtifact) let system = DefaultPackagingSystem(printWarning: printStderr, which: which(_:)) self.init( options: options, @@ -813,7 +969,6 @@ extension PackagingPlanner { wasmProductArtifact: BuildPath(absolute: wasmProductArtifact.path), wasmFilename: wasmFilename, configuration: configuration, - triple: triple, system: system ) } diff --git a/Plugins/PackageToJS/Sources/ParseWasm.swift b/Plugins/PackageToJS/Sources/ParseWasm.swift index 4372b32c5..31cd4a692 100644 --- a/Plugins/PackageToJS/Sources/ParseWasm.swift +++ b/Plugins/PackageToJS/Sources/ParseWasm.swift @@ -186,27 +186,29 @@ func parseImports(moduleBytes: Data) throws -> [ImportEntry] { let name = try parseState.readName() let type = try parseState.readByte() + let kind: ImportEntry.ImportKind switch type { case 0x00: // Function let index = try parseState.readUnsignedLEB128() guard index < UInt32(types.count) else { throw ParseError.unexpectedEndOfData } + kind = .function case 0x01: // Table _ = try parseTableType(parseState) + kind = .table case 0x02: // Memory - let limits = try parseLimits(parseState) - imports.append( - ImportEntry(module: module, name: name, kind: .memory(type: limits)) - ) + kind = .memory(type: try parseLimits(parseState)) case 0x03: // Global _ = try parseGlobalType(parseState) + kind = .global default: throw ParseError.unknownImportDescriptorType(type) } + imports.append(ImportEntry(module: module, name: name, kind: kind)) } // Skip the rest of the module return imports diff --git a/Plugins/PackageToJS/Tests/PackagingPlannerTests.swift b/Plugins/PackageToJS/Tests/PackagingPlannerTests.swift index 12187a201..4cff48e6c 100644 --- a/Plugins/PackageToJS/Tests/PackagingPlannerTests.swift +++ b/Plugins/PackageToJS/Tests/PackagingPlannerTests.swift @@ -76,7 +76,6 @@ import Testing wasmProductArtifact: BuildPath(prefix: "WASM_PRODUCT_ARTIFACT"), wasmFilename: "main.wasm", configuration: configuration, - triple: "wasm32-unknown-wasi", selfPath: BuildPath(prefix: "PLANNER_SOURCE_PATH"), system: system ) @@ -106,7 +105,6 @@ import Testing wasmProductArtifact: BuildPath(prefix: "WASM_PRODUCT_ARTIFACT"), wasmFilename: "main.wasm", configuration: "debug", - triple: "wasm32-unknown-wasi", selfPath: BuildPath(prefix: "PLANNER_SOURCE_PATH"), system: system ) @@ -172,7 +170,6 @@ import Testing wasmProductArtifact: BuildPath(absolute: wasm.path), wasmFilename: "main.wasm", configuration: "debug", - triple: "wasm32-unknown-wasi", selfPath: BuildPath(absolute: plannerSource.path), system: system ) @@ -266,7 +263,6 @@ import Testing wasmProductArtifact: BuildPath(absolute: wasm.path), wasmFilename: "main.wasm", configuration: "debug", - triple: "wasm32-unknown-wasi", selfPath: BuildPath(absolute: plannerSource.path), system: system ) @@ -345,7 +341,6 @@ import Testing wasmProductArtifact: BuildPath(absolute: wasm.path), wasmFilename: "main.wasm", configuration: "debug", - triple: "wasm32-unknown-wasi", selfPath: BuildPath(absolute: plannerSource.path), system: system ) @@ -370,3 +365,57 @@ import Testing } } } + +@Suite struct WasmFeaturesTests { + private func memoryImport(shared: Bool) -> ImportEntry { + ImportEntry( + module: "env", + name: "memory", + kind: .memory(type: MemoryType(minimum: 17, maximum: 65536, shared: shared, index: .i32)) + ) + } + + @Test func noImports() { + let features = WasmFeatures(imports: []) + #expect(features.isWASI == false) + #expect(features.sharedMemory == false) + #expect(features.importedMemory == nil) + } + + @Test func wasiImport() { + let features = WasmFeatures(imports: [ + ImportEntry(module: "wasi_snapshot_preview1", name: "proc_exit", kind: .function) + ]) + #expect(features.isWASI == true) + #expect(features.sharedMemory == false) + } + + @Test func unsharedMemoryImport() { + let features = WasmFeatures(imports: [memoryImport(shared: false)]) + #expect(features.sharedMemory == false) + #expect(features.importedMemory?.minimum == 17) + } + + @Test func sharedMemoryImport() { + let features = WasmFeatures(imports: [ + memoryImport(shared: true), + ImportEntry(module: "wasi", name: "thread-spawn", kind: .function), + ]) + #expect(features.sharedMemory == true) + #expect(features.isWASI == false) + } + + /// Only the memory imported as "env.memory" is the one instantiated by the generated + /// JavaScript, so a memory imported under another name must not be picked up. + @Test func otherMemoryImport() { + let features = WasmFeatures(imports: [ + ImportEntry( + module: "other", + name: "memory", + kind: .memory(type: MemoryType(minimum: 1, maximum: nil, shared: true, index: .i32)) + ) + ]) + #expect(features.sharedMemory == false) + #expect(features.importedMemory == nil) + } +} diff --git a/Plugins/PackageToJS/Tests/ParseWasmTests.swift b/Plugins/PackageToJS/Tests/ParseWasmTests.swift new file mode 100644 index 000000000..7da67b6d6 --- /dev/null +++ b/Plugins/PackageToJS/Tests/ParseWasmTests.swift @@ -0,0 +1,52 @@ +import Foundation +import Testing + +@testable import PackageToJS + +@Suite struct ParseWasmTests { + /// A module importing `wasi_snapshot_preview1.proc_exit`, `env.memory` and `env.__stack_pointer` + private var moduleBytes: Data { + var bytes: [UInt8] = [ + 0x00, 0x61, 0x73, 0x6D, // magic + 0x01, 0x00, 0x00, 0x00, // version + ] + // Type section: [(i32) -> ()] + let typeSection: [UInt8] = [0x01, 0x60, 0x01, 0x7F, 0x00] + bytes += [0x01, UInt8(typeSection.count)] + typeSection + + var importSection: [UInt8] = [0x03] // 3 imports + func name(_ value: String) -> [UInt8] { + [UInt8(value.utf8.count)] + Array(value.utf8) + } + importSection += name("wasi_snapshot_preview1") + name("proc_exit") + [0x00, 0x00] + importSection += name("env") + name("memory") + [0x02, 0x00, 0x11] + importSection += name("env") + name("__stack_pointer") + [0x03, 0x7F, 0x01] + bytes += [0x02, UInt8(importSection.count)] + importSection + + return Data(bytes) + } + + @Test func parseAllImportKinds() throws { + let imports = try parseImports(moduleBytes: moduleBytes) + #expect(imports.count == 3) + #expect(imports[0].module == "wasi_snapshot_preview1") + #expect(imports[0].name == "proc_exit") + if case .function = imports[0].kind { + } else { + Issue.record("expected a function import, got \(imports[0].kind)") + } + #expect(imports[2].name == "__stack_pointer") + if case .global = imports[2].kind { + } else { + Issue.record("expected a global import, got \(imports[2].kind)") + } + } + + /// WASI is detected by the imported functions, so they must not be dropped while parsing. + @Test func deriveFeaturesFromParsedImports() throws { + let features = WasmFeatures(imports: try parseImports(moduleBytes: moduleBytes)) + #expect(features.isWASI == true) + #expect(features.sharedMemory == false) + #expect(features.importedMemory?.minimum == 17) + } +} diff --git a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_debug.json b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_debug.json index 49cee1f90..fefcda9b2 100644 --- a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_debug.json +++ b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_debug.json @@ -17,13 +17,11 @@ ], "inputs" : [ "$PLANNER_SOURCE_PATH", - "$OUTPUT\/main.wasm" + "$WASM_PRODUCT_ARTIFACT" ], "output" : "$INTERMEDIATES\/wasm-imports.json", "wants" : [ - "$OUTPUT", - "$INTERMEDIATES", - "$OUTPUT\/main.wasm" + "$INTERMEDIATES" ] }, { @@ -48,11 +46,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -65,11 +63,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -82,11 +80,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -99,11 +97,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -125,12 +123,14 @@ ], "inputs" : [ "$PLANNER_SOURCE_PATH", - "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/package.json" + "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/package.json", + "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/package.json", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ - "$OUTPUT" + "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json" ] }, { @@ -155,11 +155,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -172,11 +172,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -189,11 +189,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.worker.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -206,11 +206,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -223,11 +223,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -240,11 +240,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -257,11 +257,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { diff --git a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release.json b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release.json index 6b1e1090c..32fc2b670 100644 --- a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release.json +++ b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release.json @@ -31,13 +31,11 @@ ], "inputs" : [ "$PLANNER_SOURCE_PATH", - "$OUTPUT\/main.wasm" + "$WASM_PRODUCT_ARTIFACT" ], "output" : "$INTERMEDIATES\/wasm-imports.json", "wants" : [ - "$OUTPUT", - "$INTERMEDIATES", - "$OUTPUT\/main.wasm" + "$INTERMEDIATES" ] }, { @@ -62,11 +60,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -79,11 +77,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -96,11 +94,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -113,11 +111,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -140,12 +138,14 @@ ], "inputs" : [ "$PLANNER_SOURCE_PATH", - "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/package.json" + "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/package.json", + "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/package.json", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ - "$OUTPUT" + "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json" ] }, { @@ -170,11 +170,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -187,11 +187,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -204,11 +204,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.worker.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -221,11 +221,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -238,11 +238,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -255,11 +255,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -272,11 +272,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { diff --git a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release_dwarf.json b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release_dwarf.json index 49cee1f90..fefcda9b2 100644 --- a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release_dwarf.json +++ b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release_dwarf.json @@ -17,13 +17,11 @@ ], "inputs" : [ "$PLANNER_SOURCE_PATH", - "$OUTPUT\/main.wasm" + "$WASM_PRODUCT_ARTIFACT" ], "output" : "$INTERMEDIATES\/wasm-imports.json", "wants" : [ - "$OUTPUT", - "$INTERMEDIATES", - "$OUTPUT\/main.wasm" + "$INTERMEDIATES" ] }, { @@ -48,11 +46,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -65,11 +63,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -82,11 +80,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -99,11 +97,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -125,12 +123,14 @@ ], "inputs" : [ "$PLANNER_SOURCE_PATH", - "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/package.json" + "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/package.json", + "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/package.json", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ - "$OUTPUT" + "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json" ] }, { @@ -155,11 +155,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -172,11 +172,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -189,11 +189,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.worker.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -206,11 +206,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -223,11 +223,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -240,11 +240,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -257,11 +257,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { diff --git a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release_name.json b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release_name.json index 6b1e1090c..32fc2b670 100644 --- a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release_name.json +++ b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release_name.json @@ -31,13 +31,11 @@ ], "inputs" : [ "$PLANNER_SOURCE_PATH", - "$OUTPUT\/main.wasm" + "$WASM_PRODUCT_ARTIFACT" ], "output" : "$INTERMEDIATES\/wasm-imports.json", "wants" : [ - "$OUTPUT", - "$INTERMEDIATES", - "$OUTPUT\/main.wasm" + "$INTERMEDIATES" ] }, { @@ -62,11 +60,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -79,11 +77,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -96,11 +94,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -113,11 +111,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -140,12 +138,14 @@ ], "inputs" : [ "$PLANNER_SOURCE_PATH", - "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/package.json" + "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/package.json", + "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/package.json", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ - "$OUTPUT" + "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json" ] }, { @@ -170,11 +170,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -187,11 +187,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -204,11 +204,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.worker.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -221,11 +221,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -238,11 +238,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -255,11 +255,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -272,11 +272,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { diff --git a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release_no_optimize.json b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release_no_optimize.json index 49cee1f90..fefcda9b2 100644 --- a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release_no_optimize.json +++ b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planBuild_release_no_optimize.json @@ -17,13 +17,11 @@ ], "inputs" : [ "$PLANNER_SOURCE_PATH", - "$OUTPUT\/main.wasm" + "$WASM_PRODUCT_ARTIFACT" ], "output" : "$INTERMEDIATES\/wasm-imports.json", "wants" : [ - "$OUTPUT", - "$INTERMEDIATES", - "$OUTPUT\/main.wasm" + "$INTERMEDIATES" ] }, { @@ -48,11 +46,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -65,11 +63,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -82,11 +80,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -99,11 +97,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -125,12 +123,14 @@ ], "inputs" : [ "$PLANNER_SOURCE_PATH", - "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/package.json" + "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/package.json", + "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/package.json", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ - "$OUTPUT" + "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json" ] }, { @@ -155,11 +155,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -172,11 +172,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -189,11 +189,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.worker.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -206,11 +206,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -223,11 +223,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -240,11 +240,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -257,11 +257,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { diff --git a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planTestBuild.json b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planTestBuild.json index 5f16f6e8e..b6b382ae3 100644 --- a/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planTestBuild.json +++ b/Plugins/PackageToJS/Tests/__Snapshots__/PackagingPlannerTests/planTestBuild.json @@ -31,13 +31,11 @@ ], "inputs" : [ "$PLANNER_SOURCE_PATH", - "$OUTPUT\/main.wasm" + "$WASM_PRODUCT_ARTIFACT" ], "output" : "$INTERMEDIATES\/wasm-imports.json", "wants" : [ - "$OUTPUT", - "$INTERMEDIATES", - "$OUTPUT\/main.wasm" + "$INTERMEDIATES" ] }, { @@ -70,12 +68,14 @@ ], "inputs" : [ "$PLANNER_SOURCE_PATH", - "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/bin\/test.js" + "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/bin\/test.js", + "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/bin\/test.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json", "$OUTPUT\/bin" ] }, @@ -89,11 +89,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -106,11 +106,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/index.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -123,11 +123,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -140,11 +140,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/instantiate.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -166,12 +166,14 @@ ], "inputs" : [ "$PLANNER_SOURCE_PATH", - "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/package.json" + "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/package.json", + "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/package.json", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ - "$OUTPUT" + "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json" ] }, { @@ -196,11 +198,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -213,11 +215,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -230,11 +232,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/browser.worker.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -247,11 +249,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -264,11 +266,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/platforms\/node.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -281,11 +283,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -298,11 +300,11 @@ "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/runtime.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", - "$OUTPUT\/platforms", - "$INTERMEDIATES\/wasm-imports.json" + "$INTERMEDIATES\/wasm-imports.json", + "$OUTPUT\/platforms" ] }, { @@ -311,12 +313,14 @@ ], "inputs" : [ "$PLANNER_SOURCE_PATH", - "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/test.browser.html" + "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/test.browser.html", + "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/test.browser.html", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json", "$OUTPUT\/bin" ] }, @@ -326,12 +330,14 @@ ], "inputs" : [ "$PLANNER_SOURCE_PATH", - "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/test.d.ts" + "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/test.d.ts", + "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/test.d.ts", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json", "$OUTPUT\/bin" ] }, @@ -341,12 +347,14 @@ ], "inputs" : [ "$PLANNER_SOURCE_PATH", - "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/test.js" + "$SELF_PACKAGE\/Plugins\/PackageToJS\/Templates\/test.js", + "$INTERMEDIATES\/wasm-imports.json" ], "output" : "$OUTPUT\/test.js", - "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIklTX1dBU0kiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfU0hBUkVEX01FTU9SWSI6ZmFsc2UsIlVTRV9XQVNJX0NETiI6ZmFsc2V9LCJzdWJzdGl0dXRpb25zIjp7IlBBQ0tBR0VfVE9fSlNfTU9EVUxFX1BBVEgiOiJtYWluLndhc20iLCJQQUNLQUdFX1RPX0pTX1BBQ0tBR0VfTkFNRSI6InRlc3QifX0=", + "salt" : "eyJjb25kaXRpb25zIjp7IkhBU19CUklER0UiOmZhbHNlLCJIQVNfSU1QT1JUUyI6ZmFsc2UsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX0JST1dTRVIiOnRydWUsIlRBUkdFVF9ERUZBVUxUX1BMQVRGT1JNX05PREUiOmZhbHNlLCJVU0VfV0FTSV9DRE4iOmZhbHNlfSwic3Vic3RpdHV0aW9ucyI6eyJQQUNLQUdFX1RPX0pTX01PRFVMRV9QQVRIIjoibWFpbi53YXNtIiwiUEFDS0FHRV9UT19KU19QQUNLQUdFX05BTUUiOiJ0ZXN0In19", "wants" : [ "$OUTPUT", + "$INTERMEDIATES\/wasm-imports.json", "$OUTPUT\/bin" ] },